You are on page 1of 80

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.

DESHMUKHI DBMS Lab Manual

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 1
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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? Type


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)

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 LNAME EMP_ID BDATE HDATE DESGN MGR_ID SALARY DEPT_NO


shashank g 111 23mar1959 23mar2007 xyz1 112 1000011
nano t 112 17oct1989 17oct2007 xyz2 112 1200011
babu n 113 17aug1989 17aug2007 xyz3 113 1200013
Anand m 114 22may1956 02jan2006 xyz4 114 1000014
sreekanth t 115 05nov1989 05nov2005 xyz5 113 12000013
prashanth m 116 22may1956 02may2005 xyz1 113 1300012
karthik d 117 02apr1989 02apr2006 xyz3 114 1400014

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 2
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Creating department table

create table department2(dept_name varchar2(10),dept_no


varchar2(10));

desc department2;

Name Null? Type


DEPT_NAME   VARCHAR2(10)
DEPT_NO   VARCHAR2(10)

Inserting values into department table

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

select * from department2;

DEPT_NAME DEPT_NO
HR 11
RESEARCH 12
MANAGEMENT 13
devpmt 14
recovery 15

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 3
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Works_on table creation

create table works_on1(emp_id number(5),proj_no


number(5),hrs number(5));

desc works_on1;

Name Null? Type


EMP_ID   NUMBER(5)
PROJ_NO   NUMBER(5)
HRS   NUMBER(5)

inserting values into table

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

select *from works_on1;

EMP_ID PROJ_NO HRS


111 101 10
114 104 11
116 105 12
117 104 8

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 4
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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? Type


PROJ_NAME   VARCHAR2(30)
PROJ_NO   NUMBER(5)
PROJ_LOC   VARCHAR2(30)
DEPT_NO   NUMBER(5)

inserting values into table


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

select *from project1

PROJ_NAME PROJ_NO PROJ_LOC DEPT_NO


abc1 101hyd 11
abc2 102chennai 12
abc3 103hyd 12
abc4 104goa 14
abc5 105banglore 13
abc6 106jaipur 15
6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 5
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Deptloc table creation

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

desc deptloc;

Name Null? Type


DEPT_NO   NUMBER
DEPT_LOC   VARCHAR2(30)

inserting values into table

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

select * from deptloc;

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

6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 6
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? Type


ACC_NO   NUMBER(20)
B_NAME   VARCHAR2(20)
BALANCE   NUMBER(10)

Inserting values into accounts table

insert into accounts values(&acc_no,'&b_name',&balance);

select * from accounts;

ACC_NO B_NAME BALANCE


101sb1 500
102sb2 400
201sb3 900
215sb4 700
217sb3 715
222sb5 700
305sb6 350

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 7
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Creating customer table

create table customer(cust_name varchar2(20),cust_street varchar2(20),cust_city


varchar2(20));

desc customer;

Name Null? Type


CUST_NAME   VARCHAR2(20)
CUST_STREET   VARCHAR2(20)
CUST_CITY   VARCHAR2(20)

Inserting values into customer

insert into customer values('&cust_name','&cust_street','&cust_city');

select * from customer;

CUST_NAME CUST_STREET CUST_CITY


anand spring jaipur
babu senator hyderabad
giri north chennai
sreekanth hill delhi
shashank main calcutta
pradeep alma goa
karthik north chennai
kishore main calcutta
chanu park jaipur
saleem putnam stanford

10 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 8
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   NUMBER(20)
B_NAME   VARCHAR2(20)
AMOUNT   NUMBER(20)

Inserting values into loan table

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

select * from loan;

LOAN_NO B_NAME AMOUNT


11sb6 900
14sb1 1500
15sb2 1500
16sb2 1300
17sb1 1000
23sb5 2000
93sb4 500

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 9
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Creating borrower table

create table borrower(cust_name varchar2(20),loan_no number(20));

desc borrower;

Name Null? Type


CUST_NAME   VARCHAR2(20)
LOAN_NO   NUMBER(20)

Inserting values into borrower table

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

select * from borrower;

CUST_NAME LOAN_NO

anand 16
giri 93
shashank 15
sreekanth 14
kishore 17
karthik 11
karthik 23
babu 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? Type


CUST_NAME   VARCHAR2(20)
ACC_NO   NUMBER(20)

Inserting values into depositors table

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

Select * from depositors;

CUST_NAME ACC_NO
shashank 102
prided 101
pradeep 201
kishore 217
chanu 222
karthik 215
saleem 305

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 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? Type


B_NAME   VARCHAR2(20)
B_CITY   VARCHAR2(20)
ASSETS   NUMBER

Inserting values into branch table

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

select * from branch;

B_NAME B_CITY ASSETS


sb3 hyderabad 710000
sb1 hyderabad 900000
sb4 bangalore 400000
sb7 chennai 370000
sb2 bangalore 170000
sb8 mumbai 30000
sb5 goa 210000
sb6 bangalore 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? Type


SID   NUMBER(20)
BID   NUMBER(20)
RDATE   VARCHAR2(20)

Inserting values into reserves table

insert into reserves values(&sid,&bid,'&rdate');

select * from reserves;

SID BID RDATE


1111 10110-may-09
1112 10223-mar-89
1113 10320-mar-06
1114 10423-mar-00
1111 10505-nov-89

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 13
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 SAGE


1111name1 7 21
1112bob 6 20
1113bhatt 6 18
1114nano 9 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 BNAME


101green vamsi
102white sudeep
103black giri
104cream sree
105red krishna

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 14
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 DEPT_NAME


PRASHANTH MRESEARCH

2. For every project located in “hyd” list the


proj_no,dept_no,dept_mgr’s 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 LNAME


101 11g
101 11t
103 12m

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


Ans:
select fname,lname from employee where bdate like '%195_'

FNAME LNAME
shashank g
Anand m
prashanth m

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 15
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 LNAME
babu n

5. Retrieve the names of all employees, who don’t have


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

FNAME LNAME
nano t
babu n
Anand m

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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 16
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 COUNT(*) AVG(SALARY)


11 2 11000
12 1 13000
13 2 66000
14 2 12000

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


Ans:
select count(emp_id) from employee;

COUNT(EMP_ID)
7

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 17
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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


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 LNAME
shashank g
nano t
babu n
Anand m
sreekanth t
prashanth m
karthik d

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 18
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 SRATING SAGE


1111name1 7 21
1112bob 6 20

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 sid’s 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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 19
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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'

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) 20
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
nano

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 21
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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
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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 22
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Queries on bank database

1. Find all loan_no’s for 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_no’s.

Ans:

select distinct b.cust_name,b.loan_no from borrower b, loan l


where b.loan_no=l.loan_no

CUST_NAME LOAN_NO
karthik 11
sreekanth 14
shashank 15
anand 16
babu 17
kishore 17
karthik 23
Giri 93

8 rows

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 23
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

3. Find the names & loan_no’s 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
14sreekanth
17babu
17kishore

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

min(assets) from branch1 group by(b_city)

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

7 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 24
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 25
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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

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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 26
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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';

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 500
sb2 400
sb3 807.5
sb4 700
sb5 700
sb6 350

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 27
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 1
sb2 1
sb3 2
sb4 1
sb5 1
sb6 1

6 rows selected.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 28
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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 TYPE OPERATIONMODE OPENDATE CURRBALANCE


B12771 CA Single 12-04-95 2500
H12902 SB Joint 05-11-00 15000
W87532 SB Single 29-05-04 65000
L35193 CA Single 04-09-90 14500

DATE opendate DATE ex- 1 jan 2016

AVERAGE (AVG()):-

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

Average Balance
24250

MINIMUM (min()):-

SQL>select min(currbalance) "Minimum Balance" from acc_mstr;

Minimum Balance
2500

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 29
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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(*):-

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

No. of Account
4

SUM():-

SQL>select sum(currbalance) "Total 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

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) 31
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;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 32
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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

CUST_NO FNAME LNAME MNAME


A111 d raju Naga
B777 sushma Venlakshmi Venkstlakshmi
C666 vasa Devi Diwakar
D123 kk Kishore Settee
E321 krishna Manohar Pantulu

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


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

Table created;

SQL>insert into emp_mstr values(‘&emp_no’,’&fname’,’&lname’,’&desg’,


’&branch_no’);

EMP_NO FNAME LNAME DESG BRANCH_NO


A111 d raju clerk 99254
B777 vasa Diwakar manager 65471
C666 krishna Manohar peon 129873

EXIST clause:-

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


emp_no=E.cust_no);

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 33
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

CUST_NO MNAME
B777 Venkatlakshmi
C666 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);

CUST_NO MNAME
A111 naga
D123 setty
E321 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));

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 34
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

SQL>insert into emp values(’&emp_no’,’&ename’,’&job’,’&sal’,’&dept_no’);

SQL>select *from emp;

EMP_NO ENAME JOB SAL DEPT_NO


7369 smith Clerk 800 20
7499 aleen Salesman 1600 30
7566 jones Manager 2975 20
7698 blake Manager 2800 30
7788 Scott Analyst 3000 20
7868 King President 5000 10
7900 James Clerk 950 20
7902 Ford Analyst 3000 10

IN lists: -

SQL>select ename,job,dept_no from emp where dept_no in(‘10’);

select ename,job,dept_no from emp where dept_no in(‘10’,’20’);

ENAME JOB DEPT_NO


King President 10
Ford Analyst 10

NOT IN lists: -

SQL>select ename,job,dept_no from emp where dept_no not in(‘20’);

EMP_NO JOB DEPT_NO

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 35
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Allen Salesman 30
Blake Manager 30
King President 10
Ford Annalyst 10

ORDER BY clause:-

SQL>select ename,job,sal, from emp where dept_no in(‘20’) order by ename;

EMP_NO JOB SAL


James Clerk 950
Jones Manager 2975
Scott Analyst 3000
Smith Clerk 800

GROUPBY clause:-

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

DEPT_NO COUNT(DEPT_NO)
10 2
20 4
30 2

HAVING
we want to see total salary department wise where the dept wise total salary is above 5000.

For this you have to use HAVING clause. Remember HAVING clause is used to filter groups
and WHERE clause is used to filter rows. You cannot use WHERE clause to filter groups.

select deptno,sum(sal)

from emp

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 36
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

group by deptno

having sum(sal) >= 5000;

We want to see those departments  and the number of employees working in them where the
number of employees is more than 2.

Select deptno, count(*)

from emp

group by deptno

Having count(*) >=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 NAME SALARY
201 Venkatlakshmi 30000
202 Diwakar 35000
203 Rohan 15000
204 Monty 25000

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

SQL>insert into sal2 values(’&no’,’&name’,’&salary’);


Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 37
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

SQL>select *from sal2;

NO NAME SALARY
101 Sushma 25000
102 Diwakar 25000
103 Lakshman 10000
104 Krishna 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));

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 38
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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

SQL>select * from cust_mstr;

CUST_NO FNAME LNAME MNAME


A666 aaa ravi Ooo
B222 bbb yyy Ppp
C333 ccc www 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 FNAME LNAME DESG BRANCH_NO


A666 madhav Venu clerk 99254
B222 bbb Yyy manager 65471
C333 ccc www AsstMgr 129873

QUE3)CREATE THE ADDRESS DETAIL(add_detail) TABLE.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 39
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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');

SQL>select *from add_detail;

CODE_NO ADD1 ADD2 CITY STATE PINCODE


A666 123-21 PT colony Hyd AP 500060
B777 22/12-2 MAGISTIC Bangalore Karnataka 600006
C888 11/23-65 wst-street Vijayawada AP 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 CUST_NO
CA612 CA221
CA335 CA120
SB112 SB340
FS771 FS110

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 40
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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
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 CUSYOMER/EMPLOYEE
A666 Aaaravi
A666 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%'

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 41
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

CUST_NO
CA120

MINUS: -

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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 42
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

CDI CAME CAGE


501 c1 21
502 c2 22
503 c3 23
504 c4 26

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

Table created

Insert into borrowers values(‘&cdi’,’&lno’,’&amount’)

Select * from borrowers

CDI LNO AMOUNT


501 101 2000
502 102 3000
505 105 4000
506 106 5000

Inner join:

Sql>select * from depositors d inner join borrowers b on d.cdi=b.cdi

CDI CAME CAGE CDI LNO AMOUNT


501 c1 21 501 101 2000
502 c2 22 502 102 3000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 43
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

Outer join:

Left outer join:

Sql>select * from depositors d left outer join borrowers b on d.cdi=b.cdi

CDI CAME CAGE CDI LNO AMOUNT


501 c1 21 501 101 2000
502 c2 22 502 102 3000
504 c4 26      
503 c3 23      

Right outer join:

Sql> select * from depositors d right outer join borrowers b on d.cdi=b.cdi

CDI CAME CAGE CDI LNO AMOUNT


501 c1 21 501 101 2000
502 c2 22 502 102 3000
     505 105 4000
     506 106 5000

Full outer join:

Sql> select * from depositors d full outer join borrowers b on d.cdi=b.cdi

CDI CAME CAGE CDI LNO AMOUNT


501 c1 21 501 101 2000
502 c2 22 502 102 3000
504 c4 26      
503 c3 23      
     505 105 4000

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 44
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

     506 106 5000

Cross join

Sql> select * from depositors cross join borrowers

CDI CAME CAGE CDI LNO AMOUNT


501 c1 21 501 101 2000
501 c1 21 502 102 3000
501 c1 21 505 105 4000
501 c1 21 506 106 5000
502 c2 22 501 101 2000
502 c2 22 502 102 3000
502 c2 22 505 105 4000
502 c2 22 506 106 5000
503 c3 23 501 101 2000
503 c3 23 502 102 3000
503 c3 23 505 105 4000
503 c3 23 506 106 5000
504 c4 26 501 101 2000
504 c4 26 502 102 3000
504 c4 26 505 105 4000
504 c4 26 506 106 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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 45
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

----------
         5

SQL> SELECT 10*5 FROM DUAL;

      10*5
----------
        50

SQL> SELECT 10/5 FROM DUAL;

      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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 46
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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)
-------------
          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”.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 47
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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)
-----------
        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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 48
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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;

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;


LOWER('

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 49
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

-------
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;

INITCAP
------
Abcdef

LENGTH(str) : This function returns the number of characters in the given string (including
spaces)

SQL> SELECT LENGTH('ABCD') FROM DUAL;

LENGTH('ABCD')
--------------
             4

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;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 50
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

INSTR('
-----------------------------------------------------
       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

LPAD() : This function is used to left pad the 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.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 51
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

SQL > SELECT LPAD('BCD',3,'A') FROM DUAL;

LPA
---
BCD

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(NAME,30,’*’) FROM STUDENT;

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


LPAD('',ROWNUM,'*')
-----------------------------------------------------------------
*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************

RPAD(): This function is used to left pad the 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;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 52
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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;

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)
----------
         1
COSH(x) : It returns hyperbolic cosine of x.

SQL> SELECT COSH(0) FROM DUAL;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 53
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

 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;

 ADD_MONTHS
 ------------------
  01-JUN-05

LAST_DAY(date): Gives last date of the specified month (date).

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 54
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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(                                 (Next Friday after 1-jan-05 is on 7-jan-05)


---------
07-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;


TO_DATE('
---------
01-JAN-05

SQL> SELECT TO_DATE('MAR 05 01','MON YY DD') FROM DUAL;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 55
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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

TO_CHAR (SYSDATE,'DAYDDMONTH
---------------------------
SATURDAY 01 JANUARY   2005

SQL> SELECT TO_CHAR (SYSDATE,' DD DY MM YY') FROM DUAL;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 56
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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)


      ---------- ---------- ---------- -------------
      7369  SMITH             800         100
      7499  ALLEN            1600         300
      7521  WARD             1250         500
      7566  JONES            2975         100
      7654  MARTIN           1250        1400
      7698  BLAKE            2850         100

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 57
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

      7782  CLARK            2450         100


      7788  SCOTT            3000         100
      7839  KING             5000         100
      7844  TURNER           1500         0
      7876  ADAMS            1100         100
      7900  JAMES             950         100
      7902  FORD             3000         100
      7934  MILLER           1300         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
WARD             1250  500
JONES            2975  Commission Not Payed
MARTIN         1250  1400
BLAKE            2850  Commission Not Payed
CLARK            2450  Commission Not Payed
SCOTT            3000  Commission Not Payed

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 58
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

KING             5000  Commission Not Payed


TURNER          1500  0
ADAMS           1100  Commission Not Payed
JAMES             950  Commission Not Payed
FORD             3000  Commission Not Payed
MILLER           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
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.

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 59
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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.

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;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 60
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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) 61
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;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 62
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

exit when n>10;


end loop;
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);
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 63
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

area number(14,2);
begin
radius:=3;
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 AREA
3 28.26
4 50.24
5 78.5
6 113.04
7 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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 64
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

dbms_output.put_line('fibbonacci series');
dbms_output.put_line(n);
dbms_output.put_line(n1);
while n2 < 20
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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 65
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

if n mod 2!=0 then


dbms_output.put_line(n);
exit when n>10;
end if;
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;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 66
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

dbms_output.put_line('display the numbers from 30 to 40:');


while n <= 40
loop
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);

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 67
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

fact number(10):=1;
temp number(10);
begin
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 FACT
5 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;
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 68
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

counts number:=0;
begin
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)

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 69
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

return number
is
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


Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 70
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

dbms_output.put_line('Between 80 and 100');


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'

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 71
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

WHEN score BETWEEN 50 AND 64 THEN 'C'


WHEN score BETWEEN 40 AND 49 THEN 'D'
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);
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 72
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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
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

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 73
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

CREATE TABLE EMPLOYEE(NUM NUMBER);


BEGIN
INSERT INTO EMPLOYEE(NUM ) VALUES(‘123X’);
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:

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 74
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{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) 75
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
(: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


Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 76
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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.

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
Values('Before update, statement level',sysdate); END;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 77
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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);
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;

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 78
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

/
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:
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)

Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II – II) 79
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual

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)
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) 80

You might also like