Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg.

& Tech

TOPIC 1

1.1 INTRODUCTION TO SQL

The Structured Query Language (SQL) comprises one of the


fundamental building blocks of modern database architecture. SQL defines
the methods used to create and manipulate relational databases on all major
platforms.

SQL comes in many flavors. Oracle databases utilize their proprietary


PL/SQL. Microsoft SQL Server makes use of Transact-SQL. However, all of
these variations are based upon the industry standard ANSI SQL.

SQL commands can be divided into two main sublanguages.

1. Data Definition Language


2. Data Manipulation Language

1.2 DATA DEFINITION LANGUAGE (DDL)

It contains the commands used to create and destroy databases and


database objects. These commands will primarily be used by database
administrators during the setup and removal phases of a database project.

DDL Commands :

a) Create table command :

Syntax

CREATE TABLE table_name


(
column_name1 data_type(size),
column_name2 data_type(size),
.......
)

Example 1

This example demonstrates how you can create a table named "Person",
with four columns. The column names will be "LastName", "FirstName",
"Address", and "Age":

CREATE TABLE Person


( LastName varchar,

SQL Lab Manual- ANB 1


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

FirstName varchar,
Address varchar,
Age int )

This example demonstrates how you can specify a maximum length for
some columns:

Example 2

CREATE TABLE Person


(
LastName varchar(30),
FirstName varchar,
Address varchar,
Age int(3)
)

Creating table from another ( existing table ) table :

Syntax

CREATE TABLE tablename


[(columnname,columnaname)]]
AS SELECT columnname,columnaname
FROM tablename;

b. Alter table command :

Once table is created within a database, we may wish to modify the


definition of that table.The ALTER command allows to make changes to the
structure of a table without deleting and recreating it.

Syntax

ALTER TABLE table_name


ADD (newcolumn_name1 data_type(size),
newcolumn_name2 data_type(size),
.......)

Example

ALTER TABLE personal_info


ADD salary money null

SQL Lab Manual- ANB 2


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

This example adds a new attribute to the personal_info table -- an


employee's salary. The "money" argument specifies that an employee's
salary will be stored using a dollars and cents format. Finally, the "null"
keyword tells the database that it's OK for this field to contain no value for
any given employee.

c. Drop table command :

DROP command allows us to remove entire database objects from our


DBMS. For example, if we want to permanently remove the personal_info
table that we created, we'd use the following command:

Syntax

DROP TABLE table_name;

Example

DROP TABLE personal_info;

1.3 DATA MANIPULATION LANGUAGE(DML) :

After the database structure is defined with DDL, database administrators


and users can utilize the Data Manipulation Language to insert, retrieve and
modify the data contained within it.

a. INSERT COMMAND :

The INSERT command in SQL is used to add records to an existing table.

Format 1:-Inserting a single row of data into a table

Syntax

INSERT INTO table_name


[(columnname,columnname)]
VALUES (expression,expression);

To add a new employee to the personal_info table

SQL Lab Manual- ANB 3


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example

INSERT INTO personal_info


values('bart','simpson',12345,$45000)

Format 2 : Inserting data into a table from another table

Syntax

INSERT INTO tablename


SELECT columnname,columnname
FROM tablename

b. SELECT COMMAND :

The SELECT command is the most commonly used command in SQL.


It allows database users to retrieve the specific information they desire from
an operational database.

Syntax

SELECT A1,A2……..
FROM tablename
WHERE predicate

A1,A2 is the list of attributes and predicate is the condition which must
be satisfied by the resulting rows .

Example 1

It displays list of all last names in personal_info table

SELECT last_name
FROM personal_info

The command shown below retrieves all of the information contained within
the personal_info table. The asterisk is used as a wildcard in SQL. This
means "Select everything from the personal_info table."

SQL Lab Manual- ANB 4


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example 2

SELECT *
FROM personal_info

Finally, the WHERE clause can be used to limit the records that are retrieved
to those that meet specified criteria. The CEO might be interested in
reviewing the personnel records of all highly paid employees. The following
command retrieves all of the data contained within personal_info for records
that have a salary value greater than $50,000 :

Example 3

SELECT * FROM personal_info


WHERE salary > $50000

c. UPDATE COMMAND :

The UPDATE command can be used to modify information contained within a


table.

Syntax

UPDATE tablename
SET columnname=expression,columnname=expression,…..
WHERE columnname=expression;

Each year,company gives all employees a 3% cost-of-living increase in


their salary. The following SQL command could be used to quickly apply this
to all of the employees stored in the database :

Example

UPDATE personal_info
SET salary=salary*1.03

d. DELETE COMMAND :

The DELETE command can be used to delete information contained within a


table.

SQL Lab Manual- ANB 5


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Syntax

DELETE FROM tablename


WHERE search condition

The DELETE command with a WHERE clause can be used to remove his
record from the personal_info table:

Example

DELETE FROM personal_info


WHERE employee_id=12345

The following command deletes all the rows from the table

Example

DELETE FROM personal_info;

SQL Lab Manual- ANB 6


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 2

2.1 DATA INTEGRITY :

Enforcing data integrity ensures the quality of the data in the


database. For example, if an employee is entered with an employee_id
value of “123”, the database should not allow another employee to have an
ID with the same value.
Two important steps in planning tables are to identify valid values for a
column and to decide how to enforce the integrity of the data in the column.
Data integrity falls into four categories:

 Entity integrity
 Domain integrity
 Referential integrity
 User-defined integrity

There are several ways of enforcing each type of integrity.

Integrity type Recommended options

Entity PRIMARY KEY constraint


UNIQUE constraint

Domain FOREIGN KEY constraint


CHECK constraint
NOT NULL
Referential FOREIGN KEY constraint
CHECK constraint
User-defined All column- and table-level constraints in CREATE
TABLE
StoredProcedures
Triggers

ENTITY INTEGRITY :

Entity integrity defines a row as a unique entity for a particular table. Entity
integrity enforces the integrity of the identifier column(s) or the primary key
of a table (through indexes, UNIQUE constraints, PRIMARY KEY constraints,
or IDENTITY properties).

SQL Lab Manual- ANB 7


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

DOMAIN INTEGRITY :

Domain integrity is the validity of entries for a given column. You can
enforce domain integrity by restricting the type (through data types), the
format (through CHECK constraints and rules), or the range of possible
values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT
definitions, NOT NULL definitions, and rules).

REFERENTIAL INTEGRITY :

Referential integrity preserves the defined relationships between tables when


records are entered or deleted. In Microsoft® SQL Server™, referential
integrity is based on relationships between foreign keys and primary keys or
between foreign keys and unique keys. Referential integrity ensures that key
values are consistent across tables. Such consistency requires that there be
no references to nonexistent values and that if a key value changes, all
references to it change consistently throughout the database.

a. PRIMARY KEY CONSTRAINT :

Definition:- The primary key of a relational table uniquely identifies each


record in the table.

A primary key constraint ensures no duplicate values are entered in


particular columns and that NULL values are not entered in those columns.

b. NOT NULL CONSTRAINT :

This constraint ensures that NULL values are not entered in those
columns.

c. UNIQUE CONSTRAINT :

This constraint ensures that no duplicate values are entered in those


columns.

d. CHECK CONSTRAINT :

The CHECK constraint enforces column value restrictions. Such


constraints can restrict a column, for example, to a set of values, only
positive numbers, or reasonable dates.

SQL Lab Manual- ANB 8


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

e. FOREIGN KEY CONSTRAINT:

Foreign keys constrain data based on columns in other tables. They


are called foreign keys because the constraints are foreign--that is, outside
the table. For example, suppose a table contains customer addresses, and
part of each address is a United States two-character state code. If a table
held all valid state codes, a foreign key constraint could be created to
prevent a user from entering invalid state codes.

To create a table with different types of constraints:

Syntax

CREATE TABLE table_name


(
column_name1 data_type [constraint],
column_name2 data_type [constraint],
.......
)

Example

Create table customer


( customer-name char(20) not null,
customer-street char(30),
customer-city char(30),
primary key ( customer-name));

create table branch


( branch-name char(15) not null,
branch-city char(30),
assets number,
primary key ( branch-name));

create table account


( branch-name char(15),
account-number char(10) not null,
balance number,
primary key ( account-number),
foreign key ( branch-name) references branch,
check (balance>500));

SQL Lab Manual- ANB 9


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

create table depositor


( customer-name char(20) not null,
account-number char(10) not null,
primary key ( customer-name,account-number),
foreign key ( account-number) references account,
foreign key ( customer-name) references customer);

SQL Lab Manual- ANB 10


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 3
3.1 JOINS :
Sometimes we have to select data from two or more tables to make
our result complete. We have to perform a join. Tables in a database can be
related to each other with keys.
In the "Employees" table below, the "Employee_ID" column is the primary
key, meaning that no two rows can have the same Employee_ID. The
Employee_ID distinguishes two persons even if they have the same name.

 The "Employee_ID" column is the primary key of the "Employees"


table
 The "Prod_ID" column is the primary key of the "Orders" table
 The "Employee_ID" column in the "Orders" table is used to refer to the
persons in the "Employees" table without using their names

Employees :

Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari

Orders :

Prod_ID Product Employee_ID


234 Printer 01
657 Table 03
865 Chair 03

Referring to Two Tables


We can select data from two tables by referring to two tables, like this:

Example

Who has ordered a product, and what did they order?

SQL Lab Manual- ANB 11


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

SELECT Employees.Name, Orders.Product


FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Using Joins
OR we can select data from two tables with the JOIN keyword, like this:

3.2 INNER JOIN :

The INNER JOIN returns all rows from both tables where there is a
match. If there are rows in Employees that do not have matches in Orders,
those rows will not be listed.

Example 1

SELECT field1, field2, field3


FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

Example 2

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product


FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

SQL Lab Manual- ANB 12


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

3.3 LEFT OUTER JOIN :

The LEFT JOIN returns all the rows from the first table (Employees),
even if there are no matches in the second table (Orders). If there are rows
in Employees that do not have matches in Orders, those rows also will be
listed.

Syntax :

SELECT field1, field2, field3


FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

Example :

List all employees, and their orders - if any.

SELECT Employees.Name, Orders.Product


FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

Result

Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari

3.4 RIGHT OUTER JOIN :

The RIGHT JOIN returns all the rows from the second table
(Orders), even if there are no matches in the first table (Employees). If
there had been any rows in Orders that did not have matches in Employees,
those rows also would have been listed.

Syntax :

SQL Lab Manual- ANB 13


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

SELECT field1, field2, field3


FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield

Example :

List all orders, and who has ordered - if any.

SELECT Employees.Name, Orders.Product


FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

SQL Lab Manual- ANB 14


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 4

4.1 AGGREGATE FUNCTIONS :

If we want to summarize our data to produce top-level reports (For


example, the purchasing manager may not be interested in a listing of all
widget sales, but may simply want to know the number of widgets sold this
month ) , SQL provides aggregate functions to assist with the
summarization of large volumes of data.

OrderID FirstName LastName Quantity UnitPrice Continent


122 John Jacob 21 4.52 North America
923 Ralph Wiggum 192 3.99 North America
238 Ryan Johnson 87 4.49 Africa
829 Mary Smith 842 2.99 North America
824 Elizabeth Marks 48 3.48 Africa
753 James Linea 9 7.85 North America
942 Alan Jonas 638 3.29 Europe

1. SUM :

It is used within a SELECT statement and, predictably, returns the


summation of a series of values. If the widget project manager wanted to
know the total number of widgets sold to date, we could use the following
query:

Example :

SELECT SUM(QUANTITY) AS TOTAL


FROM WidgetOrders

Result :

Total
-----------
1837

SQL Lab Manual- ANB 15


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

2. AVG :

The AVG (average) function works in a similar manner to provide the


mathematical average of a series of values. To find out the average amount
of all orders placed on the North American continent.

Example :

SELECT AVG(UnitPrice*Quantity) as AveragePrice


FROM WidgetOrders
WHERE Continent = “North America”

3. COUNT :

SQL provides the COUNT function to retrieve the number of records in


a table that meet given criteria. We can use the COUNT(*) syntax alone to
retrieve the number of rows in a table. Alternatively, a WHERE clause can
be included to restrict the counting to specific records.

Example :

SELECT COUNT(*) AS 'Number of Large Orders'


FROM WidgetOrders
WHERE Quantity > 100

Above query displays how many orders are processed by company that
requested over 100 widgets.

4. MAX AND MIN :

SQL provides Min and Max functions to locate the records containing
the smallest and largest values for a given expression

The MAX() function returns the largest value in a given data series. We can
provide the function with a field name to return the largest value for a given
field in a table.To find the order in our database that produced the most
revenue for the company,following query will be used:

Example :

SELECT MAX(Quantity*UnitPrice) as ‘largest order’


SQL Lab Manual- ANB 16
MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

FROM WidgetOrders

The MIN() function functions in the same manner, but returns the minimum
value for the expression.

SQL Lab Manual- ANB 17


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 5

5.1 NUMERIC FUNCTIONS :

They are used for performing various operations on numbers.

1. ABS :

Returns the absolute, positive value of the given numeric


expression.

ABS ( numeric_expression )

Example :

SELECT abs(-15.0)
FROM dual

Result: 15

2. POWER :

Returns the value of the given expression to the specified


power.

POWER ( numeric_expression , y )

Example :

SELECT power(3,2)
FROM dual

Result :

3. ROUND :

Returns a numeric expression, rounded to the specified length or


precision

ROUND ( numeric_expression , length [ , function ] )

SQL Lab Manual- ANB 18


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example :

SELECT round(15.133,1)
FROM dual

Result: 15.1

4. SQRT : |

Returns the square root of the given expression.

SQRT ( float_expression )

Example :

SELECT sqrt(49)
FROM dual

Result : 7

5. EXP :

Returns the exponential value of the given float expression.

EXP ( float_expression )

Example :

SELECT exp(4)
FROM dual

Result : 54.59815

6. LOG :

Returns the natural logarithm of the given float expression.

SQL Lab Manual- ANB 19


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

LOG ( base,no )

Example :

SELECT log(10,100)
FROM dual

Result : 2

7. COS :

A mathematic function that returns the trigonometric cosine of


the given angle (in radians) in the given expression.

COS ( float_expression )

Example :

SELECT cos(0)
FROM dual

Result: 1

8. SIN :

Returns the trigonometric sine of the given angle (in radians) in


an approximate numeric (float) expression.

SIN ( float_expression )

Example :

SELECT sin(0)

SQL Lab Manual- ANB 20


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

FROM dual

Result: 0

9. TAN :

Returns the tangent of the input expression

TAN ( float_expression )

Example :

SELECT tan(0)
FROM dual

Result: 0

10. SIGN :

Returns the positive (+1), zero (0), or negative (-1) sign of the
given expression

SIGN ( numeric_expression)

Example :

SELECT sign(-15)
FROM dual

Result : -1

5.2 CHARACTER FUNCTIONS :

1 LOWER :

Returns a character expression after converting uppercase


character data to lowercase.

LOWER ( character_expression )

SQL Lab Manual- ANB 21


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example :

SELECT lower(‘DYPIET’)
FROM dual

Result: dypiet

2. UPPER :

Returns a character expression with lowercase character data


converted to uppercase.

UPPER ( character_expression )

Example :

SELECT upper(‘dypiet’)
FROM dual

Result: DYPIET

3. REPLACE :

Replaces all occurrences of the second given string expression in


the first string expression with a third expression.

REPLACE ( 'string_expression1' , 'string_expression2', ,'string_expression3'


)

Example :

SELECT replace(‘scott’,’s’,’boy’)
FROM dual;

Result: boycott

SQL Lab Manual- ANB 22


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

4. SUBSTRING :

Returns part of a character, binary, text, or image


expression.

SUBSTRING ( expression , start , length )

Example :

SELECT substr(‘daisy’,2,3)
FROM dual;

Result: AIS

5. LENGTH :

Returns the number of characters, rather than the number of


bytes, of the given string expression, excluding trailing blanks.

LENGTH(string_expression)

Example :

SELECT length(‘daisy’)
FROM dual;

Result: 5

6. CONCATENATION :

Returns joined character expressions.

Example :

SELECT ‘mit’ || ‘aoe’


FROM dual;

Result: mitaoe

SQL Lab Manual- ANB 23


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

7. INITCAP :

Changes the first character of the string to upper case.

INITCAP(string_expression)

Example :

SELECT initcap(‘college’)
FROM dual;

Result: College

8. USER :

Returns the name of the current user.

Example :

SELECT user
FROM dual;

Result: SCOTT

5.3 DATE FUNCTIONS:

1. ADD_MONTHS :

Returns date after adding the number of months specified with


function.

ADD_MONTHS(date,no. of months)

Example :

SELECT add_months(’20-nov-04’,3)
FROM dual;

SQL Lab Manual- ANB 24


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Result: 20-FEB-05

2. LAST_DAY :

Returns the last date of the month.

LAST_DAY(date)

Example :

SELECT last_day(’20-nov-04’)
FROM dual;

Result:30-NOV-04

3. MONTHS_BETWEEN :

Returns no of months between two parameters.

MONTHS_BETWEEN(date,date)

Example :

SELECT months_between(’20-feb-05’,’20-nov-04’)
FROM dual;

Result:3

4. NEXT_DAY :

Returns the date of the first weekday named by ‘char’ that is


after date.

NEXT_DAY (date,char);

Example :

SELECT next_day(’16-nov-04’,’sunday’)
FROM dual;

Result:21-NOV-04

SQL Lab Manual- ANB 25


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

5. ALTER SESSION
6.
7. :

Changes the format of the date

Alter session set nls_date_format = ‘ date format ‘;

Example :

Alter session
set nls_date_format = ’DD.MM.YYYY’;

5.4 CONVERSION FUNCTIONS :

Conversion functions convert a value from one datatype to


another.

1. TO_DATE :

Converts character value representing date into a date value according


to format specified.

TO_DATE(‘character’[,fmt])

Example :

SELECT TO_DATE(’3004SEP04’,’DD-MON-YYYY’)
FROM dual;

Result:30-SEP-04

2. TO_CHAR :

Converts character value representing date into a date value according


to format specified.

TO_CHAR(date,format)

SQL Lab Manual- ANB 26


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example :

SELECT TO_CHAR(sysdate,’mon dd yy’)


FROM dual;

Result: sep 3 04

3. TO_NUMBER :

The to_number function converts a string to a number.

TO_NUMBER (string1, [format], [nls_language])

string1 is the string that will be converted to a number.

format is optional. This is the format that will be used to convert string1 to
a number.

Example :

SELECT to_number ('1210.73', '9999.99')


FROM dual;

Result: 1210.73

SQL Lab Manual- ANB 27


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 6

1. UNION :

The UNION query allows to combine the result sets of 2 or more "select"
queries. It removes duplicate rows between the various "select"
statements.Each SQL statement within the UNION query must have the
same number of fields in the result sets with similar data types.

Syntax :

select field1, field2, … field_n


from tables
UNION
select field1, field2, … field_n
from tables;

Example :

Select supplier_id
from suppliers
UNION
select supplier_id
from orders;

2. UNION ALL :

The UNION ALL query allows to combine the result sets of 2 or


more "select" queries. It returns all rows (even if the row exists in
more than one of the "select" statements)i.e.it does not remove
duplicates.

Example :

Select supplier_id
from suppliers
UNION ALL
select supplier_id
from orders;

3. INTERSECT : The INTERSECT query allows to return the results of 2 or


more "select" queries. However, it only returns the rows selected by all
queries. If a record exists in one query and not in the other, it will be

SQL Lab Manual- ANB 28


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

omitted from the INTERSECT results.Each SQL statement within the


INTERSECT query must have the same number of fields in the result sets
with similar data types.

Syntax

select field1, field2, … field_n


from tables
INTERSECT
select field1, field2, … field_n
from tables;

Example :

select supplier_id
from suppliers
INTERSECT
select supplier_id
from orders;

4. MINUS :

The MINUS query returns all rows in the first query that are not
returned in the second query.Each SQL statement within the MINUS query
must have the same number of fields in the result sets with similar data
types.

Syntax

select field1, field2, … field_n


from tables
MINUS
select field1, field2, … field_n
from tables;

Example :
Select supplier_id
from suppliers
MINUS
select supplier_id
from orders;

SQL Lab Manual- ANB 29


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 7

7.1. DATA CONTROL LANGUAGE :

Data control commands in SQL allow you to control access to


data within the database. These DCL commands are normally used to
create objects related to user access and also control the distribution
of privileges among users. Some data control commands are as
follows:

GRANT
REVOKE

1. GRANT :
The objects created by one user are accessible to another user only
when the owner gives permission by using Grant statement.

Syntax

GRANT {object privileges}


ON objectname
TO username
[WITH GRANT OPTION]

Various Types of Object privileges :


a. Alter
b. Delete
c. Index
d. Insert
e. Select
f. Update
With grant option allows the grantee to grant object privileges
to other users.

Example :

GRANT select,update
ON stud
TO scott

SQL Lab Manual- ANB 30


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

2. REVOKE :

Once permissions are granted, it often proves necessary to revoke


them at a later date. SQL provides REVOKE command to remove previously
granted permissions.

Syntax

REVOKE {object privileges}


ON object_name FROM username

REVOKE select,update
ON stud
FROM scott

7.2 TRANSACTIONAL CONTROL COMMANDS :

These commands allow the user to manage database


transactions.Some of those are as

 COMMIT
 ROLLBACK

1. COMMIT :

The COMMIT statement in SQL marks the final step in the processing
of a database transaction.It makes permanent any changes made during
that transaction.

COMMIT;

2. ROLLBACK :

The ROLLBACK statement in SQL cancels the proposed changes in a


pending database transaction. It is exactly opposite to commit.It undoes the
changes made during the transaction.

ROLLBACK;

SQL Lab Manual- ANB 31


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 8

8.1 VIEWS :

Database views allow to create "virtual tables" that are generated on


the fly when they are accessed. A view is stored on the database server as
an SQL statement that pulls data from one or more tables and (optionally)
performs transformations on that data. Users may then query the view just
as they would any real database table.

Creation of Views :

Syntax
CREATE VIEW viewname AS
SELECT columnname, columnname
FROM tablename
WHERE columnname=expression list;

Example 1
CREATE VIEW vstud AS
SELECT name,no
FROM stud;

View vstud will contain two columns name and no.

Renaming the columns of a view:-

CREATE VIEW vstud1(name,number) AS


SELECT name,no
FROM stud;

View vstud1 will contain two columns name and number.

8.2 RESTRICTIONS ON VIEW :

1. The view must be created on a single table.


2. Primary key column of the table must be included in the view.
3. Aggregate functions, distinct keyword, group by clause and having
can’t be included in select statement.

SQL Lab Manual- ANB 32


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

TOPIC 9

9.1 LIKE CONDITION :

The LIKE condition allows to use wildcards in the where clause of an


SQL statement. This allows to perform pattern matching. The LIKE
condition can be used in any valid SQL statement - select, insert, update, or
delete.

The patterns that can be chosen are:

 % allows to match any string of any length (including zero


length)
 allows to match on a single character

Example 1

To find all of the suppliers whose name begins with ‘H’.

SELECT *FROM supplier


WHERE supplier_name like 'H%';

Example 2

To find suppliers whose name does not start with 'T'.

SELECT *FROM supplier


WHERE supplier_name not like 'T%';

Example 3

To find all suppliers whose name is 5 characters long, where the first two
characters is 'Sm' and the last two characters is 'th'.

SELECT *FROM supplier


WHERE supplier_name like 'Sm_th';

SQL Lab Manual- ANB 33


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

9.2 IN CONDITION :

The IN function helps to reduce the need to use multiple OR


conditions.

SELECT columns
FROM tables
WHERE column1 in (value1, value2, .... value_n);

This SQL statement will return the records where column1 is value1,
value2..., or value_n. The IN function can be used in any valid SQL
statement - select, insert, update, or delete.

Example 1

SELECT *
FROM supplier
WHERE supplier_name in ( 'IBM' , 'Hewlett Packard', 'Microsoft');

This would return all rows where the supplier_name is either IBM, Hewlett
Packard, or Microsoft.

Example 2

SELECT *
FROM supplier
WHERE supplier_name not in ( 'IBM' , 'Hewlett Packard',
'Microsoft');

This would return all rows where the supplier_name is neither IBM,
Hewlett Packard, or Microsoft.

9.3 BETWEEN CONDITION :

The BETWEEN condition allows to retrieve values within a range.

SELECT columns
FROM tables
WHERE column1 between value1 and value2;

This SQL statement will return the records where column1 is within the
range of value1 and value2 (inclusive).

SQL Lab Manual- ANB 34


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Example 1

SELECT *
FROM suppliers
WHERE supplier_id between 5000 AND 5010;

This would return all rows where the supplier_id is between 1000 and
5010, inclusive.

Example 2
SELECT *
FROM orders
WHERE order_date between to_date ('2003/01/01', 'yyyy/mm/dd')
AND to_date ('2003/12/31', 'yyyy/mm/dd);

This SQL statement would return all orders where the order_date is
between Jan 1, 2003 and Dec 31, 2003 (inclusive).

Example 3
SELECT *
FROM suppliers
WHERE supplier_id not between 5000 and 5500;

9.4 EXISTS CONDITION :

The EXISTS condition is considered "to be met" if the subquery returns


at least one row.

SELECT columns
FROM tables
WHERE EXISTS ( subquery );

Example

SELECT *
FROM suppliers
WHERE EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);

SQL Lab Manual- ANB 35


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

This select statement will return all records from the suppliers table
where there is at least one record in the orders table with the same
supplier_id.

Example
SELECT *
FROM suppliers
WHERE NOT EXISTS
(select *
from orders
where suppliers.supplier_id = orders.supplier_id);

This will return all records from the suppliers table where there are no
records in the orders table for the given supplier_id.

9.5) GROUP BY CLAUSE:-

The GROUP BY clause can be used in a SELECT statement to collect


data across multiple records and group the results by one or more columns.

SELECT column1, column2, ... column_n, aggregate_function


(expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n;

aggregate_function can be a function such as sum,count,min,max.

Example

To return the name of the department and the total sales (in the associated
department).

Example

SELECT department, SUM (sales) as "Total sales"


FROM order_details
GROUP BY department;

SQL Lab Manual- ANB 36


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

9.6 HAVING CLAUSE :

The HAVING clause is used in combination with the GROUP BY clause.


It can be used in a SELECT statement to filter the records that a GROUP BY
returns.

Syntax

SELECT column1, column2, ... column_n,


aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;

aggregate_function can be a function such as sum,count,max,min

Example

To return the name of the department and the total sales (in the
associated department). The HAVING clause will filter the results so that
only departments with sales greater than $1000 will be returned.

Example

SELECT department, SUM (sales) as "Total sales"


FROM order_details
GROUP BY department
HAVING SUM (sales) > 1000;

9.7) ORDER BY CLAUSE:-

The ORDER BY clause allows you to sort the records in your result set.
The ORDER BY clause can only be used in SELECT statements. The ORDER
BY clause sorts the result set based on the columns specified. If the ASC or
DESC value is omitted, the system assumed ascending order.

SQL Lab Manual- ANB 37


MIT Academy of Engineering, Alaldi(D), Pune School of Computer Engg. & Tech

Syntax

SELECT columns
FROM tables
WHERE predicates
ORDER BY column ASC/DESC;

ASC indicates ascending order. (default)


DESC indicates descending order.

Example 1

SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city;

This would return all records sorted by the supplier_city field in


ascending order.

Example 2

SELECT supplier_city
FROM supplier
WHERE supplier_name = 'IBM'
ORDER BY supplier_city DESC;

This would return all records sorted by the supplier_city field in descending
order.

SQL Lab Manual- ANB 38

You might also like