Vous êtes sur la page 1sur 85

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.

DESHMUKHI

DBMS Lab Manual

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Company database
Employee table creation:
create table employee(fname varchar2(10),lname varchar2(10),emp_id
varchar2(10),bdate varchar2(10),hdate varchar2(10),desgn varchar2(10),mgr_id
varchar2(10),salary number(10),dept_no varchar2(10));
Name

Null?

FNAME
LNAME
EMP_ID
BDATE
HDATE
DESGN
MGR_ID
SALARY
DEPT_NO

Type
VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(10)
VARCHAR2(10)
NUMBER(10)
VARCHAR2(10)

Inserting values into employee table


insert into employee
values('&fname','&lname','&emp_id','&bdate','&hdate','&desgn','&mgr_id',&salary
,'&dept_no');
select * from employee;
FNAME
shashank
nano
babu
Anand
sreekanth
prashanth
karthik

LNAME
g
t
n
m
t
m
d

EMP_ID
111
112
113
114
115
116
117

BDATE
23mar1959
17oct1989
17aug1989
22may1956
05nov1989
22may1956
02apr1989

HDATE
23mar2007
17oct2007
17aug2007
02jan2006
05nov2005
02may2005
02apr2006

DESGN
xyz1
xyz2
xyz3
xyz4
xyz5
xyz1
xyz3

MGR_ID SALARY DEPT_NO


112
10000 11
112
12000 11
113
12000 13
114
10000 14
113
120000 13
113
13000 12
114
14000 14

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Creating department table

create table department2(dept_name varchar2(10),dept_no


varchar2(10));

desc department2;

Name

Null?

DEPT_NAME
DEPT_NO

Type
VARCHAR2(10)
VARCHAR2(10)

Inserting values into department table


insert into department2 values('&dept_name','&dept_no');
select * from department2;

DEPT_NAME
HR
RESEARCH
MANAGEMENT
devpmt
recovery

DEPT_NO
11
12
13
14
15

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Works_on table creation

create table works_on1(emp_id number(5),proj_no


number(5),hrs number(5));
desc works_on1;
Name

Null?

EMP_ID
PROJ_NO
HRS

Type
NUMBER(5)
NUMBER(5)
NUMBER(5)

inserting values into table


insert into works_on1 values(&emp_id,&proj_no,&hrs);
select *from works_on1;

EMP_ID

PROJ_NO
111
114
116
117

HRS
101
104
105
104

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

10
11
12
8

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Project table creation


create table project1(proj_name varchar2(30),proj_no number(5),proj_loc
varchar2(30),dept_no number(5));

desc project1;
Name

Null?

PROJ_NAME
PROJ_NO
PROJ_LOC
DEPT_NO

Type
VARCHAR2(30)
NUMBER(5)
VARCHAR2(30)
NUMBER(5)

inserting values into table


insert into project1 values('&proj_name',&proj_no,'&proj_loc',&dept_no);

select *from project1


PROJ_NAME
abc1
abc2
abc3
abc4
abc5
abc6

PROJ_NO

PROJ_LOC

DEPT_NO

101 hyd
102 chennai
103 hyd
104 goa
105 banglore
106 jaipur

11
12
12
14
13
15

6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Deptloc table creation


create table deptloc(dept_no number,dept_loc varchar2(30));
desc deptloc;

Name

Null?

DEPT_NO
DEPT_LOC

Type
NUMBER
VARCHAR2(30)

inserting values into table

insert into deptloc values(&dept_no,&dept_loc);


select * from deptloc;

DEPT_NO

DEPT_LOC
11 hyderabad
12 chennai
12 hyderabad
13 bangalore
14 Goa
15 Jaipur

6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Bank database
Creating account table
create table accounts(acc_no number(20),b_name varchar2(20),balance
number(10));
desc accounts;
Name

Null?

ACC_NO
B_NAME
BALANCE

Type
NUMBER(20)
VARCHAR2(20)
NUMBER(10)

Inserting values into accounts table


insert into accounts values(&acc_no,'&b_name',&balance);
select * from accounts;
ACC_NO

B_NAME

BALANCE

101 sb1
102 sb2
201 sb3
215 sb4
217 sb3
222 sb5
305 sb6

500
400
900
700
715
700
350

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Creating customer table


create table customer(cust_name varchar2(20),cust_street varchar2(20),cust_city
varchar2(20));
desc customer;
Name

Null?

CUST_NAME
CUST_STREET
CUST_CITY

Type
VARCHAR2(20)
VARCHAR2(20)
VARCHAR2(20)

Inserting values into customer


insert into customer values('&cust_name','&cust_street','&cust_city');
select * from customer;
CUST_NAME
anand
babu
giri
sreekanth
shashank
pradeep
karthik
kishore
chanu
saleem

CUST_STREET
spring
senator
north
hill
main
alma
north
main
park
putnam

CUST_CITY
jaipur
hyderabad
chennai
delhi
calcutta
goa
chennai
calcutta
jaipur
stanford

10 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Creating loan table


create table loan(loan_no number(20),b_name varchar2(20),amount number(20));
desc loan;
Name

Null?

Type

LOAN_NO
B_NAME
AMOUNT

NUMBER(20)
VARCHAR2(20)
NUMBER(20)

Inserting values into loan table


insert into loan values(&loan_no,'&b_name',&amount);
select * from loan;

LOAN_NO

B_NAME
11 sb6
14 sb1
15 sb2
16 sb2
17 sb1
23 sb5
93 sb4

AMOUNT
900
1500
1500
1300
1000
2000
500

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Creating borrower table


create table borrower(cust_name varchar2(20),loan_no number(20));
desc borrower;
Name
CUST_NAME
LOAN_NO

Null?

Type
VARCHAR2(20)
NUMBER(20)

Inserting values into borrower table


insert into borrower values('&cust_name',&loan_no);
select * from borrower;

CUST_NAME

LOAN_NO

anand
giri
shashank
sreekanth
kishore
karthik
karthik
babu

16
93
15
14
17
11
23
17

8 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

10

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Creating depositors table


create table depositors(cust_name varchar2(20),acc_no number(20));
desc depositors;

Name

Null?

CUST_NAME
ACC_NO

Type
VARCHAR2(20)
NUMBER(20)

Inserting values into depositors table

Insert into depositors values(&cust_name,&acc_no);


Select * from depositors;
CUST_NAME

ACC_NO

shashank
prided
pradeep
kishore
chanu
karthik
saleem

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

102
101
201
217
222
215
305

11

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Creating branch table


create table branch(b_name varchar2(20),b_city varchar2(20),assets number);
desc branch;
Name

Null?

B_NAME
B_CITY
ASSETS

Type
VARCHAR2(20)
VARCHAR2(20)
NUMBER

Inserting values into branch table


insert branch into values('&b_name','&b_city',&assets);
select * from branch;

B_NAME
sb3
sb1
sb4
sb7
sb2
sb8
sb5
sb6

B_CITY
hyderabad
hyderabad
bangalore
chennai
bangalore
mumbai
goa
bangalore

ASSETS
710000
900000
400000
370000
170000
30000
210000
80000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

12

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Sailors_reserves_boats database
Creating reserves table
create table reserves(sid number(20),bid number(20),rdate varchar2(20));
desc reserves;

Name

Null?

SID
BID
RDATE

Type
NUMBER(20)
NUMBER(20)
VARCHAR2(20)

Inserting values into reserves table


insert into reserves values(&sid,&bid,'&rdate');
select * from reserves;
SID

BID
1111
1112
1113
1114
1111

RDATE
101 10-may-09
102 23-mar-89
103 20-mar-06
104 23-mar-00
105 05-nov-89

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

13

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Sailors table creation


create table sailors(sid number(10),sname varchar2(30),srating number(10),sage
number(10));

inserting values into table


insert into sailors values(&sid,'&sname',&srating,&sage);
select *from sailors;
SID

SNAME

SRATING

1111 name1
1112 bob
1113 bhatt
1114 nano

SAGE
7
6
6
9

21
20
18
17

Boats table creation


create table boats(bid number(10),bcolor varchar2(30),bname varchar2(30));

inserting values into table


insert into boats values(&bid,'&bcolor','&bname');
select *from boats;
BID

BCOLOR
101 green
102 white
103 black
104 cream
105 red

BNAME
vamsi
sudeep
giri
sree
krishna

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

14

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Queries on Company database

1. Retrieve the names of all employees, who work for


research department.
Ans:
select e.fname,e.lname from employee e,department2 d
where e.dept_no=d.dept_no and d.dept_name='research';
FNAME

LNAME
PRASHANTH

DEPT_NAME
M RESEARCH

2. For every project located in hyd list the


proj_no,dept_no,dept_mgrs last name.
Ans:
select p.proj_no,p.dept_no,e.lname from project1 p,employee
e where p.dept_no=e.dept_no and p.proj_loc='hyd'
PROJ_NO

DEPT_NO
101
101
103

LNAME
11 g
11 t
12 m

3. Find all employees, who are born in 1950s.


Ans:
select fname,lname from employee where bdate like '%195_'
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

15

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

FNAME

LNAME

shashank
Anand
prashanth

g
m
m

4. Retrieve all employees in dept_no_13 where salary is in


between 11000 and 13000.
Ans:
select fname,lname from employee where dept_no=13 and
salary>11000 and salary<13000
FNAME
babu

LNAME
n

5. Retrieve the names of all employees, who dont have


supervisors.
Ans:
select fname,lname from employee where emp_id in(select
mgr_id from employee);
FNAME
nano
babu
Anand

LNAME
t
n
m

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

16

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

6. Retrieve emp_id of all employees, who work on


proj_no=101,105.
Ans:
select emp_id from works_on where proj_no in(101,105);
EMP_ID
111
116

7.Count the number of distinct salary values in database.


Ans:
select count(distinct salary) from employee;
COUNT(DISTINCTSALARY)
5

8.For each department retrieve the dept_no and the no. of


employees in department and the average salary.
Ans:
select dept_no,count(*),avg(salary) from employee group
by(dept_no);
DEPT_NO
11
12
13

COUNT(*)

AVG(SALARY)
2
1
2

11000
13000
66000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

17

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

14

12000

9.Retrieve the total no. of employees in the company.


Ans:
select count(emp_id) from employee;
COUNT(EMP_ID)
7

10. Retrieve the total no. of employees in research department.


Ans:
select count(*) from employee e,department d where
d.dept_no=e.dept_no and d.dept_name='research'

COUNT(*)
1

11.Retrieve the names of employees whose salary>salary


Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

18

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

of all and employees in dept_no=5.


Ans:
select fname,lname from employee where
salary>all(select salary from employee where
dept_no=5);

FNAME
shashank
nano
babu
Anand
sreekanth
prashanth
karthik

LNAME
g
t
n
m
t
m
d

7 rows selected.

Queries on sailors_reserves_boats database


1.Retrieve all sailors information where age less than 19.
Ans:
select * from sailors where sage>19;
SID

SNAME
1111 name1
1112 bob

SRATING

SAGE
7
6

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

21
20

19

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

2.Find the names of sailors who have reserved boat


number 103.
Ans:
select sname from sailors s,reserves r where s.sid=r.sid
and r.bid=103;
SNAME
bhatt

3.Find sids of sailors id, who have reserved a red boat.


Ans:
select s.sid from sailors s,reserves r,boats b where
s.sid=r.sid and r.bid=b.bid and b.bcolor='red'

SID
1111

4.Find the names of sailors who reserved a red and green


boat
Ans:
select distinct s.sname from sailors s,reserves r,boats
b,boats b1 where s.sid=r.sid and r.bid=b.bid and
b.bcolor='red'

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

20

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SNAME
name1

5. Find the colours of boats reserved by the sailor nano.


Ans:
select b.bcolor from sailors s,reserves r,boats b where
s.sid=r.sid and r.bid=b.bid and s.sname='nano';
BCOLOR
cream

6. Find the names of sailors who reserved at least one


boat.
Ans:
select distinct s.sname from sailors s,reserves r,boats b
where s.sid=r.sid and r.bid=b.bid;

SNAME
bhatt
Bob
name1
nano

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

21

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

7. Find the ages of sailors whose name begins and ends


with b

Ans:

select s.sage from sailors s,reserves r,boats b where


s.sid=r.sid and r.bid=b.bid and s.sname like 'b%b';

SAGE
20

8. Find the names of sailors who have reserved a red or


green boat

Ans:

select distinct s.sname from sailors s,reserves r,boats


b,boats b1 where s.sid=r.sid and r.bid=b.bid and
(b.bcolor='red' or b1.bcolor='green');

SNAME
bhatt
Bob
name1

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

22

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

nano

9.Find the names of sailors who have reserved a red and


green boat
Ans:
select s.sname from sailors s,reserves r,boats b,boats
b1 where s.sid=r.sid and r.bid=b.bid
and b.bcolor='red' and b1.bcolor='green';

SNAME
name1

10.Find the names of sailors who have rating level 9 or


who reserved a boat no 101
Ans:
select s.sid from sailors s where s.srating=9
union
select r.sid from reserves r where r.bid=101;
SID
1111

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

23

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual


1114

11.Find the sailors with highest rating level.


Ans:
select s.sname from sailors s where s.srating=(select
max(s.srating) from sailors s);
SNAME
nano

Queries on bank database


1. Find all loan_nos for loans made at hyd branch, with loan
amount>1000.
Ans:
select loan_no from loan where b_name='sb2'and
amount>1000
LOAN_NO
15
16

2. Find all customers who have a loan from the bank


and find their names and loan_nos.
Ans:
select distinct b.cust_name,b.loan_no from borrower
b, loan l
where b.loan_no=l.loan_no

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

24

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

CUST_NAME

LOAN_NO

karthik
sreekanth
shashank
anand
babu
kishore
karthik
Giri

11
14
15
16
17
17
23
93

8 rows

3. Find the names & loan_nos of all customers who have a loan at branch
SBI.
Ans:
select distinct b.loan_no, b.cust_name
from borrower b, loan l
where b.loan_no=l.loan_no and l.b_name='sb1';

LOAN_NO

CUST_NAME
14 sreekanth
17 babu
17 kishore

4. Find the names of all branches that have assets greater than at least one
branch located in bangalore
Ans:
select b_name from branch1 where assets>(select
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

25

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

min(assets) from branch1 group by(b_city)


having(b_city='banglore');
B_NAME
sb3
sb1
sb4
sb7
sb2
sb8
sb5

7 rows selected.

5. Find the names of all customers where street address includes sub string
main
Ans
select distinct cust_name from customer where
cust_street like '%main%';

CUST_NAME
kishore
shashank

6.Find all customers who have a loan at bangalore


branch in alphabetical order
Ans
Select b.cust_name
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

26

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

from borrower b, loan l,branch1 b1


where b.loan_no=l.loan_no and b1.b_name=l.b_name
and b1.b_city='banglore' order by (b.cust_name);

CUST_NAME
anand
giri
karthik
shashank

6.Find all customers having a loan or account or both


Ans
select cust_name from depositors
UNION
select cust_name from borrower;
CUST_NAME
anand
babu
chanu
giri
karthik
kishore
pradeep
saleem
shashank
sreekanth

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

27

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

10 rows selected.

9. Find all customers who have both loan and account


Ans
select cust_name from depositors
INTERSECT
select cust_name from borrower;
CUST_NAME
karthik
kishore
shashank

10.Find all customers who have an account but not loan


Ans
select cust_name from depositors
MINUS
Select cust_name from borrower;
CUST_NAME
chanu
pradeep
saleem

11.Find the average account balance at branch sb3


Ans
select avg(balance) from accounts where b_name='sb3';
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

28

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

AVG(BALANCE)
807.5

12.Find the average account balance at each branch


Ans
select b_name,avg(balance) from accounts group by(b_name);
B_NAME

AVG(BALANCE)

sb1
sb2
sb3
sb4
sb5
sb6

500
400
807.5
700
700
350

13. Find the number of depositors at each branch


Ans
select b.b_name,count(d.cust_name)
from depositors d,accounts a,branch1 b
where b.b_name=a.b_name and a.acc_no=d.acc_no
group by b.b_name;
B_NAME

COUNT(D.CUST_NAME)

sb1
sb2
sb3
sb4
sb5
sb6

1
1
2
1
1
1

6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

29

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

AGREEGATE FUNCTIONS
SQL>create table acc_mstr(acc_no varchar2(10),type
varchar2(10),operationmode varchar2(10), opendate varchar2(10),currbalance
number(10));
SQL>insert into acc_mstr values
('&acc_no','&type','&operationmode','&opendate',' &currbalance');
ACC_NO
B12771
H12902
W87532
L35193

TYPE
CA
SB
SB
CA

OPERATIONMODE
Single
Joint
Single
Single

OPENDATE
12-04-95
05-11-00
29-05-04
04-09-90

CURRBALANCE
2500
15000
65000
14500

AVERAGE (AVG()):SQL>select avg(currbalance)"Average Balance" from acc_mstr;


Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

30

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Average Balance
24250
MINIMUM (min()):SQL>select min(currbalance)"Minimum Balance" from acc_mstr;
Minimum Balance
2500
MAXIMUM (max()):SQL>select max(currbalance)"Maximum Balance" from acc_mstr;
Maximum Balance
65000

COUNT():SQL>select count(acc_no)"No. of Account" from acc_mstr;


No. of Account
4
COUNT(*):-

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

31

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SQL>select count(*)"No of Account" from acc_mstr;


No. of Account
4
SUM():SQL>select sum(currbalance)"Total Balance" from acc_mstr;
Total Balance
97000
Second Highest
SQL> select max(salary) from emp where salary<(select max(salary) from
emp);
Max(salary)
15000
Fifth Highest
SQL> select max(salary) from emp where salary<(select max(salary) from
emp where salary<(select max(salary) from emp where salary<(select
max(salary) from emp where salary<(select max(salary) from emp))));
Max(salary)
7000
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

32

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

EXIST AND NOT EXIST FUNCTION


SQL>create table cust_mstr(cust_no number(10),fname varchar2(10),lname
varchar2(10),mname varchar2(10));
Table created;
SQL>insert into cust_mstr values(&cust_no,&fname,&lname,&mname);
CUST_NO
A111
B777
C666
D123
E321

FNAME
d
sushma
vasa
kk
krishna

LNAME
raju
Venlakshmi
Devi
Kishore
Manohar

MNAME
Naga
Venkstlakshmi
Diwakar
Settee
Pantulu

SQL>create table emp_mstr(emp_no number(10),fname varchar2(10),lname


varchar2(10),desg varchar2(10),branch_no number(10));

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

33

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Table created;
SQL>insert into emp_mstr values(&emp_no,&fname,&lname,&desg,
&branch_no);

EMP_NO
A111
B777
C666

FNAME
d
vasa
krishna

LNAME
raju
diwakar
manohar

DESG
clerk
manager
peon

BRANCH_NO
99254
65471
129873

EXIST clause:-

SQL>select cust_no,mname from cust_mstr E where exists(select *from emp_mstr where


emp_no=E.cust_no);

CUST_NO
B777
C666

MNAME
Venkatlakshmi
Diwakar

NOT EXIST clause:SQL> select cust_no,mname from cust_mstr E where not exists(select *from emp_mstr
where emp_no=E.cust_no);
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

34

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

CUST_NO
A111
D123
E321

MNAME
naga
setty
pantulu

IN, NOT IN, ORDER BY, GROUP BY CLAUSES


SQL>create table emp(emp_no number(5),ename varchar2(10),job
varchar2(10),sal number(10),dept_no number(10));
SQL>insert into emp values(&emp_no,&ename,&job,&sal,&dept_no);
SQL>select *from emp;
EMP_NO
7369
7499
7566
7698
7788
7868

ENAME
smith
aleen
jones
blake
Scott
King

JOB
clerk
salesman
manager
manager
analyst
president

SAL
800
1600
2975
2800
3000
5000

DEPT_NO
20
30
20
30
20
10

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

35

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

7900
7902

James
Ford

clerk
analyst

950
3000

20
10

IN lists: SQL>select ename,job,dept_no from emp where dept_no in(10);


ENAME
King
Ford

JOB
president
analyst

DEPT_NO
10
10

NOT IN lists: SQL>select ename,job,dept_no from emp where dept_no in(20);


EMP_NO
Allen
Blake
King
Ford

JOB
salesman
manager
president
annalyst

DEPT_NO
30
30
10
10

ORDER BY clause:SQL>select ename,job,sal, from emp where dept_no(20) order by ename;


EMP_NO
James
Jones
Scott
Smith
GROUPBY clause:-

JOB
clerk
manager
analyst
clerk

SAL
950
2975
3000
800

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

36

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SQL>select dept_no,count(deptno)from emp group by dept_no;


DEPT_NO
10
20
30

COUNT(DEPT_NO)
2
4
2

MAXIMUM AND MAXIMUM SALARIES FROM TWO


TABLES
SQL>create table sal1(no number(5),name varchar2(10), salary number(10));
SQL>insert into sal1 values(&no,&name,&salary);
SQL>select *from sal1;
NO
201
202
203
204

NAME
Venkatlakshmi
Diwakar
Rohan
Monty

SALARY
30000
35000
15000
25000

SQL>create table sal2(no number(5),name varchar2(10), salary number(10));


SQL>insert into sal2 values(&no,&name,&salary);
SQL>select *from sal2;
NO
101
102

NAME
Sushma
Diwakar

SALARY
25000
25000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

37

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

103
104

Lakshman
Krishna

DBMS Lab Manual

10000
15000

MAXIMUM SALARY:SQL>select max(salary)from(select salary from sal1 UNION select salary from sal2);
MAX(SALARY)
35000

MINIMUM SALARY:SQL>select min(salary)from(select salary from sal1 UNION select salary from sal2);
MIN(SALARY)
10000

UNION, INTERSECT AND MINUS CLAUSES


QUE1)CREATE THE CUSTOMER MASTER(cust_mstr) TABLE.

SQL>create table cust_mstr (cust_no number(10),fname varchar2(10),lname


varchar2(10), mname varchar2(10));

SQL>insert into cust_mstr values('&cust_no','&fname','&lname','&mname');

SQL>select * from cust_mstr;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

38

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

CUST_NO
A666
B222
C333

FNAME
aaa
bbb
ccc

LNAME
ravi
yyy
www

MNAME
Ooo
Ppp
Qqq

QUE2)CREATE THE EMPLOYEE MASTER(emp_mstr) TABLE.


SQL>create table emp_mstr(emp_no number(10),fname varchar2(10),lname
varchar2(10),desg varchar2(10),branch_no varchar2(10));
SQL>insert into emp_mstr values('&emp_no','&fname','&lname','&desg',
'&branch_no');

SQL>select * from emp_mstr;

EMP_NO
A666
B222
C333

FNAME
madhav
bbb
ccc

LNAME
Venu
Yyy
www

DESG
clerk
manager
AsstMgr

BRANCH_NO
99254
65471
129873

QUE3)CREATE THE ADDRESS DETAIL(add_detail) TABLE.


SQL>create table add_detail(code_no number(10),add1 varchar2(10),add2
varchar2(10),city varchar2(10),state varchar2(10),pincode number(6));
SQL>insert into add_detail
values('&code_no','&add1','&add2','&city','&state','&pincode');
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

39

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SQL>select *from add_detail;


CODE_NO
A666
B777
C888

ADD1
123-21
22/12-2
11/23-65

ADD2
PT colony
MAGISTIC
wst-street

CITY
Hyd
Bangalore
Vijayawada

STATE
AP
Karnataka
AP

PINCODE
500060
600006
500015

QUE4)CREATE THE ACCOUNT CUSTOMER DETAILS(acct_fd_cust_detail)


TABLE.
SQL>create table acct_fd_cust_detail(acct_fd_no varchar2(10),cust_no
varchar2(10));
SQL>insert into acct_fd_cust_detail values('&acct_fd_no','&cust_no');
SQL>select *from acct_fd_cust_detail;

ACCT_FD_NO
CA612
CA335
SB112
FS771

CUST_NO
CA221
CA120
SB340
FS110

UNION CLAUSE: SQL>select cust_no"ID",fname||''||lname"Customer|Employee"from


cust_mstr,add_detail where cust_mstr.cust_no=add_detail.code_no AND
add_detail.city='Hyd' AND
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

40

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

add_detail. code_no like'A%'


UNION
select emp_no"ID",fname ||''||lname "Customer|Employee"from
emp_mstr,add_detail where emp_mstr.emp_no=add_detail.code_no AND
add_detail.city='Hyd' AND add_detail.code_no like 'A%';
ID
A666
A666

CUSYOMER/EMPLOYEE
Aaaravi
Madhavvenu

INTERSECT CLAUSE: SQL>select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%'
OR acct_fd_no 'SB%'
INTERSECT
select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%' OR
acct_fd_no 'FS%'

CUST_NO
CA120

MINUS: -

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

41

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SQL>select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'CA%'


OR acct_fd_no 'SB%'
MINUS
select distinct cust_no from acc_fd_cust_detail where acct_fd_no like 'FS%' OR
acct_fd_no 'SB%'

CUST_NO
CA120

Joins:
Explanation of joins with an example
Create table depositors(cdi number,cname varchar2(20),cage number)
Table created
Insert into depositors values(&cdi,&cname,&cage)
select * from depositors
CDI
501 c1
502 c2
503 c3
504 c4

CAME

CAGE
21
22
23
26

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

42

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

Create table borrowers(cdi number,lno number,amount number)


Table created
Insert into borrowers values(&cdi,&lno,&amount)
Select * from borrowers
CDI

LNO
501
502
505
506

AMOUNT
101
102
105
106

2000
3000
4000
5000

Inner join:
Sql>select * from depositors d inner join borrowers b on d.cdi=b.cdi
CDI
CAME
501 c1
502 c2

CAGE
21
22

CDI
501
502

LNO
101
102

AMOUNT
2000
3000

Outer join:
Left outer join:
Sql>select * from depositors d left outer join borrowers b on d.cdi=b.cdi
CDI
CAME
501 c1

CAGE
21

CDI
501

LNO
101

AMOUNT
2000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

43

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

502 c2
504 c4
503 c3

22
26
23

502

102

3000

Right outer join:


Sql> select * from depositors d right outer join borrowers b on d.cdi=b.cdi
CDI
CAME
501 c1
502 c2

CAGE
21
22

CDI
501
502
505
506

LNO
101
102
105
106

AMOUNT
2000
3000
4000
5000

Full outer join:


Sql> select * from depositors d full outer join borrowers b on d.cdi=b.cdi
CDI
501
502
504
503

CAME

CAGE

c1
c2
c4
c3

21
22
26
23

CDI
501
502

LNO
101
102

AMOUNT
2000
3000

505
506

105
106

4000
5000

Cross join
Sql> select * from depositors cross join borrowers
CDI
CAME
501 c1

CAGE
21

CDI
501

LNO
101

AMOUNT
2000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

44

DBMS Lab Manual

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

501
501
501
502
502
502
502
503
503
503
503
504
504
504
504

c1
c1
c1
c2
c2
c2
c2
c3
c3
c3
c3
c4
c4
c4
c4

21
21
21
22
22
22
22
23
23
23
23
26
26
26
26

502
505
506
501
502
505
506
501
502
505
506
501
502
505
506

102
105
106
101
102
105
106
101
102
105
106
101
102
105
106

3000
4000
5000
2000
3000
4000
5000
2000
3000
4000
5000
2000
3000
4000
5000

Expressions in a SELECT statement:


Arithmetic operations can be performed using
SELECT statement as shown below.
SQL> SELECT 10+5 FROM DUAL;
10+5
---------15
SQL> SELECT 10-5 FROM DUAL;
10-5
---------5
SQL> SELECT 10*5 FROM DUAL;
10*5
---------50
SQL> SELECT 10/5 FROM DUAL;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

45

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

10/5
---------2

Numeric Functions:
These functions operate on Numeric data hence is the name.
Note: Argument num in the following functions is any float-valued number.
ABS(num): Returns absolute value of the given number.(i.e. Always positive value)
SQL> SELECT ABS(10) FROM DUAL;
ABS(10)
---------10
SQL> SELECT ABS(-10) FROM DUAL;
ABS(-10)
---------10
CEIL(num): It returns the smallest integer greater than the given number.
SQL> SELECT CEIL(123.456) FROM DUAL;
CEIL(123.456)
-------------

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

46

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

124
FLOOR(num): It returns the largest integer smaller than the given value.
SQL> SELECT FLOOR(123.456) FROM DUAL;
FLOOR(123.456)
-------------123
LN(num) : It returns natural logarithm value of num .
SQL> SELECT LN(10) FROM DUAL;
LN(10)
---------2.30258509

LOG(m, n): It returns logarithm of n with base m.


SQL> SELECT LOG(100,10) FROM DUAL;
LOG(100,10)
----------.5
SQL> SELECT LOG(10,100) FROM DUAL;
LOG(10,100)
----------2
MOD(m, n) : It returns remainder of m divided by n.
SQL> SELECT MOD(10,3) FROM DUAL;
MOD(10,3)
---------1
POWER(m, n): It returns value equal to m raised by n.
SQL> SELECT POWER(10,2) FROM DUAL;
POWER(10,2)
----------Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

47

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

100
ROUND(m, n): It rounds the given float-valued number m to the n places after the decimal
SQL> SELECT ROUND(1.23456) FROM DUAL;
ROUND(1.23456)
-------------1
SQL> SELECT ROUND(1.23456,3) FROM DUAL;
ROUND(1.23456,3)
---------------1.235
SQRT(m): It calculates square root value of number m
SQL> SELECT SQRT(9) FROM DUAL;
SQRT(9)
---------3
TRUNC(m, n): It truncates given float-valued number m to n places after the decimal.
SQL> SELECT TRUNC(1.23456) FROM DUAL;
TRUNC(1.23456)
-------------1
SQL> SELECT TRUNC(1.23456,3) FROM DUAL;
TRUNC(1.23456,3)
---------------1.234
GREATEST(expr1, expr2, ) : It finds the greatest value among the given expressions.
SQL> SELECT GREATEST(4,7,3,5,9,2) FROM DUAL;
GREATEST(4,7,3,5,9,2)
--------------------9
LEAST(expr1, expr2, ): It finds the Lowest value among the given expressions.
SQL> SELECT LEAST(4,7,3,5,9,2) FROM DUAL;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

48

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

LEAST(4,7,3,5,9,2)
-----------------2

CHARACTER FUNCTIONS:
UPPER( str) : It converts all letters in the given
string str into Upper case.
SQL> SELECT UPPER('abcDEfg') FROM DUAL;
UPPER('
------ABCDEFG
LOWER(str): It converts all the letters in the given
string str into Lower Case.
SQL> SELECT LOWER('ABCDEfg') FROM
DUAL;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

49

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

LOWER('
------abcdefg
INITCAP(str): It converts first letter of every word
in the given string str into Upper Case and
remaining letters into lower case. It is like proper
function in FoxPro.
SQL> SELECT INITCAP('ABCDEF') FROM
DUAL;
INITCA
-----Abcdef

LENGTH(str) : This function returns the number of


characters in the given string (including spaces)
SQL> SELECT LENGTH('ABCD')outpuy FROM
DUAL;
LENGTH('ABCD') output
-------------4
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

50

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

SQL> SELECT LENGTH('AB CD') FROM DUAL;


LENGTH('ABCD')
-------------5
SUBSTR(str, m, n) : Will extract n characters
from the given string starting from
m th position.
SQL> SELECT SUBSTR('ABCDEFG',2,3) FROM
DUAL
SUB
--BCD
SQL> SELECT SUBSTR('ABCDEF',1,3) FROM
DUAL
SUB
--ABC
INSTR(string, str): It displays the location of str
in the given string string .
SQL> SELECT INSTR('TRYING TO KEEP THE
THINGS AS SIMPLE AS POSSIBLE','AS') FROM
DUAL;
INSTR('
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

51

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

----------------------------------------------------27
INSTR(string, str, m, n): It displays nth occurrence
of str in the string string starting from m.
SQL> SELECT INSTR('TRYING TO KEEP THE
THINGS AS SIMPLE AS POSSIBLE','AS',1,2)
FROM DUAL
INSTR(
-----------------------37
Note : DUAL IS A TABLE WITH 1 COLUMN
AND 1 ROW OF DATA IN IT.
SQL > DESC DUAL
Name
Null? Type
----------------------------------------- -------- DUMMY
VARCHAR2(1)
SQL > SELECT * FROM DUAL;
DUMMY
-----------X
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

52

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

LPAD() : This function is used to left pad the given


string with specified character or string.
SQL > SELECT LPAD('BCD',4,'A') FROM DUAL;
LPAD
---ABCD
Explanation: To the given string "BCD" add "A" to
the left necessary number of times to make it a string
of 4 characters.
SQL > SELECT LPAD('BCD',5,'A') FROM DUAL;
LPAD(
----AABCD
Explanation: To the given string "BCD" add "A" to
the left necessary number of times to make it a string
of 5 characters.
SQL > SELECT LPAD('BCD',3,'A') FROM DUAL;
LPA
--BCD

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

53

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Explanation: To the given string "BCD" add "A" to


the left necessary number of times to make it a string
of 3 characters.

SQL > SELECT LPAD(' ',ROWNUM,'*') FROM


EMP;
LPAD('',ROWNUM,'*')
---------------------------------------------------------------*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

54

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

RPAD(): This function is used to right pad the given


string with specified character or string.
SQL > SELECT RPAD('BILL ' , 12 , 'CLINTON')
FROM DUAL;
RPAD('BILL',
-----------BILL CLINTON
LTRIM(): This function removes specified string
from the given string if it is there to the left of given
string.
SQL > SELECT LTRIM('GEORGE BUSH',
'GEORGE') FROM DUAL;
LTRIM
----BUSH
RTRIM(): This function removes specified string
from the given string if it is there to the right of
given string.
SQL > SELECT RTRIM('TONY BLAIR', 'AIR')
FROM DUAL;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

55

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

RTRIM('
------TONY BL
ASCII(): Displays equivalent ASCII value of a
character.
SQL > SELECT ASCII('A') FROM DUAL;
ASCII('A')
---------65
SQL >SELECT TRANSLATE('JOHN','H','N')
FROM DUAL;
TRAN
---JONN

OTHER FUNCTIONS:
Note: Arguments to the below given functions are in terms of radians
COS(x): It returns the Cosine of x.
SQL> SELECT COS(0) FROM DUAL;
COS(0)
---------Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

56

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

1
COSH(x) : It returns hyperbolic cosine of x.
SQL> SELECT COSH(0) FROM DUAL;
COSH(0)
---------1
SIN(x) : It returns sine of x.
SQL> SELECT SIN(0) FROM DUAL;
SIN(0)
---------0
SINH(x): It returns hyperbolic sine of x.
SQL> SELECT SINH(0) FROM DUAL;
SINH(0)
---------0
TAN(x): It returns tangent of x.
SQL> SELECT TAN(0) FROM DUAL;
TAN(0)
---------0
TANH(x): It returns hyperbolic tangent of x.
SQL> SELECT TANH(0) FROM DUAL;
TANH(0)
---------0

DATEFUNCTIONS:
ADD_MONTHS(date, n) : Adds n months to the specified date .
SQL> SELECT ADD_MONTHS('1-JAN-05',5) FROM DUAL;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

57

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

ADD_MONTHS
-----------------01-JUN-05
LAST_DAY(date): Gives last date of the specified month (date).
SQL> SELECT LAST_DAY('1-JAN-05') FROM DUAL;
LAST_DAY(
--------31-JAN-05

MONTHS_BETWEEN(date1, date2): It gives difference between the two dates date1,


date2 in months.
SQL> SELECT MONTHS_BETWEEN('31-DEC-05','1-JAN-05') FROM DUAL
MONTHS_BETWEEN('31-DEC-05','1-JAN-05')
-------------------------------------11.9677419
SQL> SELECT MONTHS_BETWEEN('31-JUL-05','1-JUL-05') FROM DUAL
MONTHS_BETWEEN('31-JUL-05','1-JUL-05')
-------------------------------------.967741935
NEXT_DAY(date, day ) : It gives date of the next occurrence of the specified day after
the given date.
SQL> SELECT NEXT_DAY('01-JAN-05','FRI') FROM DUAL;
NEXT_DAY(
--------07-JAN-05

(Next Friday after 1-jan-05 is on 7-jan-05)

TO_DATE (string): This function converts a string into an Oracle date.


SQL> SELECT TO_DATE('01 JANUARY 2005','DD MONTH YYYY') FROM DUAL;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

58

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

TO_DATE('
--------01-JAN-05
SQL> SELECT TO_DATE('MAR 05 01','MON YY DD') FROM DUAL;
TO_DATE('
--------01-MAR-05
SQL> SELECT TO_DATE('01/01/05', 'DD/MM/YY') FROM DUAL;
TO_DATE('
--------01-JAN-05
The USER, SYSDATE Functions:
USER function displays login name of the user.
SQL> SELECT USER FROM DUAL;
USER
-----------------------------SCOTT
SYSDATE function displays system date.(Date in your windows)
SQL> SELECT SYSDATE FROM DUAL;
SYSDATE
--------1-JAN-05

CONVERSION FUNCTIONS:
TO_CHAR: This function is used to convert a date or number to character string.
SQL> SELECT TO_CHAR(SYSDATE,'DAY DD MONTH YYYY') FROM DUAL

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

59

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

TO_CHAR (SYSDATE,'DAYDDMONTH
--------------------------SATURDAY 01 JANUARY 2005
SQL> SELECT TO_CHAR (SYSDATE,' DD DY MM YY') FROM DUAL;
TO_CHAR (SYSDA
------------01 SAT 01 05
NVL() Function: This function is used to substitute any null value with a user-defined value.
Consider the following data from EMP table of SCOTT.
SQL> SELECT EMPNO, ENAME, SAL, COMM FROM EMP;
EMPNO ENAME
SAL
COMM
---------- ---------- ---------- ------------------------7369 SMITH
800
7499 ALLEN
1600
300
7521 WARD
1250
500
7566 JONES
2975
7654 MARTIN
1250
1400
7698 BLAKE
2850
7782 CLARK
2450
7788 SCOTT
3000
7839 KING
5000
7844 TURNER
1500
0
7876 ADAMS
1100
7900 JAMES
950
7902 FORD
3000
7934 MILLER
1300
In the above table except for 7499, 7521, 7654 and 7844 all others commissions are null
To display their commission as 0 (zero)

We can use NVL() function as shown below.


SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 100) FROM EMP
EMPNO ENAME
SAL NVL(COMM,100)
---------- ---------- ---------- ------------Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

60

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934

SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

800
1600
1250
2975
1250
2850
2450
3000
5000
1500
1100
950
3000
1300

DBMS Lab Manual

100
300
500
100
1400
100
100
100
100
0
100
100
100
100

SQL> SELECT EMPNO, ENAME, SAL, NVL (COMM, 888) FROM EMP
EMPNO ENAME
SAL NVL(COMM,888)
---------- ---------- ---------- ------------7369 SMITH
800
888
7499 ALLEN
1600
300
7521 WARD
1250
500
7566 JONES
2975
888
7654 MARTIN
1250
1400
7698 BLAKE
2850
888
7782 CLARK
2450
888
7788 SCOTT
3000
888
7839 KING
5000
888
7844 TURNER
1500
0
7876 ADAMS
1100
888
7900 JAMES
950
888
7902 FORD
3000
888
7934 MILLER
1300
888
In above queries we have seen how to substitute a value when the comm is null.
If one want to display "Commission not payed" against the employees who have no
commission we can write the following query.

SQL > SELECT ENAME, SAL, NVL(TO_CHAR(COMM),'Commission Not Payed') FROM


EMP;
ENAME
SAL NVL(TO_CHAR(COMM),'COMMISSIONNOTPAYED')
---------- ---------- ---------------------------------------SMITH
800 Commission Not Payed
ALLEN
1600 300
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

61

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER

DBMS Lab Manual

1250 500
2975 Commission Not Payed
1250 1400
2850 Commission Not Payed
2450 Commission Not Payed
3000 Commission Not Payed
5000 Commission Not Payed
1500 0
1100 Commission Not Payed
950 Commission Not Payed
3000 Commission Not Payed
1300 Commission Not Payed

SUBQUERIES
A query nested within a query is known as subquery.
For example, you want to see all the employees whose salary is above average
salary. For this you have to first compute the average salary using AVG function
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

62

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

and then compare employees salaries with this computed salary. This is possible
using subquery. Here
the sub query will first compute the average salary and then main query will
execute.
Select * from emp where sal > (select avg(sal) from emp);
Similarly we want to see the name and empno of that employee whose salary is
maximum.
Select * from emp where sal = (select max(sal) from emp);
To see second maximum salary
Select max(sal) from emp where
sal < (select max(sal) from emp);
Similarly to see the Third highest salary.
Select max(sal) from emp where
sal < (select max(sal) from emp Where
sal < (select max(sal) from emp));
We want to see how many employees are there whose salary is above average.
Select count(*) from emp where
sal > (select max(sal) from emp);
We want to see those employees who are working in Hyderabad. Remember emp
and dept are joined on deptno and city column is in the dept table. Assuming that
wherever the department is located the employee is working in that city.
Select * from emp where deptno
in (select deptno from dept where city=HYD);
You can also use subquery in FROM clause of SELECT statement.
For example the following query returns the top 5 salaries from employees table.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

63

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Select sal from (select sal from emp order sal desc)
where rownum <= 5;
To see the sum salary deptwise you can give the following query.
Select sum(sal) from emp group by deptno;
Now to see the average total salary deptwise you can give a sub query in FROM
clause.
select avg(depttotal) from (select sum(sal) as depttotal from emp group by
deptno);

WITH
The above average total salary department wise can also be achieved in 9i using
WITH clause given below
WITH DEPTOT AS (select sum(sal) as dsal from emp
group by deptno)
select avg(dsal) from deptot;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

64

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

1) Write a PL/SQL Program to print numbers from 1 to 10.


set serverout on;
declare
n number(2):=1;
begin
loop
dbms_output.put_line(n);
n:=n+1;
exit when n>10;
end loop;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

65

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

End;
OUTPUT:
1
2
3
4
5
6
7
8
9
10

2) Write a PL/SQL program to find the AREA OF CIRCLE.


SQL>create table areas(radius number(5),area number(14,2));
set serverout on;
declare
pi constant number(4,2):=3.14;
radius number(5);
area number(14,2);
begin
radius:=3;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

66

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

while radius<=7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
radius:=radius+1;
end loop;
end;
OUT PUT:SQL> select *from areas;
RADIUS
3
4
5
6
7

AREA
28.26
50.24
78.5
113.04
153.86

3) Write a PL/SQL program to find the FIBBONACCI NUMBERS.


set serverout on;
declare
n number(2):=0;
n1 number(2):=1;
n2 number(2):=1;
begin
dbms_output.put_line('fibbonacci series');
dbms_output.put_line(n);
dbms_output.put_line(n1);
while n2 < 20
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

67

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

loop
n2:=n+n1;
dbms_output.put_line(n2);
n:=n1;
n1:=n2;
end loop;
End;
OUTPUT:fibbonacci series
0
1
1
2
3
5
8
13
21

4) Write a PL/SQL program to find the ODD NUMBER.


set serverout on;
declare
n number(2):=1;
begin
loop
if n mod 2!=0 then
dbms_output.put_line(n);
exit when n>10;
end if;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

68

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

n:=n+1;
end loop;
End;

OUTPUT:
1
3
5
7
9
11

5) Write a pl/sql program to display the numbers from 30 to 40.


set serverout on;
declare
n number(2):=1;
begin
dbms_output.put_line('enter a number');
n:=&n;
dbms_output.put_line('display the numbers from 30 to 40:');
while n <= 40
loop
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

69

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

dbms_output.put_line(n);
n:=n+1;
end loop;
end;
Output:old 5: n:=&n;
new 5: n:=30;
enter a number
display the numbers from 30 to 40:
30
31
32
33
34
35
36
37
38
39
40
6) Write a PL/SQL program to find the FACTORIAL OT THE
GIVEN NUMBER.

SQL>create table facto(num number(6),fact number(6));


set serverout on;
declare
num number(10);
fact number(10):=1;
temp number(10);
begin
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

70

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

num:=&num;
temp:=num;
while num>0
loop
fact:=fact*num;
num:=num-1;
end loop;
insert into facto values(temp,fact);
end;
OUTPUT:procedure successfully completed
SQL>select *from facto;
NUM
5

FACT
120

7) Write a PL/SQL program to find the given number is PRIME or


NOT
set serverout on
declare
i number:=1;
n number(10):=&n;
counts number:=0;
begin
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

71

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

while i<=n
loop
if n mod i=0
then
counts:=counts+1;
endif;
I:=I+1;
End loop;
If counts=2
Then
dbms_output.put_line(prime);
else
dbms_output.put_line(not prime);
end if;
end;
OUT PUT:old 3: n number(10):=&n;
new 3: n number(10):=6;
not prime
PL/SQL procedure successfully completed.

Function:8) Write a PL/SQL program to find the area of the circle with the
function

create function f_cal_area(radius in number)


return number
is
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

72

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

pi constant number(9,7):=3.14;
area number(14,2);
begin
area:=pi*power(radius,2);
return area;
end;

OUT PUT:-

FUNCTION USING CASE STATEMENTS:


create or replace function Get_Grade1(score IN NUMBER)
RETURN VARCHAR2
is
begin
CASE
WHEN score BETWEEN 80 AND 100 THEN
dbms_output.put_line('Between 80 and 100');
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

73

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

return 'A';
WHEN score BETWEEN 65 AND 79 THEN
dbms_output.put_line('Between 65 and 79');
return 'B';
WHEN score BETWEEN 50 AND 64 THEN
dbms_output.put_line('Between 50 and 64');
return 'C';
WHEN score BETWEEN 40 AND 49 THEN
dbms_output.put_line('Between 40 and 49');
return 'D';
WHEN score BETWEEN 0 AND 39 THEN
dbms_output.put_line('Between 0 and 39');
return 'F';
ELSE
return 'Invalid score';
END CASE;
end Get_Grade1;

2.
create or replace function Get_Grade2(score IN NUMBER)
RETURN VARCHAR2
is
grade VARCHAR2(15);
begin
grade := CASE
WHEN score BETWEEN 80 AND 100 THEN 'A'
WHEN score BETWEEN 65 AND 79 THEN 'B'
WHEN score BETWEEN 50 AND 64 THEN 'C'
WHEN score BETWEEN 40 AND 49 THEN 'D'
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

74

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

WHEN score BETWEEN 0 AND 39 THEN 'F'


ELSE 'Invalid score'
END;
return grade;
end Get_Grade2;

Procedure:
create procedure area_c6(radius in number)
as
pi constant number(9,7):=3.14;
area number(14,2);
begin
area:=pi*power(radius,2);
insert into areas values(radius,area);
end;

EXCEPTION HANDLING:
1) WRITE A PL/SQL PROGRAM TO DEMONSTRATE THE
DIVIDE BY ZERO EXCEPTION

set serveroutput on
DECLARE
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

75

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Num_a NUMBER := 6;
Num_b NUMBER;
BEGIN
Num_b := 0;
Num_a := Num_a / Num_b;
Num_b := 7;
dbms_output.put_line(' Value of Num_b ' ||
Num_b);
EXCEPTION
WHEN ZERO_DIVIDE
THEN
dbms_output.put_line('Trying to divide by zero');
dbms_output.put_line(' Value of Num_a ' || Num_a);
bms_output.put_line(' Value of Num_b ' || Num_b);
END;

OUT PUT:

Trying to divide by zero


Value of num_a 6
Value of num_b 0
Pl/sql procedure successfully completed.
2) WRITE A PL/SQL PROGRAM TO DEMONSTRATE THE
STRING CONVERSION EXCEPTION

CREATE TABLE EMPLOYEE(NUM NUMBER);


BEGIN
INSERT INTO EMPLOYEE(NUM ) VALUES(123X);
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

76

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

EXCEPTION
WHEN INVALID_NUMBER
THEN
DBMS_OUTPUT.PUT_LINE (CONVERSION TO STRING
TO NUMBER FAILED);
END;
O/P:
CONVERSION TO STRING TO NUMBER FAILED
PL/SQL PROCEDURE SUCCESFULLY COMPLETED.

Triggers:A trigger is a pl/sql block structure which is fired when a DML statements
like Insert, Delete, Update is executed on a database table. A trigger is
triggered automatically when an associated DML statement is executed.
Syntax of Triggers
The Syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

77

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

{INSERT [OR] | UPDATE [OR] | DELETE}


[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;

CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a


trigger with the given name or overwrites an existing trigger with the same
name.
{BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time
should the trigger get fired. i.e for example: before or after updating a table.
INSTEAD OF is used to create a trigger on a view. before and after cannot
be used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the
triggering event. More than one triggering events can be used together
separated by OR keyword. The trigger gets fired at all the specified
triggering event.
[OF col_name] - This clause is used with update triggers. This clause is used
when you want to trigger an event only when a specific column is updated.
CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a
trigger with the given name or overwrites an existing trigger with the same
name.
[ON table_name] - This clause identifies the name of the table or view to
which the trigger is associated.
[REFERENCING OLD AS o NEW AS n] - This clause is used to reference
the old and new values of the data being changed. By default, you reference
the values as :old.column_name or :new.column_name. The reference names
can also be changed from old (or new) to any other user-defined name. You
cannot reference old values when inserting a record, or new values when
deleting a record, because they do not exist.
[FOR EACH ROW] - This clause is used to determine whether a trigger
must fire when each row gets affected ( i.e. a Row Level Trigger) or just
once when the entire sql statement is executed(i.e.statement level Trigger).
WHEN (condition) - This clause is valid only for row level triggers. The
trigger is fired only for rows that satisfy the condition specified.
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

78

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

For Example: The price of a product changes constantly. It is


important to maintain the history of the prices of the products.
We can create a trigger to update the 'product_price_history' table
when the price of the product is updated in the 'product' table.
1) Create the 'product' table and 'product_price_history' table

CREATE TABLE product_price_history


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
CREATE TABLE product
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

2) Create the price_history_trigger and execute it.

CREATE or REPLACE TRIGGER price_history_trigger


BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

79

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
3) Lets update the price of a product.

UPDATE PRODUCT SET unit_price = 800


WHERE product_id = 100
Once the above update query is executed, the
trigger fires and updates the 'product_price_history'
table.
4)If

you ROLLBACK the transaction before


committing to the database, the data inserted to the
table is also rolled back.

Types of PL/SQL Triggers


There are two types of triggers based on the which
level it is triggered.
1) Row level trigger - An event is triggered for each
row upated, inserted or deleted.
2) Statement level trigger - An event is triggered for
each sql statement executed.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

80

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

PL/SQL Trigger Execution Hierarchy


The following hierarchy is followed when a trigger is fired.
1) BEFORE statement trigger fires first.
2) Next BEFORE row level trigger fires, once for each row affected.
3) Then AFTER row level trigger fires once for each affected row. These
events will alternates between BEFORE and AFTER row level triggers.
4) Finally the AFTER statement level trigger fires.
For Example: Let's

create a table 'product_check' which


we can use to store messages when triggers are fired.
CREATE TABLE product
(Message varchar2(50),
Current_Date number(32));
Let's create a BEFORE and AFTER statement and
row level triggers for the product table.

1)BEFORE UPDATE, Statement Level: This trigger


will insert a record into the table 'product_check'
before an sql update statement is executed, at the
statement level.
CREATE or REPLACE TRIGGER
Before_Update_Stat_product
BEFORE UPDATE ON product
Begin
INSERT INTO product_check
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

81

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Values('Before update, statement level',sysdate);


END;
2) BEFORE

UPDATE, Row Level: This trigger will insert a


record into the table 'product_check' before each row is
updated.
CREATE or REPLACE TRIGGER
Before_Upddate_Row_product
BEFORE UPDATE ON product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('Before update row level',sysdate);
END;

3) AFTER

UPDATE, Statement Level: This trigger


will insert a record into the table 'product_check' after
a sql update statement is executed, at the statement
level.
CREATE or REPLACE TRIGGER After_Update_Stat_product
AFTER UPDATE ON product
BEGIN
INSERT INTO product_check
Values('After update, statement level', sysdate);
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

82

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

End;
4) AFTER

UPDATE, Row Level: This trigger will


insert a record into the table 'product_check' after each
row is updated.
CREATE or REPLACE TRIGGER
After_Update_Row_product
AFTER insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('After update, Row level',sysdate);
END;
/

Now lets execute a update statement on table product.


UPDATE PRODUCT SET unit_price = 800
WHERE product_id in (100,101);
Lets check the data in 'product_check' table to see the order in
which the trigger is fired.

SELECT * FROM product_check;


Output:
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

83

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

Mesage
Current_Date
-----------------------------------------------------------Before update, statement level
26-Nov-2008
Before update, row level
26-Nov-2008
After update, Row level
26-Nov-2008
Before update, row level
26-Nov-2008
After update, Row level
26-Nov-2008
After update, statement level
26-Nov-2008
The above result shows 'before update' and 'after update' row level events
have occured twice, since two records were updated. But 'before update' and
'after update' statement level events are fired only once per sql statement.
The above rules apply similarly for INSERT and DELETE statements.

How to know information about Triggers.


We can use the data dictionary view 'USER_TRIGGERS' to obtain
information about any trigger.

The below statement shows the structure of the view 'USER_TRIGGERS'

DESC USER_TRIGGERS;
NAME
Type
-------------------------------------------------------TRIGGER_NAME
VARCHAR2(30)
TRIGGER_TYPE
VARCHAR2(16)
TRIGGER_EVENT
VARCHAR2(75)
TABLE_OWNER
VARCHAR2(30)
BASE_OBJECT_TYPE
VARCHAR2(16)
TABLE_NAME
VARCHAR2(30)
COLUMN_NAME
VARCHAR2(4000)
REFERENCING_NAMES
VARCHAR2(128)
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

84

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI

DBMS Lab Manual

WHEN_CLAUSE
VARCHAR2(4000)
STATUS
VARCHAR2(8)
DESCRIPTION
VARCHAR2(4000)
ACTION_TYPE
VARCHAR2(11)
TRIGGER_BODY
LONG
This view stores information about header and body of the trigger.

SELECT * FROM user_triggers WHERE trigger_name =


'Before_Update_Stat_product';
The above sql query provides the header and body of
the trigger 'Before_Update_Stat_product'.
You can drop a trigger using the following command.
DROP TRIGGER trigger_name;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

85

Vous aimerez peut-être aussi