DBMS Lab Exercises
DBMS Lab Exercises
ROLL NO:
Date:
Week-1
Experiments:
Creation, altering and droping of tables and inserting rows into a table (use constraints while
creating tables) examples using SELECT command.
Program:
DDL Commands:
1) CREATE TABLE:
CREATE TABLE students1
(sid integer,
sname varchar2(50),
age integer,
address varchar(60)
);
Output:
Table created.
2) ALTER TABLE COMMAND:
Adding Columns:
Modifying Column:
Rename column:
Dropping Columns:
Output:
Page
Table altered.
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
ROLL NO:
Date:
3) Rename:
RENAME students1 to students3;
Output:
Table renamed.
4) Truncate:
TRUNCATE TABLE student3;
Output:
Table truncated.
5) DROP TABLE:
DROP TABLE student3;
Output:
Table dropped.
DML COMMANDS:
INSERT COMMAND:
UPDATE COMMAND:
UPDATE students3 SET address='vemuluru' where sroll=03;
Output:
1 row updated.
DELETE COMMAND:
DELETE FROM students3 WHERE sroll=08;
Output:
1 row deleted.
SELECT COMMAND:
SELECT * FROM students3;
Output:
SROLL SNAME AGE ADDRESS
3 RamSai 20 Kovvur
7 Rao 20 Peddanapalli
2
Page
Not Null:
CREATE TABLE student2(
Roll_no integer not null,
name varchar2(50),
marks integer
);
Output:
Table created.
1 row inserted.
Unique:
CREATE TABLE student3(
roll integer,
name varchar2(50),
marks integer,
unique(roll));
Output:
Table created.
Primary Key:
CREATE TABLE student4(
Roll_no integer,
name varchar2(50),
primary key(roll));
Output:
Table created.
Foreign key:
Output:
ERROR at line 1:
ORA-02291: integrity constraint (CSE24LE507.SYS_C0041883) violated - parent key not
found
ROLL_NO FEE
7 50000
Check:
Output:
ERROR at line 1:
ORA-02290: check constraint (CSE24LE507.SYS_C0041946) violated
Output:
6
Page
Week-2
Experiments:
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.
Program:
CREATE TABLE sailors (
sid integer,
sname varchar2(30),
rating integer,
age number(3,1),
constraint pk_sailors primary key(sid) );
Output:
Table created.
INSERT INTO sailors VALUES (22, 'Dustin', 7, 45);
INSERT INTO sailors VALUES (29, 'Brutus', 1, 33);
INSERT INTO sailors VALUES (31, 'Lubber', 8, 55.5);
INSERT INTO sailors VALUES (32, 'Andy', 8, 25.5);
INSERT INTO sailors VALUES (58, 'Rusty', 10, 35);
INSERT INTO sailors VALUES (64, 'Horatio', 7, 35);
INSERT INTO sailors VALUES (71, 'Zorba', 10, 16);
INSERT INTO sailors VALUES (74, 'Ravi', 9, 40);
INSERT INTO sailors VALUES (85, 'Art', 3, 25.5);
INSERT INTO sailors VALUES (95, 'Bob', 3, 63.5);
Output:
10 rows created.
CREATE TABLE
boats (
bid integer,
bname varchar2(20),
bcolor varchar2(20),
constraint pk_boats primary key(bid) );
7
Page
Output:
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Table created.
4 rows created.
CREATE TABLE
reserves (
sid integer,
bid integer,
rdate date,
foreign key(sid) references sailors(sid),
foreign key(bid) references boats(bid) );
Output:
Table created.
YYYY'));
Page
10 rows created.
SELECT * FROM
sailors;
Output:
10 rows selected.
SELECT * FROM
boats;
Output:
4 rows selected.
SELECT * FROM reserves;
9
Page
10 rows selected.
Find the names and ages of all
sailors SELECT sname, age FROM
sailors; Output:
Output:
10
Page
Output:
Find the names of the sailors who have reserved at least one boat.
SELECT s.sname
FROM sailors s,reserves r
WHERE s.sid=r.sid;
Output:
11
Page
UNION:
This set operator returns the combined result in the sorted order (ascending by default),
and it excludes the duplicate results. Only one result is displayed for the duplicate results.
For example- f(x) = {a,b,x} and g(x) = {a,a,b,c,c,d} then the UNION Set for them will be
{a,b,d,x}
Find the names of the sailors who have reserved red or green boats.
SELECT s.sname
FROM sailors s
JOIN reserves r ON s.sid = r.sid
JOIN boats b ON b.bid = r.bid
WHERE b.bcolor = 'red'
UNION
SELECT s1.sname
FROM sailors s1
JOIN reserves r1 ON s1.sid = r1.sid
JOIN boats b1 ON b1.bid = r1.bid
WHERE b1.bcolor = 'green';
Output:
UNION ALL:
This set operator is similar to UNION set operator but it includes the duplicate results in
the final result. The UNION ALL set operator gives better performance as compared to
the UNION set operator. Because resources are not used in filtering duplicates and sorting
the result set. For example- f(x) = {a,b,x} and g(x) = {a,a,b,c,c,d} then the UNION ALL
Set for them will be {a,b,x,a,a,b,c,c,d}
Find the names of the sailors who have reserved red or green boats.
8 rows selected.
INTERSECT:
This set operator in Oracle returns the common values in sorted order (ascending by
default). It produces an unduplicated result. For example- f(x) = {a,b,x} and g(x) =
{a,a,b,c,c,d} then the INTERSECT Set for them will be {a,b}
Find the names of the sailors who have reserved both red and green boats.
SELECT s.sname FROM sailors s,reserves r, boats b
WHERE s.sid=r.sid AND b.bid=r.bid AND b.bcolor ='red';
INTERSECT
SELECT s1.sname FROM sailors s1,reserves r1,boats b1
WHERE s1.sid=r1.sid AND b1.bid=r1.bid AND b1.bcolor ='green';
Output: 13
Page
Find the names of the sailors who have reserved a red boat but not a green boat.
SELECT s.sname
FROM sailors s, reserves r, boats b
WHERE s.sid = r.sid AND b.bid = r.bid AND b.bcolor = 'red'
MINUS
SELECT s1.sname
FROM sailors s1, reserves r1, boats b1
WHERE s1.sid = r1.sid AND b1.bid = r1.bid AND b1.bcolor = 'green';
Output:
SNAME
Horatio
Types of Subqueries
Single Row Sub Query: Sub query which returns single row output. They make use of
single-row comparison operators when used in WHERE conditions.
Multiple row subquery: Sub query returning multiple row output. They make use of
multiple-row comparison operators like IN, ANY, and ALL. There can be sub-queries
returning multiple columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query. This type of subquery also includes subqueries that use the EXISTS operator to test
the existence of data rows satisfying specified criteria.
subquery
subquery
subquery
subquery
Output:
SELECT s.sname
FROM sailors s
WHERE s.sid NOT IN(SELECT r.sid FROM reserves r WHERE r.bid=103);
Output:
7 rows selected.
Exists and Not exists:
SELECT s.sname
FROM sailors s
WHERE EXISTS
(SELECT * FROM reserves r WHERE s.sid=r.sid and r.bid=103);
15
Page
SELECT s.sname
FROM sailors s
WHERE s.rating>=ALL(SELECT s2.rating FROM sailors s2);
Output:
16
Page
Table created.
CREATE
TABLE t2 (
t1_id integer,
t2_id integer,
t2desc varchar2(20),
primary key(t2_id),
foreign key(t1_id) REFERENCES t1(t1_id) on delete cascade );
Output:
Table created.
CREATE TABLE
t3(
t2_id integer,
t3_id integer,
t3desc varchar2(20),
primary key(t3_id),
foreign key(t2_id) REFERENCES t2(t2_id) on delete cascade );
Output:
Table created.
INSERT INTO t1 VALUES(1,'T1 ONE');
Output:
1 row created.
17
Output:
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
1 row created.
INSERT INTO t3 VALUES(1,1,'T3 ONE');
Output:
1 row created.
DELETE FROM t1
cascade; Output:
1 rows deleted.
SELECT * FROM t1;
Output:
no rows selected
SELECT * FROM t2;
Output:
no rows selected
Output:
no rows selected
Table created
Page
1 row created.
Output:
1 rows deleted.
SELECT * FROM t12;
Output:
Select the roll number and name of the student who secured fourth rank in the class.
CREATE TABLE students (
roll_number NUMBER PRIMARY KEY,
name VARCHAR2(100),
math NUMBER,
science NUMBER,
english NUMBER,
hindi NUMBER,
social NUMBER,
telugu NUMBER
);
Insert Queries
INSERT INTO students VALUES (101, 'Amit Kumar', 95, 90, 88, 85, 89, 92);
INSERT INTO students VALUES (102, 'Priya Sharma', 88, 91, 85, 87, 90, 86);
INSERT INTO students VALUES (103, 'Rahul Verma', 92, 89, 91, 90, 85, 87);
INSERT INTO students VALUES (104, 'Sneha Gupta', 85, 87, 89, 91, 93, 88);
INSERT INTO students VALUES (105, 'Vikram Rathore', 90, 92, 88, 85, 87, 91);
INSERT INTO students VALUES (106, 'Neha Jain', 87, 85, 90, 88, 89, 92);
INSERT INTO students VALUES (107, 'Arjun Malhotra', 91, 88, 85, 90, 86, 89);
INSERT INTO students VALUES (108, 'Pooja Yadav', 86, 89, 87, 92, 90, 85);
INSERT INTO students VALUES (109, 'Ravi Mehta', 89, 90, 92, 85, 88, 87);
INSERT INTO students VALUES (110, 'Kavita Rao', 83, 86, 85, 88, 87, 90);
Input
19
Page
Output
20
Page
Week-3
Experiments
Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
Program:
AGGREGATE FUNCTIONS:
SQL supports five aggregate operators which can be applied on any column, say A, of a
relation.
1. COUNT (DISTINCT A): The number of (unique) values in A column.
2. SUM (DISTINCT A): The sum of all (unique) values in A column.
3. AVG (DISTINCT A): The Average of all (unique) values in A column.
4. MAX (A): The maximum values in A column.
5. MIN (A): The minimum values in A column.
Group by clause:
Using group by, we can create groups of related information. Columns used in select
clause must be used with group by clause; otherwise it was not a group by expression.
Having clause:
This will work as where clause which can be used only with group by clause because of
absence of where clause in group by.
Views:
A view is a tailored presentation of the data contained in one or more tables (or other
views), and takes the output of a query and treats it as a table. You can think of a view as
a “stored query” or a “virtual table.” You can use views in most places where a table can
be used.
COUNT( ):
COUNT(*)
10
AVG() :
21
sailors?
Output:
AVG(S.AGE)
37.4
SUM() :
Find the sum of ratings of all sailors?
SELECT SUM(s.rating) FROM sailors s;
Output:
SUM(S.RATING)
66
MIN() :
Find the Minimum age of the
sailors? SELECT MIN(age) FROM
sailors;
Output:
MIN(AGE)
16
MAX():
Find the Maximum age of the
sailors? SELECT MAX(age) FROM
sailors;
Output:
MAX(AGE)
63.5
Group by:
SELECT companyn,SUM(p.amount)
FROM company;
Output:
Find the sum of amount of each company
SELECT companyn,SUM(p.amount)
FROM company p;
*
ERROR at line 1:
ORA-00937: not a single-group group function
COMPANYNAME SUM(AMOUNT
Wipro 9000
dell 16000
ibm 9000
wipro 2
23
dell 2
Page
ibm 1
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Find the Minimum amount of the each company
SELECT companyname,MIN(amount) from company GROUP BY companyname;
Output:
COMPANYNAME MIN(AMOUNT)
wipro 4000
dell 6000
ibm 9000
wipro 5000
dell 10000
ibm 9000
Having clause:
Find the count of all rows group by each company having count greater than 1.
SELECT companyname,COUNT(*)
FROM company
GROUP BY companyname
HAVING COUNT(*)>1;
Output:
COMPANYNAME COUNT(*)
wipro 2
dell 2
Find the sum of amount group by each company having amount greater than 10000.
SELECT companyname,SUM(amount) FROM company GROUP BY companyname
HAVING SUM(amount)>10000;
24
Page
dell 16000
Order by:
Find the count of all rows group by company having count greater than 1 order by
ascending order.
SELECT companyname,count(*) FROM company GROUP BY companyname
HAVING COUNT(*)>1 2 ORDER BY companyname ASC;
Output:
COMPANYNAME COUNT(*)
dell 2
wipro 2
View:
Creation of view:
CREATE VIEW company_view AS (SELECT companyname FROM company);
Output:
View created.
SELECT * FROM company_view;
Output:
COMPANYNAME
wipro
dell
ibm
dell
wipro
Insertion on view :
INSERT INTO company_view VALUES(‘delotte’);
Output:
1 row created.
SELECT * FROM C_view;
25
Page
SELECT*FROM Company;
Output:
COMPANYNAME AMOUNT
wipro 5000
dell 10000
ibm 9000
dell 6000
wipro 4000
delotte null
Force:
ERROR at line 1:
26
Check Option:
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
View created.
INSERT INTO company_c VALUES(‘HP’,70000);
Output:
INSERT INTO company_c VALUES(‘HP’;,70000)
*
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation
Drop View:
DROP VIEW company_c;
Output:
View dropped.
27
Page
Week-4
Experiments
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, leas
Program:
String functions:
Concat:
Lower:
Upper:
Output:
ADITYA
Length:
6
ASCII:
Page
Chr:
Reverse:
Lpad:
*********aditya
Rpad:
Ltrim:
Rtrim:
Replace:
Page
Initcap:
Instr:
Substr:
SELECT SUBSTR('abcdef',-3,2)FROM dual;
Output:
de
Numeric functions:
ABS():
20.0855369
30
Page
Output:
3
LOG():
3
TRUNCATE():
Page
EXTRACT():
SELECT EXTRACT(year from sysdate)FROM dual;
Output:
2025
Add_months(sysdate,integer):
SELECT ADD_MONTHS(sysdate,2)FROM dual;
Output:
08-MAR-25
Last_day(sysdate):
SELECT LAST_DAY(sysdate)FROM dual;
Output:
31-JAN-25
Next_day(sysdate,day):
SELECT NEXT_DAY('10-dec-2019','Tuesday')FROM dual;
Output:
17-DEC-19
Months_between():
SELECT MONTHS_BETWEEN(to_date('09-dec-2020','dd-mm-yyyy'),to_DATE('09-dec-
2019','dd-mm-yyyy'))f
rom dual;
Output:
12
To_char(sysdate,format):
Output:
Page
11:01:43
Week-5 A
Experiments
i. Create a 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)
Program:
Sample PL/ program:
BEGIN
dbms_output.put_line('hello');
END;
OUTPUT:
hello
PL/ procedure successfully completed.
Sum of two numbers:
DECLARE
a integer;
b integer;
c integer;
BEGIN
a:=2;
b:=3;
c:=a+b;
dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
END;
/
OUTPUT:
sum of2and3is5
PL/ procedure successfully completed.
student_name varchar2(50),
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
Date: ROLL NO:
total_marks number(5),
percentage number(5,2) );
OUTPUT:
Table created.
Program for Student marks can be selected from the table and printed for who secured
first class and an exception can be raised if no records were found.
DECLARE
no_records_found EXCEPTION;
BEGIN
IF scount = 0 THEN
RAISE no_records_found;
END IF;
LOOP
dbms_output.put_line(records.student_id);
34
END LOOP;
Page
EXCEPTION
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
Date: ROLL NO:
END;
OUTPUT:
first class students are ---- ::
101
103
104
PL/ procedure successfully completed.
35
Page
Week-5 B
Experiments
ii. Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.
Program:5B
name varchar2(20) );
OUTPUT:
Table created.
501 ravi
Page
502 suma
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
Date: ROLL NO:
503 padma
ROLLBACK to b;
Output:
Rollback complete.
SELECT * FROM student;
Output:
ROLLNO NAME
501 ravi
502 suma
rollback to a;
Output:
ROLLNO NAME
501 ravi
Program using savepoint , commit and rollback:
BEGIN
INSERT INTO student VALUES(504,'yashoda');
UPDATE student SET name='rani' WHERE rollno=504;
SAVEPOINT s;
DELETE FROM student WHERE rollno=501;
ROLLBACK to s;
COMMIT;
END;
/
Output:
PL/ procedure successfully completed.
501 ravi
504 rani
37
Page
Week-6
Experiments:
Develop a program that includes the features NESTED IF, CASE and CASE expression. The
program can be extended using the NULLIF and COALESCE functions.
Program:
Nested if case to find a number is even or odd
DECLARE
n int := &n;
BEGIN
if mod(n,2)=0 then
dbms_output.put_line('even number'|| n);
else
dbms_output.put_line('odd number'|| n);
end if;
END;
/
OUTPUT:
Enter value for
n: 2 old 2: n int
:= &n; new 2:
n int := 2;
even number 2
Nested if case to find bigger number
DECLARE
a NUMBER := &a;
b NUMBER := &b;
BEGIN
IF a > b THEN
dbms_output.put_line('Bigger number: ' || a);
ELSIF a < b THEN
dbms_output.put_line('Smaller number: ' || b);
ELSE
dbms_output.put_line('Both numbers are equal.');
END IF;
END;
/
OUTPUT:
Enter value for
a: 2 old 2: a
int:=&a; new
2: a int:=2;
38
int:=&b; new
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
3: b int:=3;
bigger
number3
DECLARE
marks NUMBER := &marks;
BEGIN
IF marks > 75 THEN
dbms_output.put_line('DISTINCTION');
ELSIF marks >= 60 AND marks < 75 THEN
dbms_output.put_line('FIRST CLASS');
ELSIF marks >= 50 AND marks < 60 THEN
dbms_output.put_line('SECOND CLASS');
ELSIF marks >= 30 AND marks < 50 THEN
dbms_output.put_line('THIRD CLASS');
ELSE
dbms_output.put_line('FAILED');
END IF;
END;
/
OUTPUT:
Enter value for marks: 50
old 2: marks
integer:=&marks; new 2:
marks integer:=50;
SECOND CLASS
39
Page
DECLARE
a INTEGER := &a;
b INTEGER := &b;
c INTEGER := &c;
BEGIN
IF a >= b AND a >= c THEN
dbms_output.put_line('A is the greatest');
ELSIF b >= a AND b >= c THEN
dbms_output.put_line('B is the greatest');
ELSIF c >= a AND c >= b THEN
dbms_output.put_line('C is the greatest');
ELSE
dbms_output.put_line('All values are equal');
END IF;
END;
/
OUTPUT:
dbms_output.put_line('INVALID GRADE');
END CASE;
Page
END;
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
/
OUTPUT:
Enter value for grade: 'A'
old 2: grade char(1) :=
&grade; new 2: grade
char(1) := 'A';
EXCELLENT
CASE expression to display student_percentage
SELECT student_id,percentage,
(CASE
WHEN percentage > 60 THEN 'FIRST CLASS'
WHEN percentage = 20 THEN 'FAIL'
ELSE 'The percentage is good'
END) AS student_percentage
from student_marks
end;
OUTPUT:
NULLIF statements
OUTPUT:
TECH
OUTPUT:
tech honey
NULL
SELECT NULLIF(2,2) FROM dual;
OUTPUT:
NULL
OUTPUT:
smallintcol integer,
bigintcol integer,
intcol integer);
OUTPUT:
Table created.
OUTPUT:
1 row created
OUTPUT:
1 row created.
COALESCE statements
FROM temps;
42
Page
OUTPUT:
1
2
3
OUTPUT:
1
3
43
Page
Week-7
Experiments
Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using
ERROR Handling, BUILT –IN Exceptions, USE defined Exceptions, RAISEAPPLICATION
ERROR.
Program:
SIMPLE LOOP:
Write a PL/ program to print Sequence of n numbers using simple loop
DECLARE
a NUMBER;
n NUMBER;
BEGIN
a := 1;
n := &n;
IF n IS NULL THEN
dbms_output.put_line('Invalid value for n.');
RETURN;
END IF;
LOOP
EXIT WHEN a > n; -- Corrected position of EXIT condition
dbms_output.put_line(a);
a := a + 1;
END LOOP;
END;
/
Output:-
SET SERVEROUTPUT
ON;
DECLARE
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
a int:=1;
n int:=&n;
BEGIN
while(a<=n)loop
dbms_output.put_line(a);
a:=a+1;
end loop;
END;
/
Output:-
Enter value for
n: 6 old 3: n
int:=&n; new 3:
n int:=6;
1
2
3
4
5
6
PL/ procedure successfully completed.
FOR LOOP:
FOR a IN 1..n
LOOP
dbms_output.put_line(a);
END LOOP;
END;
/
Output:-
Enter value for
n: 6 old 3: n
int:=&n; new 3:
n int:=6;
1
2
3
4
45
5
6
Page
EXCEPTIONS:
DECLARE
id NUMBER := 12;
BEGIN
BEGIN
id := 12 / 0;
END;
/
Output:-
*
ERROR at line 1:
ORA-01476: Division by zero is
not allowedORA-06512: at line
4
WITH EXCEPTION:
DECLARE
id NUMBER := 12;
BEGIN
id := 12 / 0; -- Division by zero occurs here
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line('Divide by zero');
END;
/
Output:
Divide by zero
PL/ procedure successfully completed.
DECLARE
num number:=#
BEGIN
dbms_output.put_line('Square root of'||num||' is '||sqrt(num));
END;
/
Output:
46
WITH EXCEPTION:
DECLARE
num number:=#
BEGIN
dbms_output.put_line('Square root of '||num||' is '||sqrt(num));
exception
when value_error then
dbms_output.put_line('Value error');
END;
/
Output:
Enter value for num: -
54 old 2: num
number:=# new 2:
num number:=-54;
Value error
PL/ procedure successfully completed.
DECLARE
roll_no INTEGER := 502;
sname VARCHAR2(20) := 'Alekhya';
marks NUMBER := 99;
BEGIN
INSERT INTO student (roll_no, sname, marks)
VALUES (roll_no, sname, marks);
END;
/
Output:
declare
*
ERROR at line 1:
ORA-00001: unique constraint (CSE23565.SYS_C0046057)
violated ORA-06512: at line 6
47
Page
DECLARE
roll_no INTEGER := 502;
sname VARCHAR2(20) := 'Alekhya';
marks NUMBER := 99;
BEGIN
INSERT INTO student (roll_no, sname, marks)
VALUES (roll_no, sname, marks);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
dbms_output.put_line('Unique Constraint violated');
END;
/
Output:
Unique Consraint violated
PL/ procedure successfully completed.
DECLARE
id INT := &id;
name VARCHAR2(20);
BEGIN
SELECT sname INTO name FROM student WHERE roll_no = id;
dbms_output.put_line(name);
END;
/
Output:
Enter value for id:
504 old 2: id
int:=&id; new 2:
id int:=504;
declare
*
ERROR at line 1:
ORA-01403: no data
found ORA-06512: at
line 5
WITH EXCEPTION:
DECLARE
id INT:= &id;
name VARCHAR2(20);
BEGIN
48
dbms_output.put_line(name);
EXCEPTION
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('No data found');
END;
/
Output:
Enter value for id:
504 old 2: id
int:=&id; new 2:
id int:=504; No
dta found
PL/ procedure successfully completed.
DECLARE
grade char(1):='&grade';
BEGIN
case grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Good');
when 'C' then dbms_output.put_line('Average');
when 'D' then dbms_output.put_line('Poor');
end case;
END;
/
Output:
Enter value for grade: E
old 2: grade
char(1):='&grade'; new 2:
grade char(1):='E'; declare
*
ERROR at line 1:
ORA-06592: CASE not found while executing CASE
statement ORA-06512: at line 4
WITH EXCEPTION:
DECLARE
grade char(1):='&grade';
BEGIN
case grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Good');
when 'C' then dbms_output.put_line('Average');
when 'D' then dbms_output.put_line('Poor');
end case;
EXCEPTION
49
END;
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Output:
Enter value for grade: E
old 2: grade
char(1):='&grade'; new 2:
grade char(1):='E'; Case
not found
PL/ procedure successfully completed.
DECLARE
a integer:=&a;
b exception;
BEGIN
if a<3 then raise b;
end if;
exception
when b then dbms_output.put_line('User defined exception raised');
END;
/
Output:
Enter value for a:
2 old 2: a
integer:=&a; new
2: a integer:=2;
User defined exception raised
PL/ procedure successfully completed.
DECLARE
myex exception;
n number:=&n;
BEGIN
for i in 1..n loop
dbms_output.put_line(i);
if i=n then
raise myex;
end if;
end loop;
EXCEPTION
when myex then
raise_application_error(-20015,'loop finish');
END;
50
/
Page
DECLARE
type scoretable is table of number;
type studentscorestable is table of scoretable;
student_scores studentscorestable;
total_score number;
BEGIN
student_scores:=studentscorestable(
scoretable(85,90,78),
scoretable(92,88,-5),
10 scoretable(75,80,95),
scoretable()
);
for i in 1..student_scores.count loop
dbms_output.put_line('processing scores for student'||i||':');
total_score:=0;
for j in 1..student_scores(i).count loop
begin
if student_scores(i)(j)<0 then
raise_application_error(-20001,'invalid score:'||student_scores(i)(j)||'for student'||i);
end if;
total_score:=total_score+student_scores(i)(j);
EXCEPTION
when others then
dbms_output.put_line('error processing
score for
student'||i||',score'||student_scores(i)(j)||':'||SQ
LERRM);
end;
end loop;
51
if total_score>0 then
dbms_output.put_line('total score for student'||i||':'||total_score);
Page
else
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
dbms_output.put_line('no valid scores for student'||i||':');
end if;
end loop;
dbms_output.put_line('processing complete');
exception
when others then
dbms_output.put_line('an unexpected error occured:'||SQLERRM);
END;
/
Output:
52
Page
Week-8
Experiments:
Programs development using creation of procedures, passing parameters IN and OUT of
PROCEDURES.
Program:
Creation of procedures:
CREATE procedure greet
as
BEGIN
dbms_output.put_line('Hello');
END;
/
Output:
Procedure created.
BEGIN
greet;
END;
/
Output:
Hello
PL/ procedure successfully completed.
exec greet;
Output:
Hello
PL/ procedure successfully completed.
dbms_output.put_line(d);
END;
Page
/
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Output:
9
PL/ procedure successfully completed.
54
Page
Week-9
Experiments:
Program development using creation of stored functions, invoke functions in SQL Statements and
write complex functions.
Program:
Write a stored function to find square of a given number
SET SERVEROUTPUT ON;
CREATE FUNCTION sq(x in number)
return number
as
BEGIN
return(x*x);
END;
/
Output:
Function created.
BEGIN
dbms_output.put_line(sq(7));
END;
/
Output:
49
PL/ procedure successfully completed.
64
created.
Page
DECLARE
Output:
9
PL/ procedure successfully completed.
14
DECLARE
area_rec number;
BEGIN
area_rec:=area_rect(2,7);
dbms_output.put_line(area_rec);
END;
/
Output:
14
56
Week-10
Experiments:
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
PROGRAM:
DECLARE
cursor sail_cur is
select sid,sname from sailors;
ab sail_cur%rowtype;
BEGIN
open sail_cur;
fetch sail_cur into ab;
while sail_cur%FOUND
57
loop
dbms_output.put_line(ab.sid||' '||ab.sname);
Page
OUTPUT:
22 Dustin
29 Brutus
31 Lubber
32 Andy
58 Rusty
64 Horatio
71 Zorba
74 Ravi
85 Art
95 Bob
DECLARE
cursor sail_cur is select sname from sailors;
ab sail_cur%rowtype;
BEGIN
for ab in sail_cur
loop dbms_output.put_line(ab.sname);
end loop;
END;
/
OUTPUT:
OUTPUT:
22 Dustin 7 45
29 Brutus 1 33
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 45
64 Horatio 7 35
71 Zorba 10 26
74 Ravi 9 40
85 Art 3 25.5
95 Bob 3 63.5
DECLARE
TYPE sail_ref_cursor IS REF CURSOR;
sail_cursor sail_ref_cursor;
59
var_sid sailors.sid%TYPE;
var_sname sailors.sname%TYPE;
Page
var_rating sailors.rating%TYPE;
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
BEGIN
OPEN sail_cursor FOR SELECT sid, sname, rating from sailors WHERE rating>7;
loop
fetch sail_cursor INTO var_sid, var_sname, var_rating;
EXIT when sail_cursor%NOTFOUND;
dbms_output.put_line('sid: '|| var_sid||',sname: '|| var_sname|| ',rating: '|| var_rating);
end loop;
close sail_cursor;
commit;
END;
/
OUTPUT:
sid: 31,sname:
Lubber,rating: 8 sid:
32,sname: Andy,rating: 8
sid: 58,sname: Rusty,rating:
10 sid: 71,sname:
Zorba,rating: 10 sid:
74,sname: Ravi,rating: 9
60
Page
Week-11
Experiments:
Develop Programs using BEFORE and AFTER Triggers, Row and Statement Triggers and
INSTEAD OF Triggers
PROGRAM:
Oracle Trigger
In Oracle, you can define procedures that are implicitly executed when an INSERT,
UPDATE or DELETE statement is issued against the associated table. These
procedures are called database triggers.
1. This statement specifies that Oracle will fire this trigger BEFORE the
INSERT/UPDATE or DELETE operation is executed.
Syntax :
CREATE [ OR REPLACE ] TRIGGER trigger_name
BEFORE INSERT or UPDATE or DELETE
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger
code
EXCEPTION
WHEN ...
-- exception handling
END;
2. This statement specifies that Oracle will fire this trigger AFTER the
INSERT/UPDATE or DELETE operation is executed.
Syntax:
CREATE [ OR REPLACE ] TRIGGER trigger_name
AFTER INSERT or UPDATE or DELETE
ON table_name
[ FOR EACH ROW ]
61
DECLARE
Page
-- variable declarations
BEGIN
-- trigger
code
EXCEPTION
WHEN ...
-- exception handling
END;
Ou
tpu
t:-
Trigger created
INSERT into sailors values(11,'John',7.7,30);
---Welcome to new sailors---
1 row created
INSERT into sailors values(12,'dany',6.9,22);
---Welcome to new sailors---
1 row created
Ou
tpu
t:-
trigger created
insert into sailors values(13,'lilly',9.1,30); 1
row created
insert into sailors values(13,'lilly',-9.1,30); Error
at line1:
ORA-06512:at"CSE16P501.TRG2",line4
ORA-04088:error during execution of trigger 'CSE16P501
TRG2'
63
Page
Week-12
Experiments:
Create a table and perform the search operation on table using indexing and nonindexing
Techniques
PROGRAM:
Index in Oracle :
Syntax :
Output:
Output:
65
Page
Week-13
PROGRAM
Source Code:
import java.sql.*;
try{
if(con!=null)
else{
System.out.println("Connection Failed");
}
66
}
Page
catch(SQLException e)
System.out.println(e);
con.close();
Output:
67
Page
Week-14
PROGRAM
Write a java program to connect to a database using JDBC and insert values into it.
Source Code:
import java.sql.*;
try{
if(con!=null)
else
System.out.println("Connection Failed");
}
68
Statement st=con.createStatement();
Page
st.executeUpdate(query);
int count=st.executeUpdate(query);
if(count>0)
catch(SQLException e)
System.out.println(e);
Output:
69
Page
Week-15
PROGRAM
Source Code:
import java.sql.*;
try{
if(con!=null)
else
System.out.println("Connection Failed");
70
Page
Statement st=con.createStatement();
int count=st.executeUpdate(query);
if(count>0)
catch(SQLException e){
System.out.println(e);
Output:
71
Page