0% found this document useful (1 vote)
281 views73 pages

II Cse Dbms Lab Manual

This document describes the objectives and topics covered in a Database Management Systems lab. The objectives are to teach students database design, querying using SQL and PL/SQL. The document lists 12 topics that will be covered, including creating and querying tables, joins, aggregates, functions, PL/SQL programming, stored procedures and functions, packages, triggers and more. It also provides examples of creating tables, inserting data, queries and a PL/SQL program to retrieve and print student marks from a table.

Uploaded by

Mouna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
281 views73 pages

II Cse Dbms Lab Manual

This document describes the objectives and topics covered in a Database Management Systems lab. The objectives are to teach students database design, querying using SQL and PL/SQL. The document lists 12 topics that will be covered, including creating and querying tables, joins, aggregates, functions, PL/SQL programming, stored procedures and functions, packages, triggers and more. It also provides examples of creating tables, inserting data, queries and a PL/SQL program to retrieve and print student marks from a table.

Uploaded by

Mouna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 73

DATA BASE MANAGEMENT SYSTEMS LAB

DATA BASE MANAGEMENT SYSTEMS LAB

Objectives:
To teach the student database design and query and PL/SQL.
Recommended Systems/Software Requirements:
Intel based desktop PC
Mysql /Oracle latest version Recommended
1) Creation, altering and droping of tables and inserting rows into a table (use constraints
while creating tables) examples using SELECT command.
2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.
Example:- Select the roll number and name of the student who secured fourth rank in the class.
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
4) Queries using Conversion functions (to_char, to_number and to_date), string functions

(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
Functions (Sysdate, next_day, add_months, last day, months between, least, greatest, trunk,
round, to char, to date)
5) i) Creation of simple PL/SQL program which includes declaration section, executable
section
and exception Handling section (Ex. Student marks can be selected from the table and
printed for those who secured first class and an exception can be raised if no records were
Found)
ii) Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.

6) Develop a program that includes the features NESTED IF, CASE and CASE expression.
The program can be extended using the NULLIF and COALESCE functions.
7) Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT IN Exceptions, USE defined Exceptions, RAISEAPPLICATION ERROR.
8) Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
9) Program development using creation of stored functions, invoke functions in SQL
Statements and write complex functions.
10) Program development using creation of package specification, package bodies, private
objects, package variables and cursors and calling stored packages.
11) Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
12) Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
TEXT BOOKS :
1)ORACLE PL/SQL by example. Benjamin Rosenzweig, Elena Silvestrova, Pearson
Education 3rd Edition
2)ORACLE DATA BASE LOG PL/SQL Programming SCOTT URMAN, Tata McGraw Hill.
3)SQL & PL/SQL for Oracle 10g, Black Book, Dr.P.S. Deshpande.

List of Programs
1. Perform the DDL and DML operations
2. Perform the Set Comparison operations
3. Queries Using Aggregate functions, Group By, Having, and Views
4. Queries using Conversion functions, String functions, Date functions
5. Create a Pl/SQL program and use Commit, Rollback, Save point operations
6. Develop a program using Conditional statements( If, Nested If, Case, etc)
7. Develop a program using Control Statements, Error Handling and Exceptions
8. Create a Procedure with passing parameters In and Out
9. Create Stored functions, Invoked functions, and write Complex functions
10. Create Package Specification, bodies, private objects, Stored packages
11. Write a program using Cursor, Update , Where Current, and cursor variables
12. Develop a Trigger (before and after)-Row, Statement and Nested of Trigger.
Add-on Programs
1. Performing database backup and restore operations in a database instance
2. Usage of SQL loader to create a large volumes of data

TEXT BOOKS:
1) ORACLE PL/SQL by example. Benjamin Rosenzweig, Elena Silvestrova, Pearson
Education 3rd Edition.
2) ORACLE DATA BASE LOG PL/SQL Programming SCOTT URMAN, Tata McGraw Hill.
3) SQL & PL/SQL for Oracle 10g, Black Book, Dr. P. S. Deshpande.

TASK I
Creation, altering and dropping of tables and inserting rows into a table (use Constraints
while creating tables) examples using SELECT command.
DESCRIPTION:
To perform the queries on DDL and DML statements
Types of DDL:
1. Create
2. Alter
3. Drop
4. Truncate
Syntax:
1. Create table <table name>
(<column name 1> <data type>(<size>),
(<column name 2> <data type>(<size>)..);
2. Alter table <table name>
ADD (<new column name> <data type>(<size>),
(<new column name> <data type>(<size>) );(Adding new columns)
MODIFY (<column name > < new data type > (<new size)); ( Modifying columns)
DROP Column <column name > (Dropping a column)
3. Drop table < table name>
4. Truncate table < table name>
DML STATEMENTS:
1. Insert
2. Select
3. Delete
4. Update
1. Insert into<table name> (<field name1>,<field name2>..)
Values (field value1, field value 2)
2. Select <field names_ list>from table name Where (condition)
3. Delete from <table name> Where (condition)
4. Update < table name >
Set(<field name 1 >=<value>(or) <expression>)
Where(<field name>=<value (or)<expression>)
1.write a DDL Statement to create the sailors table.
create table sailors(sid number(10) primary key,sname char(10),rating integer,age real)
Table created.
2. write a DML Statement to insert the values into sailors table.
insert into sailors(sid,sname,rating,age) values(22,'dustin',7,45.0)

1 row created.
insert into sailors(sid,sname,rating,age) values(29,'brutus',1,33.0)
1 row created.
insert into sailors(sid,sname,rating,age) values(31,'lubber',8,55.5)
1 row created.
insert into sailors(sid,sname,rating,age) values(32,'andy',8,25.5)
1 row created.
insert into sailors(sid,sname,rating,age) values(58,'rusty',10,35.0)
1 row created.
insert into sailors(sid,sname,rating,age) values(64,'horatio',7,35.0)
1 row created.
insert into sailors(sid,sname,rating,age) values(71,'zorba',10,16.0)
1 row created.
insert into sailors(sid,sname,rating,age) values(74,'horatio',9,35.0)
1 row created.
insert into sailors(sid,sname,rating,age) values(85,'art',3,25.5)
1 row created.
insert into sailors(sid,sname,rating,age) values(95,'bob',3,63.5)
1 row created.
3. write a DDL Statement to list all the data from sailors table
select * from sailors;
SID

SNAME

RATING

AGE

22 dustin

45

29 brutus

33

31 lubber

55.5

32 andy

25.5

58 rusty

10

35

35

10

16

74 horatio

35

85 art

25.5

95 bob

63.5

64 horatio
71 zorba

10 rows selected.

4. write a DDL Statement to create the Boats table.


create table boats(bid number(10) primary key,bname char(10),color char(10));
Table created.
5. write a DML Statement to insert the values into Boats table.
insert into boats(bid,bname,color) values(101,'interlake','blue')

1 row created.
insert into boats(bid,bname,color) values(102,'interlake','red')
1 row created.
insert into boats(bid,bname,color) values(103,'clipper','green')
1 row created.
insert into boats(bid,bname,color) values(104,'marine','red')
1 row created.
6. write a DDL Statement to list all the data from boats table
select * from boats
BID

BNAME

COLOR

101 interlake

blue

102 interlake

red

103 clipper

green

104 marine

red

4 rows selected
7. write a DDL Statement to create the Reserves table.
create table reserves(sid number(10),bid number(10),day date,foreign key(sid)
references sailors,foreign key(bid) references boats)
Table created.
8. write a DML Statement to insert the values into reserves table.
insert into reserves(sid,bid,day) values(22,101,'10-oct-98')
1 row created
insert into reserves(sid,bid,day) values(22,102,'10-oct-98')
1 row created
insert into reserves(sid,bid,day) values(22,103,'10-aug-98')
1 row created
insert into reserves(sid,bid,day) values(22,104,'10-jul-98')
1 row created
insert into reserves(sid,bid,day) values(31,102,'11-oct-98')
1 row created
insert into reserves(sid,bid,day) values(31,103,'11-jun-98')
1 row created
insert into reserves(sid,bid,day) values(31,104,'11-dec-98')
1 row created
insert into reserves(sid,bid,day) values(64,101,'9-may-98')
1 row created
insert into reserves(sid,bid,day) values(64,102,'9-aug-98')
1 row created

insert into reserves(sid,bid,day) values(74,103,'9-aug-98')


1 row created
9. write a DDL Statement to list all the data from reserves table
select * from reserves
SID

BID

DAY

22

101 10-OCT-98

22

102 10-OCT-98

22

103 10-AUG-98

22

104 10-JUL-98

31

102 11-OCT-98

31

103 11-JUN-98

31

104 11-DEC-98

64

101 09-MAY-98

64

102 09-AUG-98

74

103 09-AUG-98

10 rows selected.

10.Write a statement that display the names and ages of all sailors
select s.sname,s.age from sailors s
SNAME

AGE

dustin

45

brutus

33

lubber

55.5

andy

25.5

rusty

35

horatio

35

zorba

16

horatio

35

art

25.5

bob

63.5

10 rows selected.
11.write a DDL statement to add the column(i.e; Contact no. to the sailors table)
alter table sailors add contactnumber integer
Table altered.

Select * from sailors


SID

SNAME

RATING

AGE

22 dustin

45

29 brutus

33

31 lubber

55.5

32 andy

25.5

58 rusty

10

35

35

10

16

74 horatio

35

85 art

25.5

95 bob

63.5

64 horatio
71 zorba

CONTACTNUMBER

10 rows selected.
12. Write a DDL statement to drop the column i.e; contact number from the sailors table
alter table sailors drop column contactnumber
Table altered.
select * from sailors
SID

SNAME

RATING

AGE

22 dustin

45

29 brutus

33

31 lubber

55.5

32 andy

25.5

58 rusty

10

35

35

10

16

74 horatio

35

85 art

25.5

95 bob

63.5

64 horatio
71 zorba

10 rows selected.
13.Write a DDL statement to modify the size of sname field
alter table sailors modify sname char(20)
Table altered.
select * from sailors;
SID

SNAME

RATING

AGE

22 dustin

45

29 brutus

33

31 lubber

55.5

32 andy

25.5

58 rusty

10

35

35

64 horatio

71 zorba

10

16

74 horatio

35

85 art

25.5

95 bob

63.5

10 rows selected.
14.Find all the records with the rating above 7 from the sailors table
select * from sailors where rating>7
SID

SNAME

RATING

AGE

31 lubber

55.5

32 andy

25.5

58 rusty

10

35

71 zorba

10

16

35

74 horatio

15. Find all the details of boats having the name as Interlake
select * from boats where bname='interlake'
BID

BNAME

COLOR

101 interlake

blue

102 interlake

red

16. Write a DML statement to list different names available in sailors


Select distinct(sname) from sailors
SNAME
horatio
bob
brutus
art
dustin
andy
rusty
zorba
lubber
9 rows selected.

17. List all the data in sailors in sorted order with respect to sname

Select * from sailors order by sname


SID
SNAME

RATING

AGE

32 andy

25.5

85 art

25.5

95 bob

63.5

29 brutus

33

22 dustin

45

64 horatio

35

74 horatio

35

31 lubber

55.5

58 rusty

10

35

71 zorba

10

16

10 rows selected.
18. List all the names start with letter a in the sailors table.
select sname from sailors where sname like 'a%'
SNAME
andy
art
19.List all the namesin the sailors table end with tio
Select distinct sname from sailors where sname like %tio%
SNAME
horatio
20.Truncate the boats table.
Truncate table boats
Table truncated.
TASK 2
2) Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS,
UNION,INTERSET, Constraints.
DESCRIPTION:
To perform the queries on set comparison operations.
21. Find the names of Sailors who have reserved red boat
select s.sname
from sailors s,reserves r
where r.bid=103 and r.sid=s.sid

SNAME
dustin
lubber
horatio
22. Find the sid of Sailors who have reserved red boats
select sid
from reserves r,boats b
where b.color='red' and r.bid=b.bid
SID
22
22
31
31
64

23. Find names of Sailors who had reserved a red color boat.
select sname from
sailors s,reserves r,boats b
where b.color='red' and b.bid=r.bid and r.sid=s.sid

SNAME
dustin
dustin
lubber
lubber
horatio

24. Find the colors of boats reserved by lubber


select b.color from sailors s,reserves r,boats b
where s.sname='lubber' and s.sid=r.sid and r.bid=b.bid

COLOR
red
green
red
25. Find names of Sailors who have reserved at least one boat

select distinct sname from sailors s,reserves r where s.sid=r.sid

SNAME
horatio
dustin
lubber
26. Find names of Sailors who have reserved red or a green boat
select distinct s.sname from sailors s,reserves r,boats b
where (b.color='red' or b.color='green') and (b.bid=r.bid and r.sid=s.sid)
SNAME
horatio
dustin
lubber
27.. Find names of Sailors who have reserved red or a green boat
select distinct s.sid from sailors s,reserves r,boats b
where (b.color='red' or b.color='green') and (b.bid=r.bid and r.sid=s.sid)
SID
22
31
74
64

28. Find names of Sailors who have reserved red and a green boat
select distinct s.sname from sailors s,reserves r,boats b
where b.color='red' and b.color='green' and b.bid=r.bid and r.sid=s.sid

SNAME
dustin
lubber

29. Find sids of sailors who have reserved a red boat and a green boat by using union clause
select s.sid from sailors s,reserves r,boats b
where b.color='red' and b.bid=r.bid and r.sid=s.sid
union select s1.sid from sailors s1,reserves r1,boats b1
where b1.color='green' and b1.bid=r1.bid and r1.sid=s1.sid

SID
22
31
64
74

30. Find snames of sailors who have reserved a red boat and a green boat by
using union clause

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


where b.color='red' and b.bid=r.bid and r.sid=s.sid
union select s1.sname from sailors s1,reserves r1,boats b1
where b1.color='green' and b1.bid=r1.bid and r1.sid=s1.sid

SNAME
dustin
horatio
lubber
31. Find sids of sailors who have reserved a red boat and a green boat by using intersect clause
select s.sid from sailors s,reserves r,boats b
where b.color='red' and b.bid=r.bid and r.sid=s.sid
intersect select s1.sid from sailors s1,reserves r1,boats b1
where b1.color='green' and b1.bid=r1.bid and r1.sid=s1.sid
SID
22
31
32. Find snames of sailors who have reserved a red boat and a green boat by using intersect
clause
select s.sname from sailors s,reserves r,boats b
where b.color='red' and b.bid=r.bid and r.sid=s.sid
intersect select s1.sname from sailors s1,reserves r1,boats b1
where b1.color='green' and b1.bid=r1.bid and r1.sid=s1.sid

SNAME
dustin
Lubber

33.Find sids of all sailors who reserved redboat but not green boat
select r.sid from reserves r,boats b
where b.color='red' and b.bid=r.bid
minus select r1.sid from reserves r1,boats b1
where b1.color='red' and b1.bid=r1.bid

SID
64

Nested Queries:
34.Find the names of Sailors who have reserved the boat no 103
Select s.sname from sailors s Where s.sid in (select r.sid
from reserves r

where r.bid=103)
SNAME

dustin
horatio
lubber
35. Find the names of Sailors who have reserved a red boat by implementing nested queries
Select s.sname
from sailors s
Where s.sid in (select r.sid
from reserves r
where r.bid
in (select b.bid
from boats b
where b.color=red))
SNAME
dustin
horatio
lubber
36. Find the names of Sailors who have reserved a red boat.
Select s.sname
from sailors s
Where s.sid in (select r.sid
from reserves r
where r.bid (select b.bid
from boats b

where b.color=red))
SNAME
dustin
horatio
lubber
horatio
37.Find the names of sailors who have reserved boat no.103 using exists clause
Select s.sname from sailors s where exists(select *

from reserves r

where r.bid =103 and r.sid=s.sid)


SNAME
dustin
horatio
lubber
38.Find the names of sailors who have reserved boat no.103 using exists clause
Select s.sname from sailors s
from reserves r

where s.sid in (select r.sid

where r.bid=103)
SNAME

dustin
horatio
lubber

39. Find the names of sailors who have reserved boat no.103 using not exists clause
Select s.sname from sailors s where not exists (select r.sid
from reserves r where r.bid=103 and r.sid=s.sid)

SNAME
Zorba
art
rusty
Horatio
Andy
Brutus
bob
40. Find sailors sids Whose rating is better than some sailor called horatio.
Select s.sid

from sailors s
where(s.rating > all(select s.rating
from sailors s
where s.sname=horatio))

SID
58
71
41.Find the sailors with highest rating.
Select s.sid
from sailors s
where s.rating >= all(select s1.rating
from sailors s1)
SID
58
71

42.Find the names of sailors who have reserved both red and green boats by using IN.
Select s.sname
from sailors s,boats b,reserves r
where b.color=red and b.bid=r.bid and r.sid=s.sid
and s.sid in (select s1.sid
from sailors s1,boats b1,reserves r1
where b1.color=red and b1.bid=r1.bid and r1.sid=s1.sid)
SNAME
dustin
Dustin
lubber
Lubber
43. Find the names of sailors who have reserved both red and green boats by using IN and
INTERSECT.
Select s.sname from sailors s where s.sid in(Select s1.sid
from sailors s1,boats b1,reserves r1
where b1.color=red and b1.bid=r1.bid and r1.sid=s1.sid)
intersect (Select s2.sid from sailors s2,boats b2,reserves r2
where b2.color=green and b2.bid=r2.bid and r2.sid=s2.sid)

SNAME
dustin
Lubber
44. Find the names of sailors who have reserved all boats.
Select s.sname from sailors s
where not exists(select b.bid from boats b minus(select r.bid
from reserves r
where r.sid =s.sid)
SNAME
dustin

45. Find the names of sailors who have reserved red boat but not blue boats.
Select s.sname
from sailors s,boats b,reserves r
where b.color=red and b.bid=r.bid and r.sid=s.sid
minus
Select s1.sname
from sailors s1,boats b1,reserves r1
where b1.color=blue and b1.bid=r1.bid and r1.sid=s1.sid
SNAME
lubber

Task-3
3) Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
DESCRIPTION:
To perform the queries on aggregate functions.
1.Find the average age of all the sailors.
Select AVG(age)
from sailors
AVG(AGE)
36.9
2. Find the average age of all the sailors with a rating of 10
Select AVG(age)
from sailors s
where s.rating=10
AVG(DISTINCT.RATING)
36.9
3. Find the name and age of the oldest sailor.
Select s.sname,s.age
From sailors s
Where (s.age=(select MAX(s1.age) from sailors s1)
SNAME

AGE

bob

63.5

4.Count the number of sailors


Select count(*)
From sailors
COUNT(*)
10

5. Count the number of different sailors name.


Select count(distinct s.sname)
From sailors s
COUNT(DISTINCT.SNAME)
9
6. Find the names of the sailors who are older than the oldest sailor with a rating of 10
Select s.sname
From sailors s
Where (s.age >(select max(s1.age)
From sailors s1
Where s1.rating=10))

SNAME
dustin
Bob
lubber
GROUP BY HAVING CLAUSES:
7. Find the age of the youngest sailor for each rating level.
Select s.rating,Min(s.age)
From sailors s
Group by s.rating
RATING

MIN(S.AGE )

33

25.5

35

25.5

10

16

35

8. Find the age of the youngest sailor who is eligible to vote i.e;atleast for each rating level
With atleast two such sailors
Select s.rating,Min(s.age)
From sailors s
Where s.age>=18
Group by rating
Having count(*)>1
RATING

MIN(S.AGE )

25.5

35

25.5

9. For each red boat find the number of reservations for this boat.
Select b.bid,count(*)
from reserves r,boats b
where b.color=red and b.bid=r.bid
group by b.bid
BID

COUNT(*)

102

104

10. Find the avg age of Sailors for each rating level that has atleast two such sailors
Select s.rating,Avg (s.age)
From sailors s
Groupby s.rating
Having count(*)>1

RATING

MIN(S.AGE )

40.5

40

44.5

10

25.5

11. Find the avg age of sailors who are of voting age i.e;atleast 18 years old for each rating
level With atleast two such sailors
Select s.rating,Avg (s.age)
From sailors s Where s.age>=18
Groupby s.rating
Having count(*)>1
RATING

MIN(S.AGE )

40.5

40

44.5

12. Find the avg age of sailors who are of voting age i.e;atleast 18 years old for each rating
level With exactly two such sailors.
Select s.rating,Avg (s.age)
From sailors s
Where s.age>=18

Groupby s.rating
Having count(*)>1
RATING

MIN(S.AGE )

40.5

40

44.5

13.Find those ratings for which the avg age of allsailors is the min over all ratings
Select s.rating From sailors s
Where avg(s.age)=select min(avg(s2.age))
From sailors s2
Group by s2.rating
RATING
8
3
Creation and dropping of views:
14. Create view that contain all sailors who reserved atleast one boat.
Create view sailors1
as select s.sid,s.sname,s.rating,s.age
from sailors s,reserves r
where s.sid=r.sid
view created.
15. Create view that contain all boats data.
Create view boats1
As select b.bid,b.bname,b.color
from boats b
view created.
Select * from boats1
BID

BNAME

COLOR

101 interlake

blue

102 interlake

red

103 clipper

green

104 marine

red

16. Select all data from the view sailors with sid as 22
Select * from sailors1
Where sid=22

SID

SNAME

RATING

22 dustin

AGE
7

17. Update boats1 where bname is interlake to XXX.


Update boats1
Set bname=XXX
Where bname=Interlake
2 rows updated.
Select * from boats1
BID

BNAME

COLOR

101 XXX

blue

102 XXX

red

103 clipper

green

104 marine

red

18. Drop the view boats1


Drop view boats1
View dropped.

45

TASK 4
Queries using Conversion functions (to_char, to_number and to_date), string functions
(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr), date
functions (Sysdate, next_day, add_months, last_day, months_between, least, greatest, trunk,
round, to_char, to_date)
DESCRIPTION:
To perform the queries on conversion functions and date functions with respect to the syntax
given below.
Conversion Functions:To_char:
Converts a value of number datatype to character datatype.
Syntax:
To_char(n,[fmt])
Where n is the number and fmt is the format to accept in which the number have to
appear.
Ex:
select to_char(17145,'$99,999') "char" from dual
Output:
char
$17,145
To_number:
Converts a character value expressing a number to a number datatype.
Syntax:
To_number(char)
Ex:
select to_number(17145) number from dual
Output:
number
17145
To date:
Converts a value of date datatype to char value.
Syntax:
To_char(date,[fmt])
To char accepts a date as well as the format in which the date has to be appeared. Fmt
is the date format, if fmt is ommited, the date is converted into char value using the default date
format.
Ex:
Select to_char(Sysdate,month,dd,yyyy) Date from dual

Output:
number
march ,13,2009
String Functions:Concatenation:
The function is used to concatenate two strings.
Syntax:
Concat(n1,n2)
Where n1 is the string1 and n2 is the string2
Ex:
Select concat(for,est) String from dual
Output:
string
forest
Lpad:(left padding)
Returns char1, left padded to length n with the sequence of characters specified in char2. If
char2 is not specified oracle uses blank by default.
Syntax:
LPAD(char1,n,[char2])
Ex:
select LPAD(sunil,10,*) LPAD from dual
Output:
LPAD
*****sunil
Rpad:(Right Padding)
Returns char1, right padded to length n with the sequence of characters specified in
char2. If char2 is not specified oracle uses blank by default.
Syntax:
RPAD(char1,n,[char2])
Ex:
select RPAD(sunil,10,*) RPAD from dual
Output:
RPAD
sunil*****
Ltrim:(left trimming)
Removes char from left of char with the initial characters removed upto the first
character not in set.

Syntax:
LTRIM(char,[set])
Ex:
select LTRIM(vasavi,v) LTRIM from dual.

Output:
LTRIM
asavi
Rtrim:(right trimming)
Removes char from right of char with the last characters removed upto the first character
not in set.
Syntax:
RTRIM(char,[set])
Ex:
select RTRIM(vasavi,i) RTRIM from dual.
Output:
RTRIM
vasav
Lower:
Returns char with all letters in lower case.
Syntax:
Lower(char)
Ex:
Select lower(IVAN BAYROSS) Lower from dual
Output:
Lower
ivan bayross
Upper:
Returns char with all letters in upper case.
Syntax:
Upper(char)
Ex:
Select upper(ivan bayross) Upper from dual
Output:
Upper
IVAN BAYROSS
Initcap:
Returns a string with the letter of each word in uppercase.

Syntax:
Initcap(char)
Ex:
Select initcap(vasavi) Initcap from dual
Output:
Initcap
Vasavi
Length:
Returns the length of the word
Syntax:
Length(word)
Ex:
Select length(DBMS) Length from dual

Output:
Length
4
Substring:
Returns a portion of chars beginning M and going upto chars n. If n is omitted the
resultreturned upto last character in the string, the first portion of string is 1.
Syntax:
SUBSTR(<string>,<start_position>,[<length>])
Where <string> is input string or source string, start position is the position of
extraction, the first position of the string is always 1,length is the number of characters to
extract.
Ex:
Select SUBSTR(vasavi,2,4) Substr from dual
Output:
Substr
asav
Instring:
Returns the location of a substring in a string
Syntax:
INSTR(<string1>,<string2>,[start_position],[n th appearance])
A string is the source string1,string2 is the substring to search for a string1,start position
is the position in string1 where the search will start,if omitted it defaults to one.
The first position in the string is 1,if start position is negative. The function counts back
start position number of characters from the end of the string1 and then searches towards the
beginning of string.n th appearance is the appearance of string2. If omitted it defaults
Ex:

Select INSTR(set on the net,t,1,2) INSTR from dual


Output:
INSTR
8
Date Functions:Sysdate:
Used to display the system date
Ex:
Select sysdate from dual
Output:
SYSDATE
13-MAR-09
Next_day:
Returns the date of the first TASKday named by char that is offered by the date named
date,char must be day of the TASK
Syntax:
Next_day(date,char)
Ex:
Select Next_day(25-jan-09,sunday) Next_day from dual
Output:
Next_day
01-FEB-09
Add_months:
Returns the date after adding the number of months specified in the function
Syntax:
Add_months(d,n)
Where d is the date,n is the value.
Ex:
Select add_months(sysdate,5) date from dual
Output:
date
28-JAN-09
Last_day:
Returns the last date of the month specified in the function
Syntax:
Last_day(d)
Ex:
Select last_day(sysdate) last_day from dual
Output:

last-day
31-MAR-09
Months_between():
Returns the number of months between the two specific months i.e., d1 and d2
Syntax:
Months_between(d1,d2)
Ex:
Select Months_between (02-Apr-92,02-Jan-92) diff from dual
Output:
diff
3
Least:
Returns the least value in a list of expressions in the input n expressions
Syntax:
Least(expr1,expr2,exprn)
Where expr1,expr2,..exprn are the expressions that are evaluated by the least
functions
Ex:
Select least(4,6,7,19) num from dual
Output:
num
4
Greatest:
Returns the greatest value in a list of expressions in the input n expressions
Syntax:
greatest(expr1,expr2,exprn)
Where expr1,expr2,..exprn are the expressions that are evaluated by the least
functions
Ex:
Select greatest(4,6,7,19) num from dual
Output:
num
19

Truncate:
Returns a number truncated to a certain number of decimal places. The decimal place
value must be an integer. If this parameter is omitted, the truncate function will truncate the
number to zero decimal places
Syntax:
Trunk(number,[decimal places])

Ex:
Select trunk(125.835,1) trunk from dual
Output:
trunc
125.8
Round:
Returns n rounded to m places to theright of the decimal point. If m is omitted n is rounde
to 0 places
Syntax:
Round)n.[m])
Ex:
Select round(15.19,1) round from dual
Output:
round
15.2
To_char:
The to_char function facilitates the retrieval of data in the format different from the
default format
Syntax:
To_char(<datavalue>,[<fmt>])
Where date value stands for the input date and fmt is specified format in which the
date have to be displayed
Ex:
Select to_char(sysdate,dd-mm-yyyy) to_char from dual
Output:
to_char
13-03-2009
To_date:
To_date converts a char value into date value. It allows the user to insert date into date
column in any required format by specifying char value of the date
Syntax:

To_date(<char value>,[<fmt>])

Ex:
Select to_date(06/07/02,dd/mm/yyyy) to_date from dual
Output:

to_date
06-JUL-02

TASK-5
5) i) Creation of simple PL/SQL program which includes declaration section,
executable section and exception Handling section (Ex. Student marks can
be selected from the table and printed for those who secured first class and
an exception can be raised if no records were found)
ii)Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT
in PL/SQL block.
Description: To develop the PL/SQL program we include the following tools which we
prescribe are block structure, execution statements.
PL/SQL-PROGRAMMING LANGUAGE
FEATURES:
It is a procedure language.
It is developed by oracle company.
Used only with oracle.

It process only row at time where non-procedural language process a set of rows at
time.
BLOCK STRUCTURE:
>declare
<variable declaration>;
Begin
<executable statements>;
Exception;
<executable statements>;
End;
EXECUTABLE STATEMENTS:
1. DML allowed.
2. TCL allowed.
3. DDL and DCL are not allowed.
4. select<column list>into<variable list> from<table name> where<condition>;
5. single line comment;
/*Multi
Line
Comment*/
6. dbms_output.put_line(message||variable);
Used to print variables and messages.
DBMS_OUTPUT->It is a package.
7. set serveroutput on
(used to activities dbms.statements.)
:=it for external value
Into----used with select command.
Sal number(7,2);
Note:- select statements must return one and only one row.
Create table students(sno number(2), sname char(20),m1 integer,m2 integer);
Table created.
Insert into students(sno,sname,m1,m2) values(101,david,20,30);
1 row created;
Insert into students(sno,sname,m1,m2) values(102,rajesh,70,80);
1 row created;
Insert into students(sno,sname,m1,m2) values(103,lavanya,60,40);
1 row created;
Insert into students(sno,sname,m1,m2) values(104,kumar,90,90);
1 row created;
Insert into students(sno,sname,m1,m2) values(105,malini,20,40);
1 row created;
Select * from students;

Sno

Sname

M1

M2

101

David

20

30

102

Rajesh

70

80

103

Lavnya

60

40

104

Kumar

90

90

105

Malini

20

40

Declare
M1 integer;
M2 integer;
Tot integer;
Avg real;
Count integer;
I integer;
St char(20);
Select count(*) into count from students I;
I=101;
While i<=cnt
Loop
Select M1 into M1 from students where sno=I;
Select M2 into M2 from students where sno=I;
Tot:=M1+M2;
Avg=Tot/2;
If Avg>60 then
Select sname from students where sno=I;
Dbms_output.put_line(st);
End if;
I:=I+1;
End loop;
End;
Sname
Rajesh
Kumar
PL / SQL procedure successfully completed;
2) Create a pl/sql script which include a declarable section ,an executable section, an
exception handling section. The student marks can be taken as an input and the students whose
average is greater than 60,that is who secured first class should be retrieve. If no records were
found and an exception should be raised i.e no records found.
Create table students(sno number(2), sname char(20),m1 integer,m2 integer);
Table created.
Insert into students(sno,sname,m1,m2) values(101,david,20,30);
1 row created;
Insert into students(sno,sname,m1,m2) values(102,rajesh,70,80);
1 row created;

Insert into students(sno,sname,m1,m2) values(103,lavanya,60,40);


1 row created;
Insert into students(sno,sname,m1,m2) values(104,kumar,90,90);
1 row created;
Insert into students(sno,sname,m1,m2) values(105,malini,20,40);
1 row created;

Select * from students;


Sno

Sname

M1

M2

213

David

20

30

341

Rajesh

70

80

901

Lavnya

60

40

568

Kumar

90

90

156

Malini

20

40

Set serveroutput on;


Declare
Cursor rid is select sno from students;
Rid_val rid%rowtype;
M1 integer;
M2 integer;
Avg Float;
Sname char(20);
Begin
Open rid;
Loop
Fetch rid into rid_val;
Exit when rid%NOTFOUND;
Select m1 into from m1 students where sno=rid_val.sno;
Select m2 into from m2 students where sno=rid_val.sno;
Avg:=(m1+m2)/2;
If avg>60 then
Select sname into sname from students where sno=rid_val.sno;
Dbms_output.put_line(sid,sname);
End if;
End loop;
End;
Sid

Sname

341 Rajesh
568 Kumar
PL / SQL procedure successfully completed;

b) Insert data into student table using COMMIT,ROLLBACK and SAVEPOINTS in PL/SQL
block.

TASK-6
program that includes the features NESTED IF, CASE and CASE expression.
Theprogram can be extended using the NULLIF and COALESCE functions.
Description: To develop a PL/SQL program we use the following tools like NESTED IF,
CASE and COLASCE functions.
NESTED IF:
IF <condition> THEN
SQL statements.
ELSIF<condition> THEN
SQL statements.
ELSIF<condition> THEN
SQL statements.
ELSE
SQL statements
END IF;
CASE:
It is similar to switch case concept.
Syntax:
Case variable
When<value 1> then
<statements>;
When<value 2> then
<statements>;
.
.
.
.
.
Else
<statements>;
End case;
COALESCE:
The COALESCE function is similar to the IFNULL function in that it is used to specifically
replace NULL values within the result set. The COALESCE function can accept a whole set of
values and checks each one in order until if finds a non-NULL result. If a non-NULL result is
not a present, COALESCE returns a NULL value.

1) Develop a program that takes the input (marks of a particular student) develop a
PL/SQL script
>70

-A

>=60 and <=70

-B

>=50 and <=60

-C

Otherwise -D
set serveroutput on;
declare
avg_marks number:=&avg_marks;
grade char(2);
begin
if avg_marks>70 then grade:='A';
elsif avg_marks>=60 and avg_marks<=70 then
grade:='B';
elsif avg_marks>=50 and avg_marks<60 then
grade:='C';
else
grade:='D';
end if;
dbms_output.put_line('The grade is '||grade);
end;
Output:
Enter value for avg_marks :75
old 2: avg_marks number:=&avg_marks;
new 2: avg_marks number:=78;
The grade is A
PL/SQL procedure successfully completed.
2) Input a grade value for a student and print the corresponding grade as the output using case.
declare
grade char(1):=&grade;
begin
case grade
when 'A' then dbms_output.put_line('Grade is A');
when 'B' then dbms_output.put_line('Grade is B');
when 'C' then dbms_output.put_line('Grade is C');
dbms_output.put_line('Grade is none');
end case;
end;
Output:
Enter value for grade: A
old 2: grade char(1):=&grade;
new 2: grade char(1):='A';
Grade is A
PL/SQL procedure successfully completed.

3) Develop a program that includes the features nested if, case and case expression. The
program can be extended using the nullif and coalesce functions.
set serveroutput on;
declare
avg_marks number:=&avg_marks;
grade char(2);
begin
if avg_marks>70 then
grade:='A';
elsif avg_marks>=60 and avg_marks<=70 then
grade:='B';
elsif avg_marks>=50 and avg_marks<60 then
grade:='C';
else
grade:='D';
end if;
case grade
when 'null' then dbms_output.put_line('Grade is null');
when 'A' then dbms_output.put_line('Grade is A');
when 'B' then dbms_output.put_line('Grade is B');
when 'C' then dbms_output.put_line('Grade is C');
else
dbms_output.put_line('The grade is none');
end case;
end;
Output:
Enter value for avg_marks : 75
old 2: avg_marks number:=&avg_marks;
new 2: avg_marks number:=75;
Grade is A
PL/SQL procedure successfully completed.
4) write a program PL/SQL script that calculate area of the circle and if area is greater than 30
then the value should be inserted into areas table.
set serveroutput on;
declare
pi constant number(2):=3.14;
radius real:=&radius;
area number(2);
begin
area:=pi*power(radius,2);
if area>30 then
insert into areas values(radius,area);
else

dbms_output.put_line(area);
end if;
end;
Output:
Enter value for radius:3.0
old 3: radius real:=&radius;
new 3: radius real:=3.0;
27
PL/SQL procedure successfully completed
5) write a PL/SQL script that accepts the empno as the input from the employee table and print
the corresponding dept no as output.
set serveroutput on;
declare
empn number(8):=&empn;
dept number(8);
begin
select deptno into dept from emp where empno=empn;
dbms_output.put_line(dept);
end;
Output:
Enter value for empn:7369
old 2: empn number(8):=&empn;
new 2: empn number(8):=7369;
20
PL/SQL procedure successfully completed
6) Write a PL/SQL script that implements nullif functions.
create table students(num number, branch varchar(20))
Output:
Table created.
declare
temp number:=27;
begin
if temp<5 then
insert into students(branch) values('CSE');
elsif temp<20 then
null;
else
insert into students(branch) values('IT');
end if;
end;
Output:
PL/SQL procedure successfully completed

select * from students


Output:
NUM

BRANCH
IT

7) Write a PL/SQL script that implements nullif functions


create table students1(ssn number,name char(20),address1 number,address2 number,address3
number)
Output:
Table created
insert into students1 values(1,'a',9,10,11)
Output:
1 row created
insert into students1
values(2,'a',null,5,6)
Output:
1 row created
insert into students1
values(3,'b',null,null,6)
Output:
1 row created
insert into students1
values(4,'b',null,6,null)
Output:
1 row created
select * from students1
Output:
SSN

NAME
1a

ADDRESS1

ADDRESS2
9

2a

ADDRESS3
10

11

3b

4b

select coalesce(address1,address2,address3) result from students1


Output:
RESULT
9
5
6
6

DATA BASE MANAGEMENT SYSTEMS LAB

TASK-7
Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT IN Exceptions, USE defined Exceptions, RAISEAPPLICATION ERROR
Description: To develop PL/SQL program by including the following features like WHILE
LOOP, FOR LOOP.
WHILE LOOP:
It is a pre-tested loop.
Syntax:
WHILE <condition>
LOOP
SQL statements
END LOOP;
FOR LOOP:
Numeric for loop:
Syntax:
FOR variable IN <val 1><val 2>
LOOP
SQL statements.
END LOOP;
User-Defined Exception:
STEP-1 : Declare Exception
STEP-2: Raise in Executable section explicitly using
RAISE Statement
STEP-3: Handle the raised exception.
1.
set serveroutput on;
declare
c number:=0;
begin
while c<=10 loop
c:=c+1;
dbms_output.put_line('the value of c is'||c);
end loop;
end;

40

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
the value of c is1
the value of c is2
the value of c is3
the value of c is4
the value of c is5
the value of c is6
the value of c is7
the value of c is8
the value of c is9
the value of c is10
the value of c is11
PL/SQL procedure successfully completed.
2.
set serveroutput on;
declare
counter integer:=2;
begin
counter:=0;
while counter<6 loop
counter:=counter+1;
dbms_output.put_line(counter);
end loop;
end;
Output:
1
2
3
4
5
6
PL/SQL procedure successfully completed.
3.
set serveroutput on;
declare
v_radius number:=2;
begin
while true loop
dbms_output.put_line('the area is'|| v_radius*v_radius);
41

DATA BASE MANAGEMENT SYSTEMS LAB

exit when v_radius=10;


v_radius:=v_radius+2;
end loop;
end;
Output:
the area is4
the area is16
the area is36
the area is64
the area is100
PL/SQL procedure successfully completed.
5.
set serveroutput on;
declare
counter integer:=2;
begin
for counter in 1..5 loop
dbms_output.put_line(counter);
end loop;
end;
Output:
1
2
3
4
5
PL/SQL procedure successfully completed.
6.
set serveroutput on;
begin
for i in 1..2 loop
for j in 1..4 loop
dbms_output.put_line('outer loop counter is' ||i || 'inner loop counter is'||j);
end loop;
end loop;
end;

42

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
outer loop counter is1inner loop counter is1
outer loop counter is1inner loop counter is2
outer loop counter is1inner loop counter is3
outer loop counter is1inner loop counter is4
outer loop counter is2inner loop counter is1
outer loop counter is2inner loop counter is2
outer loop counter is2inner loop counter is3
outer loop counter is2inner loop counter is4
PL/SQL procedure successfully completed.
7.
set serveroutput on;
declare
loop_start integer:=1;
begin
for i in reverse loop_start..5 loop
dbms_output.put_line(' loop counter is'||i);
end loop;
end;
Output:
loop counter is5
loop counter is4
loop counter is3
loop counter is2
loop counter is1
PL/SQL procedure successfully completed.
8.
set serveroutput on;
begin
for i in 1..6 loop
if mod(i,2)=0 then
dbms_output.put_line(' loop counter is'||i);
end if;
end loop;
end;
Output:
loop counter is2
loop counter is4
loop counter is6
PL/SQL procedure successfully completed.
43

DATA BASE MANAGEMENT SYSTEMS LAB

9.
set serveroutput on;
declare
myvalue integer:=5;
begin
for i in 1..12 loop
myvalue:=myvalue+5;
dbms_output.put_line(myvalue);
exit when myvalue>100;
end loop;
end;
Output:
10
15
20
25
30
35
40
45
50
55
60
65
PL/SQL procedure successfully completed.
10.
set serveroutput on;
begin
for v_loopcounter in 1..20 loop
if mod(v_loopcounter,2)=0 then
dbms_output.put_line(' The area of the circle is'||v_loopcounter*v_loopcounter);
end if;
if v_loopcounter=10 then
exit;
end if;
end loop;
end;

44

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
The area of the circle is4
The area of the circle is16
The area of the circle is36
The area of the circle is64
The area of the circle is100
PL/SQL procedure successfully completed.
11.
set serveroutput on;
declare
v_mychar varchar2(20):='test';
v_number number;
v_date date:=sysdate;
v_counter integer;
begin
dbms_output.put_line('This is a test');
dbms_output.put_line('of syntax error debugging');
for v_counter in 1..5 loop
dbms_output.put_line('You are in loop:'||v_counter);
end loop;
end;
Output:
This is a test
of syntax error debugging
You are in loop:1
You are in loop:2
You are in loop:3
You are in loop:4
You are in loop:5
PL/SQL procedure successfully completed.
12.
create table mytable(num_col number,char_col varchar2(60))
Output:
Table created.
set serveroutput on;
begin
for v_loopcounter in 1..50 loop
insert into mytable(num_col)values(v_loopcounter);
end loop;
end;
45

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
PL/SQL procedure successfully completed.
NUM_COL

CHAR_COL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
46

DATA BASE MANAGEMENT SYSTEMS LAB

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
50 rows selected.

TASK 8
Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
Description: To develop a PL/SQL program by using procedures and calculating simple
interest and compound interest.
PROCEDURE:
47

DATA BASE MANAGEMENT SYSTEMS LAB

Syntax:
Create [OR Replace] Procedure <Procedure name>
[(arguments[Mode]<data type>) IS/AS
<Local variable>
Begin
<Executable statements>
End;
create or replace procedure p1(n in number,m out number)
is begin
m:=n*n*n;
end;
Output:
Procedure created.
Variable x number;
Exec p1(10,:x);
Print :x;
Output:
PL/SQL procedure successfully completed.

X
1000
Create or replace procedure p2(n in number,m out number,o out number)
is begin
m:=n*n;
o:=n*n*n;
end;
Output:
Procedure created.
Var x number;
Var y number;
Exec p2(3,:x,:y)
Print :y:x;
48

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
PL/SQL procedure successfully completed.

Y
27

Create or replace procedure p3(n in out number)


Is begin
N:=n*n*n;
End;
Output:
Procedure created.
Var x number;
Exec :x:=5;
Exec p3(:x);print :x;
Output:
PL/SQL procedure successfully completed.
PL/SQL procedure successfully completed.

X
125

TASK 9
Program development using creation of stored functions, invoke functions in SQL Statements
and write complex functions.
Description: To develop a program to calculate compound interest using functions.
FUNCTION:
49

DATA BASE MANAGEMENT SYSTEMS LAB

Syntax:
Create [OR Replace] FUNCTION <Function name>
(Parameter) RETURN <Data Type> IS/AS
<Local Variable>
Begin
<Executable Statements>;
RETURN(variable);
End;
Programs with functions:
Create or replace function inter(p number,n number,r number)
Return number;
Is ci number;
Begin
Ci:=power((1+r/100),n);
Ci:=p*ci;
Return(ci);
End;
Output:
Function created.
Var init number;
Exec :init :=inter(2000,1,2);
Print :init;
Output:
PL/SQL procedure successfully completed.
CINT
2040
Select inter(200,1,2) from dual;

Output:
INTER(2000,1,2)
2040
To remove a procedure using drop command
Syntax:
Drop procedure procedurename;
50

DATA BASE MANAGEMENT SYSTEMS LAB

To remove a function using drop command


Syntax:
Drop function functionname:

TASK 10
Program development using creation of package specification, package bodies, private
objects, package variables and cursors and calling stored packages.
Description: To develop PL/SQL program including the features like package
specification, package bodies, private objects, package variables and cursors and calling
stored we follow the process as specified.
Syntax for specification:
51

DATA BASE MANAGEMENT SYSTEMS LAB

Create Package<Package name>


IS/AS
<Public variable declaration>;
<subprogram declaration>
END<Package name>;
Syntax for Body:
Create Package Body<Package name>
IS/AS
<Private variable declaration>;
<Subprogram bodies>
END<Package name>;
Packages:
Create or replace package pack as result number;
Procedure p4(a number,b number);
Function p5(x number,y number);
Return number;
End pack;
Output:
Package created
Create or replace package body pack as
Procedure p4(a number,b number)
Is begin
Result :=a+b;
Dbms_output.put_line(sum||result);
End p4;
Function p5(x number,y number)
Return number is
Begin
Result :=x+y;
Return(result);
End p5;
End pack;
Output:
Package Body created.
Exec pack.p4(200,300);
Select pack.p5(20,3) from dual;
52

DATA BASE MANAGEMENT SYSTEMS LAB

Output:
PL/SQL procedure successfully completed.

XPACK.P5(20,3)
23
Set serverouput on;
Exec pack.p4(200,300);
Output:
PL/SQL procedure successfully completed.
Sum 500

TASK 11
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
/program to insert a value into areas(table) Using cursor
create table radius_vals(radius number)
Table created
53

DATA BASE MANAGEMENT SYSTEMS LAB

//insert some values for radius in radius_vals.


select * from radius_vals
RADIUS
5

create table areas(radius number,area number)


Table created.
declare
pi constant number(9,7):=3.1415927;
area number(14,2);
cursor rad_cursor is
select * from radius_vals;
rad_val rad_cursor%rowtype;
begin
open rad_cursor;
fetch rad_cursor into rad_val;
area:=pi*power(rad_val.radius,2);
Insert into areas values(rad_val.radius,area);
close rad_cursor;
end;
PL/SQL procedure successfully completed.
select * from areas

RADIUS

AREA

78.54

//PL/SQL script calculating radius of circle by taking the values from


radius_vals and the computed area for a particular radius value will
inserted into areas table by using cursor with loop
create table radius_vals(radius number)
Table created.
//insert some values for radius in radius_vals.
54

DATA BASE MANAGEMENT SYSTEMS LAB

select * from radius_vals


radius
RADIUS
5
3
2
7
8

create table areas(radius number,area number)


Table created.
declare
pi constant number(9,7):=3.1415927;
area number(14,2);
cursor rad_cursor is
select * from radius_vals;
rad_val rad_cursor%rowtype;
begin
open rad_cursor;
loop
fetch rad_cursor into rad_val;
exit when rad_cursor%NOTFOUND;
area:=pi*power(rad_val.radius,2);
insert into areas values(rad_val.radius,area);
end loop;
close rad_cursor;
end;
PL/SQL procedure successfully completed.
select * from areas
RADIUS

AREA

79

28

5513

254

201

DATA BASE MANAGEMENT SYSTEMS LAB

5 rows selected.
PL/SQL script calculating radius of circle by taking the values from radius_vals and the
computed area for a particular radius value will inserted into areas table by using cursors
with
IF Control structure (>30)
//insert some values for radius in radius_vals.
select * from radius_vals
RADIUS
2
3
4
5
6
7

create table areas(radius number,area number)


Table created.
declare
pi constant number(9,7):=3.1415927;
area number(14,2);
cursor rad_cursor is
select * from radius_vals;
rad_val rad_cursor%rowtype;
begin
open rad_cursor;
loop
fetch rad_cursor into rad_val;
56

DATA BASE MANAGEMENT SYSTEMS LAB

exit when rad_cursor%NOTFOUND;


area:=pi*power(rad_val.radius,2);
if area>30 then
insert into areas values(rad_val.radius,area);
end if;
end loop;
close rad_cursor;
end;
PL/SQL procedure successfully completed.
select * from areas

RADIUS

AREA

50.27

78.54

113.1

153.94

4 rows selected.
PL/SQL script calculating radius of circle by taking the values from radius_vals and the
computed area for a particular radius value will inserted into areas table by using cursors with
FOR
declare
pi constant number(9,7):=3.1415927;
area number(14,2);
cursor rad_cursor is
select * from radius_vals;
rad_val rad_cursor%rowtype;
begin
for rad_val in rad_cursor
loop
area:= pi*power(rad_val.radius,2);
insert into areas values(rad_val.radius,area);
end loop;
end;
PL/SQL procedure successfully completed.
57

DATA BASE MANAGEMENT SYSTEMS LAB

Select * from areas;

RADIUS

AREA

12.57

28.57

50.27

78.54

113.1

153.94

6 rows selected.
PL/SQL script calculating radius of circle by taking the values from radius_vals and the
computed area for a particular radius value will inserted into areas table with WHILE
Declare
pi constant number(9,7):=3.1415927;
area number(14,2);
begin
radius:=2;
loop
area:= pi*power(rad_val.radius,2);
insert into areas values(rad_val.radius,area);
radius:=radius+1;
end loop;
end;
PL/SQL procedure successfully completed.
Select * from areas;

RADIUS

AREA

12.57

28.57

50.27

78.54

113.1

153.94

58

DATA BASE MANAGEMENT SYSTEMS LAB

6 rows selected.
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And print the details of the specified deptno i.e;20
Select * from emp
EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

350

20

7499 allen

1600

560

20

7902 ford

3000

1100

10

7788 scott

3000

1100

20

7566 jones

2975

950

30

Commit
Commit complete
set serveroutput on;
declare
cursor c1 is select empno,sal
from emp
where deptno=20;
vemno number(4);
vsal number(7,2);
begin
open c1;
dbms_output.put_line('empnum'||' '||'salary');
dbms_output.put_line('-------'||'------'||'------');
loop
fetch c1 into vemno,vsal;
exit when c1%NOTFOUND;
dbms_output.put_line(RPAD(vemno,10,'

')||' '||vsal);

end loop;
close c1;
end;
empnum salary
------------------7369
800
7499 1600
59

DATA BASE MANAGEMENT SYSTEMS LAB

7788 3000
PL/SQL procedure successfully completed.
Cursor if-loop
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And print the details of the specified deptno i.e;20 and vsal<2000 and then updates the emp
table
set serveroutput on;
declare
cursor c1 is select empno,sal
from emp
where deptno=20;
vemno number(4);
vsal number(7,2);
begin
open c1;
dbms_output.put_line('empnum'||' '||'salary');
dbms_output.put_line('-------'||'------'||'------');
loop
fetch c1 into vemno,vsal;
exit when c1%NOTFOUND;
if vsal<2000 then
update emp
set comm=sal*3
where empno=vemno;
end if;
dbms_output.put_line(RPAD(vemno,10,'

')||' '||vsal);

end loop;
close c1;
end;
empnum salary
------------------7369 800
7499 1600
7788
3000
PL/SQL procedure successfully completed.
select * from emp
60

DATA BASE MANAGEMENT SYSTEMS LAB

EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

2400

20

7499 allen

1600

4800

20

7902 ford

3000

1100

10

7788 scott

3000

1100

20

7566 jones

2975

950

30

Rollback;
Rollback complete
Select * from emp
EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

350

20

7499 allen

1600

560

20

7902 ford

3000

1100

10

7788 scott

3000

1100

20

7566 jones

2975

950

30

Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And print the details of the vsal<2000 and then display the comm. In emp table by using if
condition

set serveroutput on;


declare
cursor c1 is
select * from emp;
i emp%rowtype;
begin
open c1;
dbms_output.put_line('employ details are');
loop
fetch c1 into i;
exit when c1%notfound;
if i.comm is null then
i.comm:=300;
61

DATA BASE MANAGEMENT SYSTEMS LAB

elsif i.comm=0 then


i.comm:=250;
else
i.comm:=i.comm+i.comm*0.25;
end if;
update emp set comm=i.comm
where empno=i.empno;
dbms_output.put_line(i.empno||'--------- '||i.ename||'
'

'||i.deptno||'

'||i.sal||

'||i.comm);

end loop;
close c1;
end;
employ details are
7369--------- smith 800 20 438
7499--------- allen 1600 20 700
7902--------- ford 3000 10 1375
7788--------- scott 3000 20 1375
7566--------- jones 2975 30 1188
PL/SQL procedure successfully completed.
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And print the details and then calculate the gross and display for those records whose
vsal>2000
declare
cursor c2 is
select empno,ename,sal basic,sal*0.25 da,sal*0.35 hra,sal *0.12 pf from emp
where sal>2000;
i c2%rowtype;
gross number(20,2);
begin
open c2;
loop
fetch c2 into i;
if c2%found then
gross:=i.basic+i.da+i.hra-i.pf;
dbms_output.put_line(i.empno||'

'||i.ename);

else
exit;
end if;
dbms_output.put_line('no. of employee valid for pf are'||'
62

'||c2%rowcount);

DATA BASE MANAGEMENT SYSTEMS LAB

dbms_output.put_line('the gross is '||gross);


end loop;
close c2;
end;
7902 ford
no. of employee valid for pf are 1
the gross is 4440
7788 scott
no. of employee valid for pf are 2
the gross is 4440
7566 jones
no. of employee valid for pf are 3
the gross is 4403
PL/SQL procedure successfully completed.
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And update the details in emp table whose sal<3000.
set serveroutput on;
declare
cursor c1 is select empno,sal from emp;
vempno number(4);
vsal number(7,2);
begin
open c1;
loop
fetch c1 into vempno,vsal;
exit when c1%notfound;
if vsal<3000 then
update emp
set comm=sal*1.3
where empno=vempno;
end if;
end loop;
close c1;
end;
select * from emp
EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

1040

20

7499 allen

1600

2080

20

63

DATA BASE MANAGEMENT SYSTEMS LAB

7902 ford

3000

1375

10

7788 scott

3000

1375

20

7566 jones

2975

3868

30

Cursor for loops


Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And print the details and then calculate the gross and display for those records whose
vsal>2000 using for loop

declare
cursor c2 is
select empno,ename,sal basic,sal*0.25 da,sal*0.35 hra,sal *0.12 pf from emp
where sal>2000;
i c2%rowtype;
gross number(20,2);
begin
for i in c2
loop
gross:=i.basic+i.da+i.hra-i.pf;
dbms_output.put_line(i.empno||'--------- '||i.ename||'

'||i.basic||

gross);
end loop;
end;
7902--------- ford 3000 4440
7788--------- scott 3000 4440
7566--------- jones 2975 4403
PL/SQL procedure successfully completed.
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And update the details in emp table whose sal<3000 by using for loop
declare
cursor c1 is select empno,sal from emp;
begin
for emp_rec in c1
loop
if emp_rec.sal<3000 then
update emp
64

DATA BASE MANAGEMENT SYSTEMS LAB

set comm=sal*1.3
where empno=emp_rec.empno;
end if;
end loop;
end;

EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

1040

20

7499 allen

1600

2080

20

7902 ford

3000

1375

10

7788 scott

3000

1375

20

7566 jones

2975

3868

30

Write an PL/SQL script that displays the low pay,high pay,total pay,no.of employees,avg pay
by using cursors on emp table.
declare
cursor c3 is
select min(sal) low_pay,max(sal) high_pay,sum(sal) tot_pay,count(*)no_of_emp,avg(sal)
avg_pay
from emp;
begin
for i in c3
loop
dbms_output.put_line(i.low_pay||i.high_pay||i.tot_pay||i.no_of_emp||i.avg_pay);
end loop;
end;
800 3000 11375 5 2275
PL/SQL procedure successfully completed.
Write a PL/SQL procedure that takes i/p from an emp table specified below with cursors
And update the details in emp table whose sal<3000 by using for loop as well as if condition.
begin
for emp_rec in (select empno,sal from emp)
loop
if emp_rec.sal<3000 then
65

DATA BASE MANAGEMENT SYSTEMS LAB

update emp
set comm=sal*1.3
where empno=emp_rec.empno;
end if;
end loop;
end;

EMPNO

ENAME

SAL

COMM

DEPTNO

7369 smith

800

1040

20

7499 allen

1600

2080

20

7902 ford

3000

1375

10

7788 scott

3000

1375

20

7566 jones

2975

3868

30

Write an PL/SQL script that takes the i/p from the user i.e empno and display the
corresponding salary using cursors
set serveroutput on;
declare
cursor c1(pempno number) is
select sal from emp
where empno=pempno;
i c1%rowtype;
begin
open c1(&empid);
loop
fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line('sal'||i.sal);
end loop;
end;
Enter value for empid :7788
old 7: open c1(&empid);
new 7: open c1(7788);
sal 3000
PL/SQL procedure successfully completed

66

DATA BASE MANAGEMENT SYSTEMS LAB

Alter the table by adding the column i.e JOB


alter table emp
add column job varchar2(30)
table altered.
insert into emp(job) values(manager)
1 row created
insert into emp(job) values(clerk)
1 row created
insert into emp(job) values(salesman)
1 row created
insert into emp(job) values(account)
1 row created
insert into emp(job) values(attender)
1 row created

select * from emp


EMPNO

ENAME

SAL

COMM

DEPTNO

JOB

7369 smith

800

1040

20 Manager

7499 allen

1600

2080

20 Clerk

7902 ford

3000

1375

10 Salesmen

7788 scott

3000

1375

20 Account

7566 jones

2975

3868

30 Attender

Write an PL/SQL script that takes the i/p from the user i.e deptno and display the
corresponding empno,ename,job, updated salary using cursors
set serveroutput on;
declare
cursor c1(dno number) is
67

DATA BASE MANAGEMENT SYSTEMS LAB

select * from emp


where deptno=dno;
i c1%rowtype;
bonus number(14,2);
begin
open c1(&deptno);
loop
fetch c1 into i;
exit when c1%notfound;
if i.job='clerk' then
bonus:=i.sal+nvl(i.comm,0)*3.5;
else
bonus:=i.sal+nvl(i.comm,0)*3;
end if;
dbms_output.put_line(i.empno||' '||i.ename||' '||i.job||' '||bonus);
end loop;
end;
old 8: open c1(&deptno);
new 8: open c1(20);
7369 smith Manager 3920
7499 allen Clerk 7840
7788 scott Account 7125
PL/SQL procedure successfully completed
old 8: open c1(&deptno);
new 8: open c1(10);
7902 ford Salesmen 7125
PL/SQL procedure successfully completed.
Using WHERE CURRENT of CLAUSE:
Write an PL/SQL script that takes the i/p from the user i.e deptno and update the table
by updating the salary using FOR UPDATE CURSOR and WHERE CURRENT Clauses
declare
cursor c1 is
select empno,sal,deptno from emp
for update;
v c1%rowtype;
begin
open c1;
loop
68

DATA BASE MANAGEMENT SYSTEMS LAB

fetch c1 into v;
exit when c1%notfound;
if v.deptno=10 then
update emp
set comm=sal*1.3
where current of c1;
end if;
end loop;
end;
PL/SQL procedure successfully completed.
Select * from emp
EMPNO

ENAME

SAL

COMM

DEPTNO

JOB

7369 smith

800

1040

20 Manager

7499 allen

1600

2080

20 Clerk

7902 ford

3000

3900

10 Salesmen

7788 scott

3000

1375

20 Account

7566 jones

2975

3868

30 Attender

Write an PL/SQL script that takes specified i/p deptno and deletes the corresponding row in the
emp table by using WHERE CURRENT Clause.
set serveroutput on;
declare
cursor emp_cur is
select empno,ename,deptno from emp
for update;
emp_cur_rec emp_cur%rowtype;
begin
open emp_cur;
dbms_output.put_line('Employee number'||'employee name'||'dept number');
loop
fetch emp_cur into emp_cur_rec;
exit when emp_cur%notfound;
dbms_output.put_line(rpad( emp_cur_rec.empno,16)||
rpad( emp_cur_rec.ename,14)||
69

DATA BASE MANAGEMENT SYSTEMS LAB

rpad( emp_cur_rec.deptno,10));
if
emp_cur_rec.deptno=10 then
delete from emp where current of emp_cur;
end if;
end loop;
close emp_cur;
open emp_cur;
dbms_output.put_line('After deleting the records having deptno=10');
dbms_output.put_line('employee number'||'employee name'||'deptnumber');
loop
fetch emp_cur into emp_cur_rec;
exit when emp_cur%notfound;
dbms_output.put_line(rpad( emp_cur_rec.empno,16)||
rpad( emp_cur_rec.ename,14)||
rpad( emp_cur_rec.deptno,10));
end loop;
close emp_cur;
end;
Employee number employee name dept number
7369
smith
20
7499
allen
20
7788
scott
20
7566
jones
30
After deleting the records having deptno=10
employee number employee name deptnumber
7369
smith
20
7499
allen
20
7788
scott
20
7566
jones
30
PL/SQL procedure successfully completed
select * from emp
EMPNO

ENAME

SAL

COMM

DEPTNO

JOB

7369

smith

800

1040

20

Manager

7499

allen

1600

2080

20

Clerk

7788

scott

3000

1375

20

Account

7566

jones

2975

3868

30

Attender

70

DATA BASE MANAGEMENT SYSTEMS LAB

TASK 12
AIM: Develop Programs using BEFORE and AFTER Triggers, Row and Statement
Triggers
and INSTEAD OF Triggers
create table student(name char(10),id integer);
Table created.
insert into student values('&name',&id);
select * from student;
NAME

ID

sasi

latha

raj

create or replace trigger upp_conv


before
71

DATA BASE MANAGEMENT SYSTEMS LAB

insert on student
for each row
begin
:new.name:=upper(:new.name);
end;
Trigger created.
insert into student values('&name',&id);
select * from student;
NAME

ID

sasi

latha

raj

REKHA

create table students(name char(10),id integer);


Table created.
insert into students values('&name',&id);
old 1: insert into students values('&name',&id)
new 1: insert into students values('hasini',9)
1 row created.
old 1: insert into stu11 values('&sname',&sid)
new 1: insert into stu11 values('pavan',9)
select * from students
NAME

ID

ram

hasini

create or replace trigger del1


AFTER delete on student
for each row
begin
insert into students values(:old.sno,:old.sname);
end;
72

DATA BASE MANAGEMENT SYSTEMS LAB

Trigger created
delete from student where id=1
1 row deleted.
select * from students

NAME

ID

sasi

AIM: To remove trigger


Syntax:
DROP TRIGGER TRIGGER NAME;
drop trigger del1;
Trigger dropped.

73

You might also like