You are on page 1of 13

STRUCTURED QUERY LANGUAGE

It is a non procedural language


Its is used with relational data base
The sub languages of SQL are

DDL(data definition language)


DML(data manipulation language)
DCL(data control language)

Each category contains some specific commands

DDL commands:
CREATE,ALTER,RENAME,DROP.

CREATE:
It is used to create relations (tables)
SYNTAX:
CREATE TABLE table name
( column name data type (size) ,
column name data type(size) [column constraint],
……………
…………..
[table constraint]);

example:
CREATE TABLE sailors
(sid number(3),
sname varchar2(20),
rating number(2),
age number(2),
primary key(sid) );

ALTER:
It is used to alter (modify and add column width and column respectively) the definition
of relation
SYNTAX:
ALTER TABLE table name MODIFY(column name data type (size)…..);
ALTER TABLE table name ADD((new)column name data type (size)…..);
Examples:
ALTER TABLE sailors MODIFY(sid number(4));
ALTER TABLE sailors ADD(mobileno number(10));
RENAME:
It is used to change the name of table
SYNTAX:
RENAME old name TO new name
Example:
RENAME sailors TO sailors_pacific

DROP:
Its is used to remove a table and its whole data
SYNTAX:
DROP TABLE table name
Example:
DROP TABLE sailors_pacific

DML COMMANDS

INSERT, UPDATE, DELETE, SELECT

INSERT:
It is used to insert the values into a relation (table)
SYNTAX:
INSERT INTO table name[(column names)] VALUES(column_values)
Example:
INSERT INTO sailors VALUES(103,’lubber’,8,35);

UPDATE:
Its is used to update a columns value
SYNTAX:
UPDATE table name SET column name=value, SET column name=value
WHERE condition;
Example:
UPDATE sailors SET sname=’rusty’ WHERE sno=103;

DELETE:
It is used to delete the tuples (rows) from a relation(table)
SYNTAX:
DELETE FROM table name WHERE condition
Example:
DELETE FROM sailors WHERE sno=103
SELECT:
It is used to display the data of tables
SYNTAX:

SELECT column name,[ column name…..]


FROM tablename,[tablename…]
[WHERE condition]

example:
SELECT * FROM sailors;
SELECT sid, rating FROM sailors ;
SELECT sid, rating FROM sailors WHERE sno=103;

Data integrity constraints


NOTNULL
UNIQUE
CHECK
PRIMARY KEY
FOREIGN KEY (referential constraint)

NOTNULL:
It specifies that a column cannot contain a ‘null’ values

Example:
CREATE TABLE emp
( empno number(4) NOT NULL,
ename varchar 2(20),……..);

UNIQUE:
It specifies that no two rows in the table can have same value for unique key(i.e. a
column(s) designated as unique)

Example:
CREATE TABLE dept
( deptno number(2),
dname varchar 2(9) CONSTRAINT unq_name UNIQUE,
loc varchar2(10) );

CREATE TABLE client


( fname varchar2(20),
l_name varchar2(20),
city varchar2(10),
state varchar2(10),
CONSTRAINTclient_uniqUNIQUE(city,state));

PRIMARY KEY:
It specifies that a column(s) designated as primary key should follow 2 conditions
1. no primary key value can appear in more than one row in the table(unique)
2. no column that is part of the primary key can contain a null(no null)
a table can have only one primary key

SYNTAX:
CREATE TABLE table_name
(col1 datatype(size)[constraint] PRIMARY KEY
……………. );

examples:
CREATE TABLE dept
(deptno number(2) CONSTRAINT pk_dept PRIMARY KEY,
dname varchar2(5),…….);

CREATE TABLE ship_cont


(shipno number(2),
containerno char(7),
status char(1),
CONSTRAINT ship_cont_pk PRIMARY KEY(shipno,containerno);
);

FOREIGN KEY(referential integrity):


A referential integrity constraint designates a column or combination of columns as a
foreign key and establishes a relationship between that foreign key and a specified
primary or unique key called the referenced key. In this relationship the table containing
the foreign key is called as child table and the table containing the referenced key is
called the parent table.
Foreign key constraint is defined in the child table.

Example:
CREATE TABLE emp(
Empno number(4),
Ename varchar2(10),
Job varchar2(5),
Mgr number(4),
Hiredate date,
Deptno number(2) CONSTRAINT fk_deptno REFERENCES dept(deptno) ON DELETE
CASCADE );
Because of the ON DELETE CASCADE option any deletion of a deptno value in the
dept table to the deptno values ,then its dependents rows of the emp table also deleted

CHECK:
It specifies a condition on a column

Example:
CREATE TABLE dept
(deptno number (2) CONSTRAINT check_deptno CHECK(deptno BETWEEN 10 AND
99),
dname varchar2(10),……………..);

ORDER BY :
It is used to display the data in an order i.e. ascending or descending

SYNTAX:
ORDER BY column name [asc][desc]
Example:
SELECT * FROM emp ORDER BY salary
SELECT * FROM emp ORDER BY ename ASC ,salary DESC

OPERATORS:

BETWEEN ..AND..
Used to select a range of values
Example:
SELECT * FROM emp WHERE salary BETWEEN 1000 AND 2000

LIKE:
Used to find a pattern
% matches any string of character
_ matches any single character

example:
SELECT * FROM emp WHERE ename LIKE ‘SA%’
SELECT * FROM emp WHERE ename LIKE ‘____’

IS NULL
Used to find the rows whos values is NULL
Example:
SELECT * FROM emp WHERE mgr IS NULL
SET COMPARISION OPERATORS:
IN,ANY,ALL,NOT IN,EXISTS

IN:
It is used to compare any number of operators
Example:
SELECT * FROM emp WHERE job IN (‘CLERK’,’ANALYST’);
SELECT * FROM emp WHERE deptno IN (10,20);

NOT IN :
It is used inverse to the IN operator

ANY:
Compares a value to each value returned by a list or a sub query
Example:
SELECT * FROM emp WHERE sal = ANY (SELECT sal FROM emp WHERE
deptno=30);

ALL:
Compares a value to every(all) values returned by a list or sub query
Example:
SELECT * FROM emp WHERE sal >ALL (SELECT sal FROM emp WHERE
deptno=30);

EXITSTS:
It returns true if the answer of a sub query is contains

SELECT * FROM emp WHERE EXISTS (SELECT sal FROM emp WHERE
deptno=30);

AGGREGATE FUNCTIONS OR GROUP FUNCTIONS

AVG, COUNT, MAX, MIN, SUM

SELECT AVG(sal) FROM emp WHERE deptno=20;


SELECT MIN(sal) FROM emp WHERE deptno=20;
SELECT MAX(sal) FROM emp WHERE deptno=20;
SELECT SUM(sal) FROM emp WHERE deptno=20;
SELECT COUNT(sal) FROM emp WHERE deptno=20;
GROUP BY:
If we want to get the average salary department wise we need to run query per
department, but if we don’t know the department numbers then we can use this GROUP
BY clause.

SELECT deptno, AVG(sal) FROM emp GROUP BY deptno;

HAVING :
Using this we can pose the conditions on grups .to get the count of employees group by
department no that each department contains atleast 4 employees.

SELECT deptno,count(ename) FROM emp GROUP BY deptno HAVING COUNT(*)>3

SET OPERATORS:
UNION , INTERSECTION, MINUS(EXCEPT)
We can apply these operators on two or more queries.
These operators works when both the table are union compatible(i.e. no of fileds and data
types of the fields must be same for both tables)
UNION :
It returns all distinct rows returned by both queries
Example:
//list the employees whose salary is equal to that of SCOTT or WARD
Select * from emp where sal in (select sal from emp where ename=’scott’)
UNION
(select sal from emp where ename=’scott’);

//list the employees whose salary is equal to that of SCOTT and WARD

select * from emp where sal in(select sal from emp where enamae=’scott’)
INTERSECTION
(select sal from emp where ename=’ward’);

//list the employees whose salary is equal to the SCOTT but not to WARD

select * from emp where sal in (select sal from emp where ename=’scott’)
MINUS
(select sal from emp where ename=’ward’);
create table sailors(sid number(3),sname varchar2(20),rating
number(2),age number(2), primary key(sid));

create table boats( bid number(3),bname varchar2(15), color


varchar2(10), primary key(bid));

create table reserves(sid number(3),bid number(3), day


date, primary key(sid,bid),foreign key(sid) references
sailors,foreign key(bid) references boats);

insert into sailors values(22,'dustin',7,45)


insert into sailors values(29,'brutus',1,33)
insert into sailors values(31,'lubber',8,55)
insert into sailors values(32,'andy',8,25)
insert into sailors values(58,'rusty',10,35)
insert into sailors values(64,'horatio’,'7',35)
insert into sailors values(71,'zorba',10,16)
insert into sailors values(74,'horatio',9,35)
insert into sailors values(85,'art',3,25)
insert into sailors values(95,'bob',3,63)

insert into boats values(101,'interlake','blue');


insert into boats values(102,'interlake','red');
insert into boats values(103,'clipper','green');
insert into boats values(104,'marine','red');
Sailors, Reserves, and Boats,.

Sailors table data:


Sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
Figure 4.15 An Instance of Sailors

Reserves table data:


sid bid day
22 101 10/10/98
22 102 10/10/98
22 103 10/8/98
22 104 10/7/98
31 102 11/10/98
31 103 11/6/98
31 104 11/12/98
64 101 9/5/98
64 102 9/8/98
74 103 9/8/98
Figure 4.16 An Instance of Reserves

Boats table data


bid bname color
101 Interlake blue
102 Interlake red
103 Clipper green
104 Marine red
Figure 4.17 An Instance of Boats
SQL EXAMPLE QUERIES:

1. find the names and ages of all sailors


ans. Select distinct sname, age from sailors
2. find all sailors with a rating above 7
ans. Select sid, sname , rating, age from sailors where rating > 7
3. find the sailors who have reserved boat no 103
ans. Select s.sname from sailors s, reserves r where s.sid=r.sid and r.bid=103
4. find the sids of sailors who have reserved a red boat
ans. Select r.sid from boats b, reserves r where b.bid=r.bid and b.color=’red’;
5. find the names of sailors who have reserved a red boat
ans. Select s.sname from sailors s, reserves r, boats b
where s.sid=r.sid and r.bid=b.bid and b.color=’red’

6. find the colors of boats reserved by lubber


ans. Select b.color from sailors s, reserves r, boats b
where s.sid=r.sid and r.bid=b.bid and s.sname=’lubber’

7. find the names of sailors who have reserved at least one boat
ans. Select s.sname from sailors s, reserves r where s.sid=r.sid

8. compute the increments for the ratings of persons who have sailed 2 different
boats on the same day
ans. Select s.sname, s.rating+1 as rating from sailors s, reserves r1, reserves r2
where s.sid=r1.sid and s.sid=r2.sid and r1.day=r2.day and r1.bid!=r2.bid;

9. find the ages of sailors whose name begins and ends with B and has at least 3
characters.
Ans. Select age from sailors where sname like ‘B_%B’

UNION, INTERSECTION AND EXCEPT

10. find the names of sailors who have reserved a red or green boat.
Ans. Select s.sname from sailors s, reserves r, boats b
Where s.sid=r.sid and r.bid=b.bid and b.color=’red’
Union
Select s2.sname from sailors s2, reserves r2, boats b2
Where s2.sid=r2.sid and r2.bid=b2.bid and b2.color=’green’

11. find the names of sailors who have reserved a red and a green boat
ans. Select s.sname from sailors s, reserves r, boats b
Where s.sid=r.sid and r.bid=b.bid and b.color=’red’
Intersection
Select s2.sname from sailors s2, reserves r2, boats b2
Where s2.sid=r2.sid and r2.bid=b2.bid and b2.color=’green’
12. find the names of sailors who have reserved red boats but not green boats
ans. Select s.sname from sailors s, reserves r, boats b
Where s.sid=r.sid and r.bid=b.bid and b.color=’red’
except
Select s2.sname from sailors s2, reserves r2, boats b2
Where s2.sid=r2.sid and r2.bid=b2.bid and b2.color=’green’

13. find all sids of sailors who have a rating 10 or reserved boats 104.
Ans. Select sid from sailors where rating = 10
Union select sid from reserves where bid=104;

NESTED QUERIES :

14. find the names of sailors who have reserved boat 103
ans. Select s.sname from sailors s where s.sid in (select r.sid from reserves r where
r.bid=103)

15. find the names f sailors who have reserved a red boat
ans. Select s.sname from sailors s where in
(select r.sid from reserves r where r.bid in
(select bid from boats b where b.color=’red’);

16. find the names of sailors who have not reserved a red boat
ans. Select s.sname from sailors s where s.sid not in
(select r.sid from reserves r where r.bid in
(select bid from boats b where b.color=’red’));

CORRELATED NESTED QUERIES

17. find the names of sailors who have reserved boat no 103
ans. Select s.sname from sailors s where exists (select *from
reserves r where r.bid=103 and r.sid=s.sid);

SET COMPARISION OPERATORS

18.find the sailors whose rating is better than some sailor called horatio
ans. Select s.sid from sailors s where s.rating > any ( select s2.rating
from sailors s2 where s2.sname=’horatio’);

19. find the sailors with the highest rating


ans. select s.sid from sailors s where s.rating >=all (select s2.rating from sailors s2)
MORE EXAMPLES ON NESTED QUERIES

20. find the names of sailors who have reserved both a red and green boat
ans. Select s.sname from sailors s, reserves r, boats b
where s.sid=r.sid and r.bid=b.bid and b.color=’red’ and s.sid in(select s2.sid
from sailors s2, reserves r2, boats b2 where s2.sid=r2.sid and r2.bid=b2.bid and
b2.color=’green’)

21. find the names of sailors who have reserved all boats
ans. Select s.sname from sailors s where not exists((select b.bid from boats b) minus
(select r.bid from reserves r where r.sid=s.sid))

AGGREGATE OPERATORS

22. find the average age of sailors


ans. Select avg (age) from sailors

23. find the average age of sailors with a rating of 10


ans. Select avg (age) from sailors where rating =10

24. find the name and age of oldest sailor


ans. Select sname from sailors where age in ( select max(age) from sailors)

25. count the number of sailors


ans. Select count(*) from sailors s

26. count the number of different sailor names


ans. Select count(distinct sname) from sailors

27. find the names of sailors who are older than the oldest sailor with a rating of 10
ans. Select s.sname from sailors s where s.age> ( select max(s2.age) from sailors s2
where s2.rating = 10);

alternative for above query

select s.sname from sailors s where s.age > all (select s2.age from sailors s2
where s2.rating = 10);
GROUP BY and HAVING clauses
28. find the age of the youngest sailor for each rating level
ans. Select rating , min(age) from sailors group by rating

29. find the age of the youngest sailor who is eligible to vote(18 years old) for each
rating level with al least 2 such sailors
ans. Select rating, min(age) minage from sailors
where age >= 18 group by rating having count(*) > 1;

You might also like