Você está na página 1de 76

VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.

DESHMUKHI DBMS Lab Manual


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



















Company database

Employee table creation:


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

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 10000 11
nano t 112 17oct1989 17oct2007 xyz2 112 12000 11
babu n 113 17aug1989 17aug2007 xyz3 113 12000 13
Anand m 114 22may1956 02jan2006 xyz4 114 10000 14
sreekanth t 115 05nov1989 05nov2005 xyz5 113 120000 13
prashanth m 116 22may1956 02may2005 xyz1 113 13000 12
karthik d 117 02apr1989 02apr2006 xyz3 114 14000 14
Creating department table

create table department2(dept_name varchar2(10),dept_no
varchar2(10));

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


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





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)

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


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




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


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

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





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
11 hyderabad
12 chennai
12 hyderabad
13 bangalore
14 Goa
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
6
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

15 Jaipur
6 rows selected.


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
101 sb1 500
102 sb2 400
201 sb3 900
215 sb4 700
217 sb3 715
222 sb5 700
305 sb6 350
7 rows selected.
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
7
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)


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.






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



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
11 sb6 900
14 sb1 1500
15 sb2 1500
16 sb2 1300
17 sb1 1000
23 sb5 2000
93 sb4 500
7 rows selected.




Creating borrower table


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

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.


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

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

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







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

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


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










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

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


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


select * from reserves;


SID BID RDATE
1111 101 10-may-09
1112 102 23-mar-89
1113 103 20-mar-06
1114 104 23-mar-00
1111 105 05-nov-89




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
1111 name1 7 21
1112 bob 6 20
1113 bhatt 6 18
1114 nano 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;
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
13
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)


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



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 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 LNAME
101 11 g
101 11 t
103 12 m


3. Find all employees, who are born in 1950s.
Ans:
select fname,lname from employee where bdate like '%195_'
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
14
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)


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


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



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


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







10. Retrieve the total no. of employees in research department.
Ans:
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
16
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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.


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
1111 name1 7 21
1112 bob 6 20

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


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'


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

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

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




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



3. Find the names of sailors who have reserved a red or
green boat


Ans:


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

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






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

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


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


CUST_NAME LOAN_NO
karthik 11
sreekanth 14
shashank 15
anand 16
babu 17
kishore 17
karthik 23
Giri 93
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
21
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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

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

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



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.
4. Find all customers who have both loan and account
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
23
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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

13. Find the number of depositors at each branch
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
24
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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.















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

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


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


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;


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

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;


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

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


Max(salary)

7000











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

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




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

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


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

ENAME JOB DEPT_NO
King president 10
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
30
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

Ford analyst 10








NOT IN lists: -

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

EMP_NO JOB DEPT_NO
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(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





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



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

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






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;




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




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.


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



SQL>select *from acct_fd_cust_detail;



ACCT_FD_NO CUST_NO
CA612 CA221
CA335 CA120
SB112 SB340
FS771 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
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: -

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


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



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


select * from depositors
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


Outer join:

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


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
506 106 5000

Cross join

Sql> select * from depositors cross join borrowers

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

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

SQL> SELECT 10*5 FROM DUAL;

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

SQL> SELECT 10/5 FROM DUAL;

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

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

FLOOR(num): It returns the largest integer smaller than the given value.
SQL> SELECT FLOOR(123.456) FROM DUAL;


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

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

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;


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





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














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

INITCAP(str): It converts first letter of every word
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
43
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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

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

LENGTH('ABCD')
--------------
5

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

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

INSTR(string, str, m, n): It displays nth occurrence
of str in the string string starting from m.

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

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 given
string with specified character or string.

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

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

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

Explanation: To the given string "BCD" add "A" to
the left necessary number of times to make it a string
of 3 characters.




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



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

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

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

RTRIM('
-------
TONY BL

ASCII(): Displays equivalent ASCII value of a
character.
SQL > SELECT ASCII('A') FROM DUAL;
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
49
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)


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;

COSH(0)
----------
1

SIN(x) : It returns sine of x.

SQL> SELECT SIN(0) FROM DUAL;

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

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

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


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


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;

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

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

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








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









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.

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

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

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;

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;












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





















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


OUTPUT:
1
2
3
4
5
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
58
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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;
while radius<=7
loop
area:=pi*power(radius,2);
insert into areas values(radius,area);
radius:=radius+1;
end loop;
end;

OUT PUT:-

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

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


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;
n:=n+1;
end loop;
End;

OUTPUT:

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

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

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

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

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


CASE

WHEN score BETWEEN 80 AND 100 THEN

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

WHEN score BETWEEN 65 AND 79 THEN 'B'

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

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

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 }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
VIGNAN INSTITUTE OF TECHNOLOGY & SCEINCE.DESHMUKHI DBMS Lab Manual
69
Dept of Computer Science & Engineering LAB Manual for 2008 -2009 (II II)

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


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


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.


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


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;

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

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

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



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

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

DROP TRIGGER trigger_name;

Você também pode gostar