0% found this document useful (0 votes)
10 views71 pages

DBMS Lab Exercises

The document outlines a series of experiments related to SQL commands, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands, with examples of creating, altering, and dropping tables, as well as inserting, updating, and deleting records. It also covers the use of constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, along with various SQL queries utilizing operators such as UNION, INTERSECT, and subqueries. The document serves as a practical guide for students to understand and apply SQL commands effectively.

Uploaded by

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

DBMS Lab Exercises

The document outlines a series of experiments related to SQL commands, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands, with examples of creating, altering, and dropping tables, as well as inserting, updating, and deleting records. It also covers the use of constraints like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, and DEFAULT, along with various SQL queries utilizing operators such as UNION, INTERSECT, and subqueries. The document serves as a practical guide for students to understand and apply SQL commands effectively.

Uploaded by

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

Exp No:

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:

ALTER TABLE students1 ADD city varchar2(80);


Output:
Table altered.

Modifying Column:

ALTER TABLE students1 MODIFY sid varchar2(30);


Output:
Table altered.

Rename column:

ALTER TABLE students1 RENAME COLUMN sid to rollno;


Output:
Table altered.

Dropping Columns:

ALTER TABLE students1 DROP COLUMN city;


1

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:

INSERT INTO students3 VALUES(03,'RamSai',20,'Kovvur');


Output:
1 row created.

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
Constraints

Not Null:
CREATE TABLE student2(
Roll_no integer not null,
name varchar2(50),
marks integer
);
Output:
Table created.

INSERT INTO student2 VALUES(null,'rao',80);


Output:
INSERT INTO student2 VALUES(null,'rao',80)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("CSE24LE507"."STUDENT2"."ROLL")

INSERT INTO student2 VALUES(1,'rao',80)

1 row inserted.

SELECT * FROM student2;


Output:

ROLL_NO NAME MARKS


1 rao 80

Unique:
CREATE TABLE student3(
roll integer,
name varchar2(50),
marks integer,
unique(roll));
Output:
Table created.

INSERT INTO student3 VALUES(3,'sai',70);


INSERT INTO student3 VALUES(3,'sai',70)
*
ERROR at line 1:
ORA-00001: unique constraint (CSE24LE507.SYS_C0041784) violated
3

SELECT * FROM STUDENT3;


Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
Output:

Roll_no Name Marks


3 Sai 70

Primary Key:
CREATE TABLE student4(
Roll_no integer,
name varchar2(50),
primary key(roll));
Output:
Table created.

INSERT INTO student4 VALUES(7,'rao');


Output:
INSERT INTO student4 VALUES(7,'rao')
*
ERROR at line 1:
ORA-00001: unique constraint (CSE24LE507.SYS_C0041848) violated

INSERT INTO student4 VALUES(null,'rao');


Output:
INSERT INTO student4 VALUES(null,'rao')
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("CSE24LE507"."STUDENT4"."ROLL")

SELECT * FROM STUDENT4;


Output:
ROLL_NO NAME
7 rao

Foreign key:

CREATE TABLE student5(


Roll_no integer,
fee integer,
foreign key(roll_no) references student4(roll_no));
Output:
Table created.
4

INSERT INTO student5 VALUES(7, 50000);


Page

INSERT INTO student5 VALUES(7,50000);


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
ROLL NO:
Date:

Output:

ERROR at line 1:
ORA-02291: integrity constraint (CSE24LE507.SYS_C0041883) violated - parent key not
found

SELECT * FROM STUDENT5;


Output:

ROLL_NO FEE
7 50000

DELETE FROM student4 WHERE roll=3;


Output:
DELETE FROM student4 WHERE roll=3
*
ERROR at line 1:
ORA-02292: integrity constraint (CSE24LE507.SYS_C0041883) violated – child record found

Check:

CREATE TABLE student6(


Roll_no integer,
name varchar2(50),
marks integer,
check(marks>50));
Output:
Table created.

INSERT INTO student6 VALUES(7,'rao',62);


INSERT INTO student6 VALUES(7,'rao',32);

Output:

ERROR at line 1:
ORA-02290: check constraint (CSE24LE507.SYS_C0041946) violated

SELECT * FROM STUDENT6;


Output:

Roll_No Name Marks


7 rao 62
5
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
Default:

CREATE TABLE student7(


Roll_no integer,
name varchar2(50),
gender char(1) default 'M',
marks integer);

INSERT INTO student7 VALUES(3,'sai',default,66);

SELECT * FROM STUDENT7;

Output:

Roll_no Name Gender Marks


3 sai M 66

6
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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.

INSERT INTO boats VALUES (101, 'Interlake', 'blue');


INSERT INTO boats VALUES (102, 'Interlake', 'red');
INSERT INTO boats VALUES (103, 'Clipper', 'green');
INSERT INTO boats VALUES (104, 'Marine', 'red');
Output:

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.

INSERT INTO reserves VALUES (22, 101, TO_DATE('10-OCT-1998', 'DD-MON-


YYYY'));
INSERT INTO reserves VALUES (22, 102, TO_DATE('10-OCT-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (22, 103, TO_DATE('08-OCT-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (22, 104, TO_DATE('07-OCT-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (31, 102, TO_DATE('10-NOV-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (31, 103, TO_DATE('06-NOV-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (31, 104, TO_DATE('12-NOV-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (64, 101, TO_DATE('05-SEP-1998', 'DD-MON-
YYYY'));
INSERT INTO reserves VALUES (64, 102, TO_DATE('08-SEP-1998', 'DD-MON-
8

YYYY'));
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
INSERT INTO reserves VALUES (74, 103, TO_DATE('08-SEP-1998', 'DD-MON-
YYYY'));
Output:

10 rows created.
SELECT * FROM
sailors;

Output:

10 rows selected.

SELECT * FROM
boats;

Output:

4 rows selected.
SELECT * FROM reserves;
9
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Output:

10 rows selected.
Find the names and ages of all
sailors SELECT sname, age FROM
sailors; Output:

Find all sailors with a rating above 7.


SELECT * FROM sailors
WHERE rating>7;

Output:
10
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Find the names of sailors who have reserved boat number 103.

SELECT s.sname FROM sailors


s,reserves r WHERE s.sid=r.sid AND
r.bid=103;

Output:

Find the names of sailors who have reserved a red 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';
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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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.

SELECT s.sname FROM sailors s,reserves r, boats b


12

where s.sid=r.sid and b.bid=r.bid and b.bcolor ='red';


Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
UNION ALL
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:

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
MINUS:
The MINUS operator in SQL is used to return rows from the first query that are not present in
the second query. It's a set operation that helps in finding differences between two result sets.

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.

Usage of Multiple Row operators

[> ALL] More than the highest value returned by the

subquery

[< ALL] Less than the lowest value returned by the

subquery

[< ANY] Less than the highest value returned by the


14
Page

subquery

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
[> ANY] More than the lowest value returned by the

subquery

[= ANY] Equal to any value returned by the subquery (same as IN)

IN and NOT IN:


SELECT s.sname
FROM sailors s
WHERE s.sid IN(SELECT r.sid FROM reserves r WHERE r.bid=103);

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Output:

SELECT s.sname FROM sailors s WHERE NOT EXISTS


(SELECT * FROM reserves r WHERE s.sid=r.sid AND r.bid=103);
Output:

ALL and ANY:


SELECT s.sname
FROM sailors s
WHERE s.rating>
ANY(SELECT s2.rating FROM sailors s2
WHERE s2.sname="Horatio");
Output:

SELECT s.sname
FROM sailors s
WHERE s.rating>=ALL(SELECT s2.rating FROM sailors s2);
Output:
16
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
On Delete Cascade:
CREATE TABLE t1(
t1_id integer,
t1desc varchar2(20),
primary
key(t1_id) );
Output:

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

INSERT INTO t2 VALUES(1,1,'T2 ONE');


Page

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

SELECT * FROM t3;

Output:

no rows selected

On Delete Set Null:


CREATE
TABLE t12
( t1_id
integer,
t2_id integer,
t2desc varchar2(20),
primary key(t2_id),
foreign key(t1_id) REFERENCES t1(t1_id) on DELETE SET null );
Output:
18

Table created
Page

INSERT INTO t1 VALUES(1,'T1 ONE');


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Output:
1 row created.
INSERT INTO t12 VALUES(1,1,'T2 ONE');
Output:

1 row created.

DELETE FROM t1;

Output:
1 rows deleted.
SELECT * FROM t12;
Output:

T1_id T2_id T2DESC


1 T2 ONE

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

SELECT roll_number, name, total_marks

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
FROM (
SELECT roll_number, name,
(math + science + english + hindi + social + telugu) AS total_marks,
RANK() OVER (ORDER BY (math + science + english + hindi + social + telugu)
DESC) AS rank
FROM students
)
WHERE rank = 4;

Output

20
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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

Find no of sailors in a sailors table?


SELECT COUNT(*) FROM sailors;
Output:

COUNT(*)

10
AVG() :
21

Find the average age of the


Page

sailors?

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
SELECT AVG(s.age) FROM
sailors s;

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

CREATE TABLE company(


Company_name varchar(50),
Amount int);

INSERT INTO company VALUES('Wipro', 4000);


INSERT INTO company VALUES('Dell', 6000);
22

INSERT INTO company VALUES('IBM', 9000);


INSERT INTO company VALUES('Wipro', 5000);
Page

INSERT INTO company VALUES('Dell', NULL);


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
INSERT INTO company VALUES('Group by', 10000);
SELECT * FROM company;
Output:

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

SELECT companyn,SUM(amount) FROM company GROUP BY companyn;


Output:

COMPANYNAME SUM(AMOUNT
Wipro 9000
dell 16000
ibm 9000

Find the count of all the rows grouped by each company


SELECT companyname,COUNT(*) FROM company GROUP BY companyn;
Output:
COMPANYNAME COUNT(*)

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

Find the Maximum amount of the each company


SELECT companyname,MAX(amount) FROM company GROUP BY companyname;
Output:
COMPANYNAME MAX(AMOUNT)

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Output:
COMPANYNAME SUM(AMOUNT)

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Output:
COMPANYNAME
Wipro
Dell
IBM
Dell
Wipro
Delotee

SELECT*FROM Company;

Output:
COMPANYNAME AMOUNT
wipro 5000
dell 10000
ibm 9000
dell 6000
wipro 4000
delotte null

Force:

CREATE force view ab_view as SELECT * FROM dummy;


Output:
Warning: View created with compilation errors.
Read Only:
CREATE VIEW company_r AS SELECT companyn, amount FROM company with read
only;
Output:
View created.
INSERT INTO company_r VALUES(‘HP’,50000);
Output:
INSERT INTO company_r VALUES(‘HP’,50000)
*

ERROR at line 1:
26

ORA-01733: virtual column not allowed here


Page

Check Option:
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:

CREATE VIEW company_c as SELECT * FROM company WHERE


amount&lt;=60000 WITH CHECK OPTION;
Output:

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:

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:

SELECT CONCAT('aditya','engg') FROM dual;


Output:
adityaengg

SELECT CONCAT(concat('aditya','engg'),'college') FROM dual;


Output:
adityaenggcollege

SELECT 'Aditya'||'engg' FROM dual;


Output:
Adityaengg

Lower:

SELECT LOWER('ADITYA')FROM dual;


Output:
aditya

Upper:

SELECT UPPER('aditya') FROM dual;

Output:
ADITYA

Length:

SELECT LENGTH('aditya')FROM dual;


Output:
28

6
ASCII:
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
SELECT ASCII('A')FROM dual;
Output:
65

Chr:

SELECT CHR(97)FROM dual;


Output:
A

Reverse:

SELECT REVERSE('aditya')FROM dual;


Output:
aytida

Lpad:

SELECT LPAD('aditya',15,'*') as lpad FROM dual;


Output:

*********aditya
Rpad:

SELECT RPAD('aditya',15,'*') as rpad FROM dual;


Output:
aditya*********

Ltrim:

SELECT LTRIM(‘123123123rama123’,’123’)FROM dual;


Output:
rama123

Rtrim:

SELECT RTRIM(‘123123123rama123’,’123’)FROM dual;


Output:
123123123rama
29

Replace:
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
SELECT REPLACE('jack and joe','j','b')FROM dual;
Output:
back and boe

Initcap:

SELECT INITCAP('aditya engg')FROM dual;


Output:
Aditya Engg

Instr:

SELECT INSTR('abab','b')FROM dual;


Output:
2

Substr:
SELECT SUBSTR('abcdef',-3,2)FROM dual;
Output:
de

Numeric functions:
ABS():

SELECT ABS(19) FROM dual;


Output:
19
CEIL():

SELECT CEIL(2.2)FROM dual;


Output:
3
EXP():
SELECT EXP(3)FROM dual;
Output:

20.0855369
30
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
ROLL NO:
Date:
FLOOR():
SELECT FLOOR(-2.2)FROM dual;
Output:
-3
MOD():

SELECT MOD(150,7)FROM dual;

Output:

3
LOG():

SELECT LOG(2,2)FROM dual;


Output:
1
POWER():
SELECT POWER(3,2)FROM dual;
Output:
9
ROUND():

SELECT ROUND(66.666,2)FROM dual;


Output:
66.67
SIGN():
SELECT SIGN(-19)FROM dual;
Output:
-1
SELECT SIGN(19) FROM dual;
Output:
1
SQRT():
SELECT SQRT(9)FROM dual;
Output:
31

3
TRUNCATE():
Page

SELECT TRUNC(66.666,2)FROM dual;


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
ROLL NO:
Date:
Output:
66.66
Date functions:

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

SELECT TO_CHAR(SYSDATE,'yyyy/mm/dd')FROM dual;


Output:
2025/01/08

SELECT TO_CHAR(SYSDATE,'HH:MM:SS')FROM dual;


32

Output:
Page

11:01:43

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

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.

CREATE TABLE student_marks (


33

student_id number primary key,


Page

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.

INSERT INTO student_marks VALUES (101, 'Ravi', 56, 70);


INSERT INTO student_marks VALUES (102, 'Anil', 450, 20);
INSERT INTO student_marks VALUES (103, 'Balu', 620, 78);
INSERT INTO student_marks VALUES (104, 'Charan', 580, 72);
INSERT INTO student_marks VALUES (105, 'David', 390, 48);

SELECT * FROM student_marks;


output

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

scount NUMBER; -- Corrected declaration

no_records_found EXCEPTION;

BEGIN

SELECT COUNT(*) INTO scount FROM student_marks WHERE percentage >=


60;

IF scount = 0 THEN

RAISE no_records_found;

END IF;

dbms_output.put_line('First class students are:');

FOR records IN (SELECT * FROM student_marks WHERE percentage >= 60)

LOOP

dbms_output.put_line(records.student_id);
34

END LOOP;
Page

EXCEPTION
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No:
Date: ROLL NO:

WHEN no_records_found THEN

dbms_output.put_line('No students secured first class.');

WHEN OTHERS THEN

dbms_output.put_line('An unexpected error occurred.');

END;

OUTPUT:
first class students are ---- ::
101
103
104
PL/ procedure successfully completed.

35
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Week-5 B

Experiments
ii. Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in
PL/SQL block.

Program:5B

CREATE TABLE student


(
rollno integer,

name varchar2(20) );

OUTPUT:
Table created.

INSERT INTO student VALUES(501,'ravi');


Output:
1 row created.
SAVEPOINT
a; Output:
Savepoint created.
INSERT INTO student VALUES(502,'suma');
Output:
1 row created.
SAVEPOINT
b; Output:
Savepoint created.
INSERT INTO student VALUES(503,'padma');
Output:
1 row created.
SELECT * FROM student;
Output:
ROLLNO NAME
------------ ---------------
36

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.

SELECT * FROM student;


Output:
ROLLNO NAME

501 ravi
504 rani
37
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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

Enter value for


b: 3 old 3: b
Page

int:=&b; new
ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
3: b int:=3;
bigger
number3

Nested if case to find student_percentage

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

Nested if case to find greater number

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:

Enter value for a:


2 old 2: a integer
:= &a; new 2: a
integer := 2; Enter
value for b: 3 old
3: b integer := &b;
new 3: b integer
:= 3; Enter value
for c: 5 old 4: c
integer := &c;
new 4: c integer
:= 5; C is greater
CASE to find student_performance
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('BELOW AVERAGE');
ELSE
40

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

SELECT NULLIF('TECH','Tech Honey') FROM dual;

OUTPUT:

TECH

SELECT NULLIF(2,1) FROM dual;


OUTPUT:
2

SELECT NULLIF('tech honey','tech') FROM dual;

OUTPUT:
tech honey

SELECT NULLIF('TECH','TECH') FROM dual;


41
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
OUTPUT:

NULL
SELECT NULLIF(2,2) FROM dual;

OUTPUT:

NULL

SELECT NULLIF(1,2) FROM dual;

OUTPUT:

CREATE TABLE temps(

smallintcol integer,

bigintcol integer,

intcol integer);

OUTPUT:

Table created.

INSERT INTO temps VALUES(1,null,null);

OUTPUT:

1 row created

INSERT INTO temps VALUES(null,null,3);

OUTPUT:

1 row created.

COALESCE statements

SELECT COALESCE (smallintcol,bigintcol)

FROM temps;
42
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
OUTPUT:

SELECT COALESCE (smallintcol,bigintcol,intcol)


FROM temps;

OUTPUT:
1
2
3

SELECT COALESCE (smallintcol,intcol)


FROM temps;

OUTPUT:

1
3

43
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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;

Enter value for


n: 5 old 6:
n:=&n;
new 6: n:=5;
1
2
3
4
5
PL/ procedure successfully completed.
WHILE LOOP:
44

Write a PL/ program to print Sequence of n numbers using while loop.


Page

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:

Write a PL/ program to print Sequence of n numbers using for loop.


DECLARE
n NUMBER := &n;
BEGIN
IF n IS NULL THEN
dbms_output.put_line('Invalid value for n.');
RETURN;
END IF;

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

PL/ procedure successfully completed.


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:

EXCEPTIONS:

i) PL/ program to print divide by zero Exception


WITHOUT EXCEPTION:

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.

ii) PL/ program to print value error exception


WITHOUT EXCEPTION:

DECLARE
num number:=&num;
BEGIN
dbms_output.put_line('Square root of'||num||' is '||sqrt(num));
END;
/
Output:
46

Enter value for num: -6


old 2: num number:=&num;
Page

new 2: num number:=-6;


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
Square root of6 is
2.449489742783178098197
28407470589139197

WITH EXCEPTION:
DECLARE
num number:=&num;
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:=&num; new 2:
num number:=-54;
Value error
PL/ procedure successfully completed.

iii) Write a PL/ program to Unique Consraint violated Exception


WITHOUT EXCEPTION:

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
WITH EXCEPTION:

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.

iv) PL/ program to print no data found Exception


WITHOUT EXCEPTION:

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

SELECT sname INTO name FROM student WHERE roll_no = id;


Page

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.

i) PL/ program to print case not found Exception


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

when case_not_found then


dbms_output.put_line('Case not found');
Page

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.

USER DEFINED EXCPTION:

Write a PL/ program for user defined exception

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.

Write a PL/ program to raise_application_error.

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Output:
Enter value for n:
6 old 3: n
number:=&n;
new 3: n
number:=6; 1
2
3
4
5
6
declare
*
ERROR at line 1:
ORA-20015: loop
finish ORA-06512:
at line 13

Write a program for nested loops using ERROR Handling

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:

processing scores for student1:


total score for student1:253
processing scores for
student2:
error processing score for student2,score-5:ORA-20001: invalid score:-5for
student2
total score for student2:180
processing scores for
student3: total score for
student3:250 processing
scores for student4: no
valid scores for student4:
processing complete
PL/ procedure successfully completed.

52
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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.

Passing parameters IN and OUT of procedures:

CREATE PROCEDURE SUM_c(a in number,b in number,c out number)


as
BEGIN
c:=a+b;
END;
/
Output:
Procedure
created.
DECLARE
d number;
BEGIN
sum_c(2,7,d);
53

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

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.

SELECT sq(8) FROM dual;


Output :
SQ(8)

64

Write a stored function to find addition of two numbers

CREATE FUNCTION add_c(a in number, b in number)


return number
AS
c number;
BEGIN
c:=a+b;
return c;
END;
/
Output:
Function
55

created.
Page

DECLARE

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
d number;
BEGIN
d:=add_c(2,7
);
dbms_output.put_line(d);
END;
/

Output:
9
PL/ procedure successfully completed.

SELECT ADD_c(3,4) FROM dual;


Output :
ADD_C(3,4)

Write a stored function to find area of a rectangle

CREATE FUNCTION area_rect(l in number,b in number)


return number
as
area number;
BEGIN
area:=l*b;
return area;
END;
/
Output:
Function created.

select area_rect(2,7) from dual;


Output:
AREA_RECT(2,7)

14

DECLARE
area_rec number;
BEGIN
area_rec:=area_rect(2,7);
dbms_output.put_line(area_rec);
END;
/
Output:
14
56

PL/ procedure successfully completed.


Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:

Week-10
Experiments:
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR,
WHERE CURRENT of clause and CURSOR variables.
PROGRAM:

Write a explicit cursor using SIMPLE LOOP


SET SERVEROUTPUT
ON;
DECLARE
cursor sail_cur is
select sid,sname from sailors;
ab sail_cur%rowtype;
BEGIN
open sail_cur;
loop
fetch sail_cur into ab;
exit when sail_cur%NOTFOUND;
dbms_output.put_line(ab.sid||' '||ab.sname);
end loop;
close sail_cur;
END;
/
OUTPUT:
22 Dustin
29 Brutus
31 Lubber
32 Andy
58 Rusty
64 Horatio
71 Zorba
74 Ravi
85 Art
95 Bob
PL/ procedure successfully completed.
Write a explicit cursor using WHILE LOOP

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

fetch sail_cur into ab;


ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY
Exp No: ROLL NO:
Date:
end loop;
close sail_cur;
END;
/

OUTPUT:
22 Dustin
29 Brutus
31 Lubber
32 Andy
58 Rusty
64 Horatio
71 Zorba
74 Ravi
85 Art
95 Bob

PL/ procedure successfully completed.

Write a explicit cursor using FOR LOOP

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:

PL/ procedure successfully completed.


58
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No: ROLL NO:
Date:
Write an explicit cursor using FOR UPDATE
DECLARE
cursor sail_cursor is select sid,sname from sailors where rating = 10 for update;
var_sid sailors.sid%TYPE;
var_sname sailors.sname%TYPE;
BEGIN
open sail_cursor;
loop
fetch sail_cursor into var_sid, var_sname;
exit when sail_cursor%NOTFOUND;
UPDATE sailors SET age = age + 10 where current of sail_cursor;
dbms_output.put_line('Updated age for sailors : '|| var_sid);
end loop;
close sail_cursor;
commit;
END;
/

OUTPUT:

Updated age for sailors


: 58 Updated age for
sailors : 71

PL/ procedure successfully completed.

SELECT * FROM sailors;


SID SNAME RATING AGE

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

Write an explicit cursor using IS REF

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

PL/ procedure successfully completed.

60
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

BEGIN
-- trigger
code
EXCEPTION
WHEN ...
-- exception handling
END;

11 A)Write PL/SQL program to print welcome message after insertion for


each row in sailors table using trigger
Aim:-A PL/SQL program to print welcome message after insertion for each row in sailors
table using trigger
Source Code:-

CREATE OR REPLACE TRIGGER trg1


AFTER INSERT
ON sailors
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('Welcome to new sailors');
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

11 B) Write PL/SQL program to convert sailor name to uppercase and print


error message when rating below zero and above 10 before insert or update
on each row in sailors table using triggers
Aim:-A PL/SQL program to convert sailor name to uppercase and print error
message when rating below zero and above 10 before insert or update on each
row in sailors table using triggers
Source Code:-
62
Page

CREATE OR REPLACE TRIGGER TRG2

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

BEFORE INSERT OR UPDATE


ON sailors
FOR EACH ROW
BEGIN
-- Convert 'sname' to uppercase
:NEW.sname := UPPER(:NEW.sname);

-- Validate 'rating' value


IF :NEW.rating < 0 OR :NEW.rating > 10 THEN
RAISE_APPLICATION_ERROR(-20027, 'Invalid rating value---');
END IF;
END;
/

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

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Week-12
Experiments:
Create a table and perform the search operation on table using indexing and nonindexing
Techniques
PROGRAM:
Index in Oracle :

An index is a performance-tuning method of allowing faster retrieval of records. An


index creates an entry for each value that appears in the indexed columns. By default,
Oracle creates B-tree indexes.
Create an
Index

Syntax :

CREATE [UNIQUE] INDEX index_name


ON table_name (column1, column2, ... column_n) [
COMPUTE STATISTICS ];

Now we create the non indexed table

CREATE TABLE employees_non_indexed (


employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
department_id NUMBER
);

CREATE TABLE employees_indexed (


employee_id NUMBER PRIMARY KEY,
first_name VARCHAR2(50),
last_name VARCHAR2(50),
department_id NUMBER
);

CREATE INDEX idx_department_id ON employees_indexed(department_id);


64

SELECT * FROM employees_non_indexed WHERE department_id = 100;


Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Output:

EMPLOYEE_ID FIRST_NAME LAST_NAME DEPARTMENT_ID

1 John Doe 100

SELECT * FROM employees_indexed WHERE department_id = 100;

Output:

EMPLOYEE_ID FIRST_NAME LAST_NAME DEPARTMENT_ID

1 John Doe 100

65
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Week-13

PROGRAM

Write a java program that connects to a database using JDBC.

Source Code:

import java.sql.*;

public class DBConnection

public static void main(String[] args)

String url =" jdbc:oracle:thin:@localhost:1521:xe";

String userName = "root";

String pwd ="alekhya@123";

Connection con= null;

try{

//Establish the connection

con= DriverManager.getConnection(url, userName, pwd);

if(con!=null)

System.out.println("Connection established Successfully");

else{

System.out.println("Connection Failed");

}
66

}
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

catch(SQLException e)

System.out.println(e);

//Close the Connection

con.close();

Output:

67
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Week-14

PROGRAM

Write a java program to connect to a database using JDBC and insert values into it.

Source Code:

import java.sql.*;

public class InsertDemo {

public static void main(String[] args)

String url =" jdbc:oracle:thin:@localhost:1521:xe";

String userName = "root";

String pwd ="alekhya@123";

Connection con= null;

try{

//Establish the connection

con= DriverManager.getConnection(url, userName, pwd);

if(con!=null)

System.out.println("Connection established Successfully");

else

System.out.println("Connection Failed");

}
68

Statement st=con.createStatement();
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

String query="create table employee(eid int,ename varchar(20),salary


decimal(7,2))";

st.executeUpdate(query);

query="insert into employee values(111,'Sivaram',45000)";

int count=st.executeUpdate(query);

if(count>0)

System.out.println("Record Inserted Successfully");

catch(SQLException e)

System.out.println(e);

Output:

69
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Week-15

PROGRAM

Write a Java Program to demonstrate deletion of record from a database using


JDBC.

Source Code:

import java.sql.*;

public class DeletionDemo

public static void main(String[] args)

String url =" jdbc:oracle:thin:@localhost:1521:xe";

String userName = "root";

String pwd ="alekhya@123";

Connection con= null;

try{

//Establish the connection

con= DriverManager.getConnection(url, userName, pwd);

if(con!=null)

System.out.println("Connection established Successfully");

else

System.out.println("Connection Failed");
70
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY


Exp No:
Date: ROLL NO:

Statement st=con.createStatement();

String query="delete from employee where eid=111";

int count=st.executeUpdate(query);

if(count>0)

System.out.println("Record Deleted Successfully");

catch(SQLException e){

System.out.println(e);

Output:

71
Page

ADITYA COLLEGE OF ENGINEERING AND TECHNOLOGY

You might also like