Dbms Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 59

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

Year & Semester : II Year I Sem

Course : B.Tech

Branch : Computer Science & Engineering

Name of the Lab : Database Management System Lab

Regulation : R19

Signature of Faculty Signature of the HOD Signature of the Principal


INDEX

EXP No: Name of the Experiment Page No:

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

ADDITIONAL PROGRAMS

EXP No: Name of the Experiment Page No:

Write a PL/SQL program to check whether the given number is


1.
ARMSTRONG or not. 28

2. Write a PL/SQL Code Creation of forms for any Information System such 29-31
as Student Information System, Employee Information System etc.
SQL:
SQL stands for Structured Query Language. It is used for storing and managing data in relational database
management system (RDMS). It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables. All the RDBMS like MySQL, Informix,
Oracle, MS Access and SQL Server use SQL as their standard database language. SQL allows users to
query the database in a number of ways, using English-like statements.
Rules:
SQL follows the following rules:
1. Structure query language is not case sensitive. Generally, keywords of SQL are written in uppercase.
2. Statements of SQL are dependent on text lines. We can use a single SQL statement on one or multiple
text line.
3. Using the SQL statements, you can perform most of the actions in a database.
4. SQL depends on tuple relational calculus and relational algebra.

SQL process:
When an SQL command is executing for any RDBMS, then the system figure out the best way to carry out
the request and the SQL engine determines that how to interpret the task. In the process, various
components are included. These components can be optimization Engine, Query engine, Query dispatcher,
classic, etc. All the non-SQL queries are handled by the classic query engine, but SQL query engine won't
handle logical files.

Next To
SQL Commands:
SQL commands are instructions. It is used to communicate with the database. It is also used to perform
specific tasks, functions, and queries of data. SQL can perform various tasks like create a table, add data to
tables, drop the table, modify the table, set permission for users.
Types of SQL Commands:
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1
DDL: (Data Definition Language)
DDL allows you to create SQL statements to make operations with database data structures (schemas,
tables etc.).
These are SQL DDL commands list and examples:

CREATE:
CREATE statement is used to create a new database, table, index or stored procedure.
Create database example:
CREATE DATABASE explainjava;
Create table example:
CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
);

DROP:
DROP statement allows you to remove database, table, index or stored procedure.
Drop database example:
DROP DATABASE explainjava;
Drop table example:
DROP TABLE user;

2
ALTER:
ALTER is used to modify existing database data structures (database, table).
Alter table example:
ALTER TABLE user ADD COLUMN lastname VARCHAR(255) NOT NULL;

RENAME:
RENAME command is used to rename SQL table.
Rename table example:
RENAME TABLE user TO student;

TRUNCATE:
TRUNCATE operation is used to delete all table records. Logically it’s the same as DELETE command.
Differences between DELETE and TRUNCATE commands are:
1. TRUNCATE is really faster
2. TRUNCATE cannot be rolled back
3. TRUNCATE command does not invoke ON DELETE triggers

Example:
TRUNCATE student;

DML: (Data Manipulation Language)


DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate (select, insert, update,
delete etc.) data in the database.
This is DML commands list with examples:

SELECT:
SELECT query is used to retrieve a data from SQL tables.
Example:
SELECT * FROM student;

INSERT:
INSERT command is used to add new rows into the database table.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');

UPDATE:
UPDATE statement modifies records into the table.
Example:
UPDATE student SET name = 'Dima' WHERE lastname = 'Shvechikov';

DELETE:
DELETE query removes entries from the table.
3
Example:
DELETE FROM student WHERE name = 'Dima';

DCL: (Data Control Language)


DCL commands are responsible for access restrictions inside of the database.

GRANT:
GRANT command gives permissions to SQL user account.
For example, I want to grant all privileges to ‘explainjava’ database for user ‘dmytro@localhost’.
Create a user first:
CREATE USER 'dmytro'@'localhost' IDENTIFIED BY '123';
Then I can grant all privileges using GRANT statement:
GRANT ALL PRIVILEGES ON explainjava.* TO 'dmytro'@'localhost';

REVOKE:
REVOKE statement is used to remove privileges from user accounts.
Example:
REVOKE ALL PRIVILEGES ON explainjava.* FROM 'dmytro'@'localhost';

TCL: (Transaction Control Language)


TCL commands are used to manage transactions in SQL databases.
This is TCL commands list:

COMMIT:
COMMIT command finishes transaction and stores all changes made inside of a transaction.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
COMMIT;

ROLLBACK:
ROLLBACK statement reverts all changes made in the scope of transaction.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
ROLLBACK;

SAVEPOINT:
SAVEPOINT statement stores the transaction temporarily to restore/roll back.
Example:
INSERT INTO student (name, lastname) VALUES ('Dmytro', 'Shvechikov');
SAVEPOINT a;
INSERT INTO student (name, lastname) VALUES ('Angel', 'Paul');
ROLLBACK TO a;
4
EXPEREMENT 1
Aim: Data Definition Commands, Data Manipulation Commands for inserting and deleting data from
Tables.

1. Create table st:


SQL> create table st(sid int,sname varchar2(20),sdept varchar2(20),sgrade varchar2(20));

Table created.

2. Insert values into the table st:


SQL> insert into st values(101,'a','cse','A');

1 row created.

SQL> insert into st values(102,'b','cse','B');

1 row created.

SQL> insert into st values(103,'c','ece','A');

1 row created.

SQL> insert into st values(104,'a','ece','b');

1 row created.

SQL> desc st;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(38)
SNAME VARCHAR2(20)
SDEPT VARCHAR2(20)
SGRADE VARCHAR2(20)

SQL> select * from st;

SID SNAME SDEPT SGRADE


---------- -------------------- -------------------- --------------------
101 a cse A
102 b cse B
103 c ece A
104 a ece b
5
3. Alter the table st by adding column:
SQL> alter table st add saddress varchar2(10);

Table altered.

SQL> desc st;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(38)
SNAME VARCHAR2(20)
SDEPT VARCHAR2(20)
SGRADE VARCHAR2(20)
SADDRESS VARCHAR2(10)

Alter the table st by dropping column:


SQL> alter table st drop column saddress;

Table altered.

SQL> desc st;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(38)
SNAME VARCHAR2(20)
SDEPT VARCHAR2(20)
SGRADE VARCHAR2(20)

4. Rename the table st to stu:


SQL> rename st to stu;

Table renamed.

SQL> desc st;


ERROR:
ORA-04043: object st does not exist

SQL> desc stu;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(38)
SNAME VARCHAR2(20)
6
SDEPT VARCHAR2(20)
SGRADE VARCHAR2(20)

Create new table st:


SQL> create table st(sid int);

Table created.

5. Truncate the table st:


SQL> truncate table st;

Table truncated.

SQL> desc st;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NUMBER(38)

6. Drop the table st:


SQL> drop table st;

Table dropped.

SQL> desc st;


ERROR:
ORA-04043: object st does not exist

7
EXPEREMENT 2

AIM: Data Manipulation commands for updating and retrieving of data from Tables and Transaction
Control Statements.

Create table sailors:


SQL> create table sailors(sid int,sname varchar2(10),srating int,ssal int);

Table created.

1. Insert values into table sailors:


SQL> insert into sailors values(22,'dustin',7,50000);

1 row created.

SQL> insert into sailors values(29,'lubber',8,40000);

1 row created.

SQL> insert into sailors values(31,'brutus',1,30000);

1 row created.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
29 lubber 8 40000
31 brutus 1 30000

2. Update table sailors by modifying the name of a particular sailor:


SQL> update sailors set sname='bob' where sid=31;

1 row updated.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
29 lubber 8 40000
8
31 bob 1 30000

3. Delete row from the table sailors:


SQL> delete from sailors where sid=29;

1 row deleted.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
31 bob 1 30000

4. Retrieve the name of a particular sailor whose sid is 22:


SQL> select sname from sailors where sid=22;

SNAME
----------
dustin

TCL Commands:
SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
31 bob 1 30000

1.Commit:
SQL> commit;

Commit complete.

SQL> insert into sailors values(95,'brutus',10,60000);

1 row created.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
9
22 dustin 7 50000
31 bob 1 30000
95 brutus 10 60000

2. Savepoint:
SQL> savepoint a;

Savepoint created.

SQL> insert into sailors values(85,'art',10,60000);

1 row created.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
31 bob 1 30000
95 brutus 10 60000
85 art 10 60000

3.Rollback:
SQL> rollback to a;

Rollback complete.

SQL> select * from sailors;

SID SNAME SRATING SSAL


---------- ---------- ---------- ----------
22 dustin 7 50000
31 bob 1 30000
95 brutus 10 60000

10
EXPEREMENT 3

AIM: Basic Functions like Numeric, String, Date and Conversion functions.

Conversion functions

1. To_char:
SQL> select to_char(1234,'9999D99') from dual;

TO_CHAR(
--------
1234.00

SQL> select to_char(1234,'9G999') from


dual;

TO_CHA
------
1,234

SQL> select to_char(1234,'L9999') from dual;

TO_CHAR(1234,'L
---------------
$1234

SQL> select to_char(1234,'9999MI') from


dual;

TO_CH
-----
1234

SQL> select to_char(-1234,'9999MI') from dual;

TO_CH
-----
1234-

SQL> select to_char(-1234,'9999PR') from dual;

TO_CHA
11
------
<1234>

SQL> select to_char(10,'s99') from dual;

TO_ CHAR
---
+10

SQL> select to_char(10,'XX') from dual;

TO_
---
A

SQL> select to_char(10,'RN') from dual;

TO_CHAR(10,'RN'
---------------
X

SQL> select to_char(105,'0999') from


dual;

TO_CH
-----
0105

SQL> select to_char(100-10,'999') from dual;

TO_C
----
90

2. To_number:

SQL> select to_number('12','99') from dual;

TO_NUMBER('12','99')
--------------------
12
SQL> select to_number('12','99D9') from dual;
12
TO_NUMBER('12','99D9'
)
----------------------
12

SQL> select to_number('12','99D99') from dual;

TO_NUMBER('12','99D9
9')
-----------------------
12

3. To-date:

SQL> SELECT TO_DATE('06-DEC-21','dd-mm-yy') from


dual;

TO_DATE('
---------
06-DEC-21

SQL> SELECT TO_DATE('102118','mmddyy') from dual;

TO_DATE('
---------
21-OCT-18

String functions:
1. Lower():
SQL> select lower('SAI') from dual;
LOW
--------
sai

2. upper():
SQL> select upper('sai') from dual;
UPP
-----
SAI
3. concat():
SQL> select concat('hello','sai') from dual;
13
CONCAT('
--------
hellosai

4. initcap():
SQL> select initcap('sai') from dual;

INI
---
Sai

5. length():

SQL> select length('sai') from dual;


LENGTH('SAI')

3
6. Instr():

SQL> select instr('ruhanika','a') from dual;


INSTR('RUHANIKA','A')
-----------------------------------
4
7. Substr():

SQL> select substr('ruhanika',5) from dual;


SUBS
nika

8. Lpad():

SQL> select lpad('ruhanika',10,'****') from dual;


LPAD('RUHA
**ruhanika

9. Rpad():
SQL> select rpad('ruhanika',10,'****') from dual;
RPAD('RUHA
ruhanika**

10. Ltrim():

14
SQL>select ltrim(' ruhanika') from dual;
LTRIM('R
ruhanika

11. Rtrim():
SQL>selectrtrim(' ruhanika ') from dual;
RTRIM('RUHANIK
ruhanika

Date functions:
1. Sysdate():
SQL> select sysdate from dual;
SYSDATE
20-NOV-15

2. last_day():
SQL> select last_day(sysdate) fromdual;
LAST_DAY(
30-NOV-15

3. next_day():
SQL> select next_day('20-nov-2015','friday') fromdual;
NEXT_DAY(
27-NOV-15

4. add_months():
SQL> select add_months(sysdate,2) from dual;
ADD_MONTH
20-JAN-16

5. months_between():
SQL> select months_between('20-nov-2015','20-jan-2016') from dual;
MONTHS_BETWEEN('20-NOV-2015','20-JAN-2016')
-2
6. least():
SQL> select least(10,11,12) from dual;
LEAST(10,11,12)
10
SQL> select least('s','f','a') from dual;
L
-
15
a
7. greatest():
SQL> select greatest(10,11,12) from dual;
GREATEST(10,11,12)
12
SQL> select greatest('s','f','a') from dual;
G
-
s

8. round():

SQL> select round(21.088) from dual;


ROUND(21.088)
21
SQL> select trim(21.088) from dual;
TRIM(2)
21.08

16
EXPEREMENT 4
Aim: Database Querying: Basic simple queries.

Create Sailors Table:

SQL> create table sailors(sid int primary key not null,sname varchar2(20),srating int,sage
int,check(sage>=25));

Table created.

Create Boats Table:

SQL> create table boats(bid int primary key not null,bname varchar2(20),bcolor varchar2(10));

Table created.

Create Reserves Table:

SQL> create table reserves(sid int,bid int,day varchar2(20),constraint fk1 foreign key(sid) references
sailors(sid),constraint fk2 foreign key(bid) references boats(bid));
Table created.
Insert values into Sailors Table:
SQL> insert into sailors values(22,'dustin',7,45);
1 row created.
SQL> insert into sailors values(22,'dustin',7,15);
insert into sailors values(22,'dustin',7,15)
*
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C004016) violated

SQL> insert into sailors values(29,'brutus',1,33);


1 row created.
SQL> insert into sailors values(31,'lubber',8,56);
1 row created.

17
SQL> insert into sailors values(32,'andy',8,26);
1 row created.
SQL> insert into sailors values(58,'rusty',10,36);
1 row created.
SQL> insert into sailors values(64,'horatio',7,36);
1 row created.
SQL> insert into sailors values(74,'horatio',9,35);
1 row created.
Insert values into Boats Table:
SQL> insert into boats values(101,'interlake','blue');
1 row created.

SQL> insert into boats values(102,'inter','red');


1 row created.

SQL> insert into boats values(103,'clipper','green');


1 row created.

SQL> insert into boats values(104,'marine','red');


1 row created.

Insert values into Reserves Table:


SQL> insert into reserves values(22,101,'10-oct-98');

1 row created.

SQL> insert into reserves values(22,102,'10-oct-98');

1 row created.

SQL> insert into reserves values(22,103,'10-aug-98');

1 row created.

SQL> insert into reserves values(22,104,'10-jul-98');

1 row created.

SQL> insert into reserves values(31,104,'10-dec-98');

1 row created.

SQL> insert into reserves values(64,102,'10-aug-98');


18
1 row created.

SQL> insert into reserves values(74,103,'10-aug-98');

1 row created.

SQL> select * from sailors;

SID SNAME SRATING SAGE


---------- -------------------- ---------- ----------
22 dustin 7 45
29 brutus 1 33
31 lubber 8 56
32 andy 8 26
58 rusty 10 36
64 horatio 7 36
74 horatio 9 35

7 rows selected.

SQL> select * from boats;

BID BNAME BCOLOR


---------- -------------------- ----------
101 interlake blue
102 inter red
103 clipper green
104 marine red

SQL> 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 104 10-dec-98
64 102 10-aug-98
74 103 10-aug-98

7 rows selected.

1. Find all sailors with rating above 9?


SQL> select * from sailors where srating>9;

19
SID SNAME SRATING SAGE
---------- -------------------- ---------- ----------
58 rusty 10 36

2. Find the names of sailors with rating above7?


SQL> select sname from sailors where srating>7;

SNAME
--------------------
lubber
andy
rusty
horatio

3. Find the names of the sailors who have reserved boat no 103?
SQL> select sname from sailors s,reserves r where s.sid=r.sid and r.bid=103;

SNAME
--------------------
dustin
horatio

4. Find the sid of sailors who have reserved a red boat.


SQL> select sid from reserves r, boats b where r.bid=b.bid and b.bcolor='red';

SID
----------
22
22
31
64

5. Find the name of the sailors who have reserved a green boat.
SQL> select sname from sailors s,boats b,reserves r where s.sid=r.sid and r.bid=b.bid and
b.bcolor='green';

SNAME
--------------------
dustin
horatio

6. Find the color of boat reserved by lubber


20
SQL> select b.bcolor from boats b,reserves r , sailors s where r.bid=b.bid and r.sid=s.sid and
s.sname='lubber';

BCOLOR
----------
red
7. Find all the sailors who have reserved atleast one boat
SQL> select distinct s.sname from sailors s ,reserves r where s.sid=r.sid;

SNAME
--------------------
lubber
dustin
horatio

8. Compute and increment the rating and display the name and sid of sailors who have sailed 2
different boats on same day
SQL> select distinct s1.sname, s1.sid, s1.srating+1 as inc_rate
2 From sailors s1, reserves r1, reserves r2
3 Where r1.bid<>r2.bid and r1.sid =r2.sid and r1.day=r2.day and r1.sid=s1.sid;

SNAME SID INC_RATE


-------------------- ---------- ----------
dustin 22 8

21
EXPEREMENT 5

Aim: Queries using Aggregate functions, GROUP BY and HAVING Clauses.

Create table product

SQL> create table product(pno int ,pname varchar2(20),price float,quantity int);


Table created.
Insert into product

SQL> insert into product values(1,'dairymilk',60,2);


1 row created.
SQL> insert into product values(2,'goodday',25,4);
1 row created.
SQL> insert into product values(3,'boost',10,6);
1 row created.
SQL> insert into product values(4,'maggi',5,10);.
1 row created.
SQL> insert into product values(5,'book',20,20);
1 row created.
Select from product

SQL> select * from product;

PNOPNAME PRICE QUANTITY


------------------------------------------------------------------------------
1 dairy milk 60 2
2 good day 25 4
3 boost 10 6
4 maggi 5 10
5 book 20 20

Aggregate Functions:

1. Count():

22
SQL> select count(price) from product;
COUNT(PRICE)
----------------------
5

SQL> select count(quantity) from product;


COUNT(QUANTITY)
-----------------------------
5

2. Sum ():

SQL> select sum(price) from product;


SUM(PRICE)
---------------
120

SQL> select sum(quantity) from product;


SUM(QUANTITY)
----------------------
42
3. Avg():

SQL> select avg(price) from product;


AVG(PRICE)
-------------------
24

SQL> select avg(quantity) from product;


AVG(QUANTITY)
-------------------------
8.4
4. Max():

SQL> select max(price) from product;


MAX(PRICE)
------------------
60

23
SQL> select max(quantity) from product;
MAX(QUANTITY)
--------------------
20

5. Min():
SQL> select min(price) from product;
MIN(PRICE)
------------------
5

SQL> select min(quantity) from product;


MIN(QUANTITY)
-----------------------
2

Group by Clause:

Create table employ(sid int, name varchar2(20), dept varchar2(10), sal float);
Table created
Select * from employ
Sid name deptsal
1 Ayisha ece 6000
2 Sindhu it 5000
3 Sai it 8000
4 Lalli ece 8000

SQL>select dept,sum(sal) from employ group by dept;


Dept sum(sal)
It 13000
Ece 14000

Having Clause:
SQL>select dept,sum(sal) from employ group by dept having sum(sal)>13000;

Dept sum(sal)
ece 14000

24
EXPEREMENT 6

AIM: Database Querying – Nested Queries, Sub Queries

Create Sailors Table:

SQL> create table sailors(sid int primary key not null,sname varchar2(20),srating int,sage
int,check(sage>=25));

Table created.

Create Boats Table:

SQL> create table boats(bid int primary key not null,bname varchar2(20),bcolor varchar2(10));

Table created.

Create Reserves Table:

SQL> create table reserves(sid int,bid int,day varchar2(20),constraint fk1 foreign key(sid) references
sailors(sid),constraint fk2 foreign key(bid) references boats(bid));
Table created.
Insert values into Sailors Table:
SQL> insert into sailors values(22,'dustin',7,45);
1 row created.
SQL> insert into sailors values(22,'dustin',7,15);
insert into sailors values(22,'dustin',7,15)
*
ERROR at line 1:
ORA-02290: check constraint (SYSTEM.SYS_C004016) violated

SQL> insert into sailors values(29,'brutus',1,33);


1 row created.
25
SQL> insert into sailors values(31,'lubber',8,56);
1 row created.
SQL> insert into sailors values(32,'andy',8,26);
1 row created.
SQL> insert into sailors values(58,'rusty',10,36);
1 row created.
SQL> insert into sailors values(64,'horatio',7,36);
1 row created.
SQL> insert into sailors values(74,'horatio',9,35);
1 row created.
Insert values into Boats Table:
SQL> insert into boats values(101,'interlake','blue');
1 row created.

SQL> insert into boats values(102,'inter','red');


1 row created.

SQL> insert into boats values(103,'clipper','green');


1 row created.

SQL> insert into boats values(104,'marine','red');


1 row created.

Insert values into Reserves Table:


SQL> insert into reserves values(22,101,'10-oct-98');

1 row created.

SQL> insert into reserves values(22,102,'10-oct-98');

1 row created.

SQL> insert into reserves values(22,103,'10-aug-98');

1 row created.

SQL> insert into reserves values(22,104,'10-jul-98');

1 row created.

SQL> insert into reserves values(31,104,'10-dec-98');

26
1 row created.

SQL> insert into reserves values(64,102,'10-aug-98');

1 row created.

SQL> insert into reserves values(74,103,'10-aug-98');

1 row created.

SQL> select * from sailors;

SID SNAME SRATING SAGE


---------- -------------------- ---------- ----------
22 dustin 7 45
29 brutus 1 33
31 lubber 8 56
32 andy 8 26
58 rusty 10 36
64 horatio 7 36
74 horatio 9 35

7 rows selected.

SQL> select * from boats;

BID BNAME BCOLOR


---------- -------------------- ----------
101 interlake blue
102 inter red
103 clipper green
104 marine red

SQL> 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 104 10-dec-98
64 102 10-aug-98
74 103 10-aug-98

7 rows selected.

27
1. Find the names of the sailors who have reserved boat 103
SQL> select sname from sailors where sid IN(select sid from reserves where bid=103);

SNAME
--------------------
dustin
horatio
2. Find the names of sailors who have reserved a red boat.
SQL> select sname from sailors where sid IN (select sid from reserves where bid in (select bid from
boats where bcolor = 'red'));

SNAME
--------------------
dustin
lubber

horatio

3. Find the names of sailors who have not reserved a red boat.
SQL> select sname from sailors
2 where sid NOT IN ( select sid from reserves where bid IN (select bid
3 from boats where bcolor = 'red'));

SNAME
--------------------
brutus
andy
rusty

horatio

4. Find the sailors whose raing is better than some sailor horatio
Select s.sid from sailors s
2 Where s.srating> ANY (select s1.srating from sailors s1 where s1.sname='horatio');
28
SID
----------
58
74
31
32
5. Find the sailors with highest rating
select s.sid from sailors s Where s.srating>=ALL(select s1.srating from sailors s1);

SID
----------
58
6. Find the names of the sailors who have reserved a boat number 103
SQL> select s.sname from sailors s where exists (select * from reserves r where r.bid=103 and
r.sid=s.sid);

SNAME
--------------------
dustin

horatio

7. Find the names of sailors who have reserved all boats

SQL> Select s.sname from sailors s Where NOT EXISTS( select b.bid from boats b

2 Where NOT EXISTS(select r.bid from reserves r Where r.sid=s.sid and r.bid=b.bid));

SNAME

--------------------

29
dustin

EXPEREMENT 7
AIM: Queries Using Joins

Create table customer:


SQL> create table customer(cid int primary key not null,cname varchar2(20),age int,sal int);

Table created.

Insert values into the table customer:


SQL> insert into customer values(1,'divya',23,34000);

1 row created.

SQL> insert into customer values(2,'chandu',45,56000);

1 row created.

SQL> insert into customer values(4,'vani',78,null);

1 row created.

SQL> insert into customer values(6,'ani',34,7800);

1 row created.

SQL> insert into customer values(7,'an',28,6500);

1 row created.

SQL> insert into customer values(9,'anil',45,8900);

1 row created.

SQL> insert into customer values(10,'pavan',23,80900);

1 row created.

30
Create table orders:
SQL> create table orders(sno int primary key not null,orderdate date,cid int,sid int,amount int);

Table created.

Insert values into the table orders:


SQL> insert into orders values(1,'8-Aug-96',4,2,540);

1 row created.

SQL> insert into orders values(2,'9-Aug-96',4,8,1800);

1 row created.

SQL> insert into orders values(3,'9-sep-96',9,1,460);

1 row created.

SQL> insert into orders values(4,'10-sep-96',7,2,2400);

1 row created.

SQL> insert into orders values(5,'10-jun-98',6,7,600);

1 row created.

SQL> insert into orders values(6,'10-jan-98',6,7,720);

1 row created.

SQL> insert into orders values(7,'13-jan-98',9,7,150);

1 row created.

SQL> select * from orders;

SNO ORDERDATE CID SID AMOUNT


---------- --------- ---------- ---------- ----------
1 08-AUG-96 4 2 540
2 09-AUG-96 4 8 1800
3 09-SEP-96 9 1 460
31
4 10-SEP-96 7 2 2400
5 10-JUN-98 6 7 600
6 10-JAN-98 6 7 720
7 13-JAN-98 9 7 150

7 rows selected.

SQL> select * from customer;

CID CNAME AGE SAL


---------- -------------------- ---------- ----------
1 divya 23 34000
2 chandu 45 56000
4 vani 78
6 ani 34 7800
7 an 28 6500
9 anil 45 8900
10 pavan 23 80900

7 rows selected.

INNER JOIN:
SQL> select cname,age,sid,amount from customer inner join orders on customer.cid=orders.cid;

CNAME AGE SID AMOUNT


-------------------- ---------- ---------- ----------
vani 78 2 540
vani 78 8 1800
anil 45 1 460
an 28 2 2400
ani 34 7 600
ani 34 7 720
anil 45 7 150

7 rows selected.

LEFT JOIN:
SQL> select cname,age,sid,orderdate,amount from customer left join orders on
customer.cid=orders.cid;

CNAME AGE SID ORDERDATE AMOUNT


-------------------- ---------- ---------- --------- ----------
32
vani 78 2 08-AUG-96 540
vani 78 8 09-AUG-96 1800
anil 45 1 09-SEP-96 460
an 28 2 10-SEP-96 2400
ani 34 7 10-JUN-98 600
ani 34 7 10-JAN-98 720
anil 45 7 13-JAN-98 150
divya 23
chandu 45
pavan 23

10 rows selected.

RIGHT JOIN:
SQL> select cname,age,sid,amount from customer right join orders on customer.cid=orders.cid;

CNAME AGE SID AMOUNT


-------------------- ---------- ---------- ----------
vani 78 8 1800
vani 78 2 540
ani 34 7 720
ani 34 7 600
an 28 2 2400
anil 45 7 150
anil 45 1 460

7 rows selected.

FULL JOIN:
SQL> select cname,age,sid,amount from customer full join orders on customer.cid=orders.cid;

CNAME AGE SID AMOUNT


-------------------- ---------- ---------- ----------
vani 78 2 540
vani 78 8 1800
anil 45 1 460
an 28 2 2400
ani 34 7 600
ani 34 7 720
anil 45 7 150
divya 23
chandu 45
33
pavan 23

10 rows selected.

CROSS JOIN:
SQL> select cname,age,amount from customer cross join orders;

CNAME AGE AMOUNT


-------------------- ---------- ----------
divya 23 540
chandu 45 540
vani 78 540
ani 34 540
an 28 540
anil 45 540
pavan 23 540
divya 23 1800
chandu 45 1800
vani 78 1800
ani 34 1800

CNAME AGE AMOUNT


-------------------- ---------- ----------
an 28 1800
anil 45 1800
pavan 23 1800
divya 23 460
chandu 45 460
vani 78 460
ani 34 460
an 28 460
anil 45 460
pavan 23 460
divya 23 2400

CNAME AGE AMOUNT


-------------------- ---------- ----------
chandu 45 2400
vani 78 2400
ani 34 2400
an 28 2400
34
anil 45 2400
pavan 23 2400
divya 23 600
chandu 45 600
vani 78 600
ani 34 600
an 28 600

CNAME AGE AMOUNT


-------------------- ---------- ----------
anil 45 600
pavan 23 600
divya 23 720
chandu 45 720
vani 78 720
ani 34 720
an 28 720
anil 45 720
pavan 23 720
divya 23 150
chandu 45 150

CNAME AGE AMOUNT


-------------------- ---------- ----------
vani 78 150
ani 34 150
an 28 150
anil 45 150
pavan 23 150

49 rows selected.

35
EXPEREMENT 8

AIM: Queries using Views.

1. Create a view:
SQL> create or replace view an as select eid,name from employeee;

View created.

SQL> select * from an;

EID NAME
---------- --------------------
1 amit
2 sachin
3 vinay
4 vivek

2. Update view:
SQL> update an set name='sunil' where eid=4;

1 row updated.

SQL> select * from an;

EID NAME
---------- --------------------
1 amit
2 sachin
3 vinay
4 sunil

36
3. Delete from view:
SQL> delete from an where eid=4;

1 row deleted.

SQL> select * from an;

EID NAME
---------- --------------------
1 amit
2 sachin
3 vinay

4. Dropping view:
SQL> drop view an;

View dropped.

SQL> select * from an;


select * from an
*
ERROR at line 1:
ORA-00942: table or view does not exist

37
EXPEREMENT 9

AIM: Procedures and Functions.

Procedure:
A subprogram is a program unit/module that performs a particular task. These subprograms are combined
to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked by
another subprogram or program which is called the calling program.
A subprogram can be created −

 At the schema level


 Inside a package
 Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted with
the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the database and can be
deleted only when the package is deleted with the DROP PACKAGE statement.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters. PL/SQL
provides two kinds of subprograms −
 Functions − These subprograms return a single value; mainly used to compute and return a value.
 Procedures − These subprograms do not return a value directly; mainly used to perform an action.

Creating a Procedure:
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name[IN | OUT | IN OUT] type [,...])]
{AS/IS}
BEGIN
<procedure_body>
ENDprocedure_name;
Where,
 procedure-name specifies the name of the procedure.
 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of the parameters. IN represents the value
that will be passed from outside and OUT represents the parameter that will be used to return a value
outside of the procedure.
 procedure-body contains the executable part.

38
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the screen when
executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.

Executing a Standalone Procedure

A standalone procedure can be called in two ways −


 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World

PL/SQL procedure successfully completed.

Deleting a Standalone Procedure


A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a
procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms


1. IN:
This is the Default Parameter for the procedure. It always receives the values from calling program.
2. OUT:
This parameter always sends the values to the calling program.
3. IN OUT:
This parameter performs both the operations. It Receives value from as well as sends the values to the
calling program.

1) Creation of procedures and passing parameters IN and OUT of procedures:


39
i. PL/SQL Program to find minimum of 2 numbers using Procedures.
SQL> declare
2 a number;
3 b number;
4 c number;
5 procedure findmin(x in number,y in number,z out number)
6 is
7 begin
8 if x<y then
9 z:=x;
10 else
11 z:=y;
12 end if
13 ;
14 end;
15 begin
16 a:=23;
17 b:=45;
18 findmin(a,b,c);
19 dbms_output.put_line('minimum='||c);
20 end;
21 /
Output: minimum=23

PL/SQL procedure successfully completed.

ii. PL/SQL Program to find square of given number using Procedures.


SQL> declare
2 a number;
3 procedure squarenum(x in out number)
4 is
5 begin
6 x:=x*x;
7 end;
8 begin
9 a:=25;
10 squarenum(a);
11 dbms_output.put_line('square='||a);
12 end;
13 /
Output: square=625

40
PL/SQL procedure successfully completed.

iii. PL/SQL Program to find the total number of primes up to given number Procedures.

SQL> create or replace procedure prime (n IN number, tot OUT number)as


2 i number;
3 c number;
4 j number;
5 begin
6 i:=1;
7 tot:=0;
8 while(i<=n)
9 loop
10 j:=1;
11 c:=0;
12 while(j<=i)
13 loop
14 if(mod(i,j)=0) then
15 c:=c+1;
16 end if;
17 j:=j+1;
18 end loop;
19 if(c=2) then
20 dbms_output.put_line(i);
21 tot:=tot+1;
22 end if;
23 i:=i+1;
24 end loop;
25 end;
26 /

Procedure created.

/*calling procedure prime*/

SQL> set serveroutput on


SQL> declare
2 t number;
3 begin
4 prime(20,t);
5 dbms_output.put_line('the total prime nos are:'||t);

41
6 end;
7 /
Output: 2
3
5
7
11
13
17
19
the total prime nos are:8

PL/SQL procedure successfully completed.

iv. PL/SQL Program to insert values into a table using Procedures.


SQL> select * from sos;

SNO SNAME
---------- ----------
1 jaya
3 ani

SQL> create or replace procedure addtuple1(x in number, y in varchar2)


2 is
3 begin
4 insert into sos values(x,y);
5 end;
6 /

Procedure created.

/*calling procedure addtuple1*/


SQL> set serveroutput on
SQL> declare
2 begin
3 addtuple1(4,'sunil');
4 end;
5 /

PL/SQL procedure successfully completed.

SQL> select * from sos;

42
SNO SNAME
---------- ----------
1 jaya
3 ani
4 sunil

SQL> drop procedure addtuple1;

Procedure dropped

2) Functions and invoke functions in SQL statements:

Creating a Function:

A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for
the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN represents the value
that will be passed from outside and OUT represents the parameter that will be used to return a value
outside of the procedure.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the function.
 function-body contains the executable part.

i. PL/SQL Program to find the maximum number from the given numbers using Functions.
SQL> set serveroutput on
SQL> DECLARE
2 a number;
3 b number;
4 c number;

43
5 FUNCTION findMax(x IN number, y IN number)
6 RETURN number
7 IS
8 z number;
9 BEGIN
10 IF x > y THEN
11 z:= x;
12 ELSE
13 Z:= y;
14 END IF;
15 RETURN z;
16 END;
17 BEGIN
18 a:= 23;
19 b:= 45;
20 c := findMax(a, b);
21 dbms_output.put_line(' Maximum of (23,45): ' || c);
22 END;
23 /
Maximum of (23,45): 45

PL/SQL procedure successfully completed.


ii. PL/SQL Program to find the total number of customers in a given table using Functions.
SQL> select * from sos;

SNO SNAME
---------- ----------
1 jaya
3 ani
4 sunil

SQL> create function totalcust


2 return number
3 as
4 total number(3):=0;
5 begin
6 select count(*) into total from sos;
7 return total;
8 end;
9 /

Function created.

44
/*calling function totalcust*/

SQL> set serveroutput on


SQL> declare
2 c number(3);
3 begin
4 c:=totalcust();
5 dbms_output.put_line(' total: ' || c);
6 end;
7 /
total: 3

PL/SQL procedure successfully completed.


iii. PL/SQL Program to find the factorial of a given number using Functions.
SQL> set serveroutput on
SQL> DECLARE
2 num number;
3 factorial number;
4
5 FUNCTION fact(x number)
6 RETURN number
7 IS
8 f number;
9 BEGIN
10 IF x=0 THEN
11 f := 1;
12 ELSE
13 f := x * fact(x-1);
14 END IF;
15 RETURN f;
16 END;
17
18 BEGIN
19 num:= 6;
20 factorial := fact(num);
21 dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
22 END;
23 /
Factorial 6 is 720

PL/SQL procedure successfully completed.

45
SQL> drop function totalcust;

Function dropped.

46
EXPEREMENT 10
AIM: Implicit and Explicit Cursors.

CURSORS:
A CURSOR is nothing but a pointer between the contest area and physical data storage contest area is a memory
which is reserved by oracle for crossing SQL statements. Suppose use for select statement then some memory
was allocated and then memory is said to be in contest area.
CURSOR can be divided into two types
 Implicit CURSOR
 Explicit CURSOR
Explicit Cursor- You can explicitly declare a cursor to process the rows individually. A cursor declared by
the user is called Explicit Cursor. For Queries that return more than one row, you must declare a cursor
explicitly. The data that is stored in the cursor is called the Active Data set. The size of the cursor in
memory is the size required to hold the number of rows in the Active. Cursor can be used when the user
wants to process data one row at a time.
Explicit Cursor Management- The steps involved in declaring a cursor and manipulating data in the
active data set are:-
• Declare a cursor that specifies the SQL select statement that you want to process.
• Open the Cursor.
• Fetch the data from the cursor one row at a time.
• Close the cursor.
Declaration: The General Syntax to create any particular cursor is as follows:-
Cursor<cur name> is Sql Select Statement;
Opening a Cursor: The General Syntax to Open any particular cursor is as follows:-
Open Cursorname;
Fetching a record From the Cursor: The fetch statement retrieves the rows from the active set to the
variables one at a time. Each time a fetch is executed. The focus of the DBA cursor advances to the next
row in the Active set. One can make use of any loop structure (Loop-End Loop along with While, For) to
fetch the records from the cursor into variable one row at a time. The General Syntax to Fetch the records
from the cursor is as follows:-
Fetch cursorname into variable1,variable2,______
Closing a Cursor:- The General Syntax to Close the cursor is as follows:-
Close <cur name>;

47
Implicit Cursors:

SQL> create table emp(eid int,ename varchar2(20),esal int);

Table created.

SQL> desc emp;


Name Null? Type
----------------------------------------- -------- ----------------------------
EID NUMBER(38)
ENAME VARCHAR2(20)
ESAL NUMBER(38)

SQL> insert into emp values(101,'raju',15000);

1 row created.

SQL> insert into emp values(102,'rani',25000);

1 row created.

I. Update the salary of employees using Cursors.

SQL> set serveroutput on


SQL> declare
2 r int;
3 begin
4 update emp set esal=esal+100;
5 if sql%notfound then
6 dbms_output.put_line('none are updated');
7 else if sql%found then
8 r:=sql%rowcount;
9 dbms_output.put_line('salaries for '||r||' emp are updated');
10 end if;
11 end if;
12 end;
13 /
salaries for 2 emp are updated

PL/SQL procedure successfully completed.

48
SQL> select * from emp;

EID ENAME ESAL


---------- -------------------- ----------
101 raju 15100
102 rani 25100

Explicit Cursors:

II. Retrieve the names of employees using Cursors.

SQL> set serveroutput on


SQL> declare
2 eename emp.ename%type;
3 cursor ecur is
4 select ename from emp;
5 begin
6 open ecur;
7 loop
8 fetch ecur into eename;
9 exit when ecur%notfound;
10 dbms_output.put_line(eename);
11 end loop;
12 close ecur;
13 end;
14 /
raju
rani

PL/SQL procedure successfully completed.

49
EXPEREMENT 11

AIM: Triggers.

Trigger: A trigger is a stored procedure in database which automatically invokes whenever a special
event in the database occurs. For example, a trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated.
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

Explanation of syntax:
create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
[before | after]: This specifies when the trigger will be executed.
{insert | update | delete}: This specifies the DML operation.
on [table_name]: This specifies the name of the table associated with the trigger.
[for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected.
[trigger_body]: This provides the operation to be performed as trigger is fired

BEFORE and AFTER of Trigger:


BEFORE triggers run the trigger action before the triggering statement is run.
AFTER triggers run the trigger action after the triggering statement is run.

1) Steps for doing Trigger Program:


a. First create a table (Don’t insert any values into created table)
b. Write code for Trigger and run the trigger program
c. Insert values into the created table after successfully completion of trigger program and
see the trigger output.

SQL> create table stud(sid int,sub1 int);

Table created.

Create Trigger (Before):

SQL> create or replace trigger trg1 before


50
2 insert on stud
3 for each row
4 begin
5 dbms_output.put_line('before insert of'||:new.sid);
6 end;
7 /

Trigger created.

Insert:
SQL> insert into stud values(1,20);
before insert of1

1 row created.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20

Insert:
SQL> insert into stud values(2,16)
2 ;
before insert of2

1 row created.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20
2 16
3
Create trigger (After):
create or replace trigger trg2 after
2 insert on stud
3 for each row
4 begin
5 dbms_output.put_line('after insert of'||:new.sid);
6 end;

51
7 /

Trigger created.

Insert:
SQL> insert into stud values(3,16);
before insert of3
after insert of3

1 row created.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20
2 16
3 16

Create Trigger:
SQL> create or replace trigger trg1 before
2 update on stud
3 for each row
4 begin
5 dbms_output.put_line('before update of'||:new.sid);
6 end;
7 /

Trigger created.

Update:
SQL> update stud set sub1=30 where sid=2;
before update of2

1 row updated.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20
2 30

52
3 16
4 17

Create Trigger:
SQL> create or replace trigger trg2 after
2 delete on stud
3 for each row
4 begin
5 dbms_output.put_line('after delete'||:new.sid);
6 end;
7 /

Trigger created.

Delete:
SQL> delete from stud where sid=3;
after delete

1 row deleted.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20
2 30
4 17

EXPEREMENT 12
53
AIM: Exception Handling.

Structure of PL/SQL Block:


PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural
language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are
made up of blocks, which can be nested within each oth

Typically, each block performs a logical action in the program. A block has the following structure:
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;

 Declare section starts with DECLARE keyword in which variables, constants, records as cursors can
be declared which stores data temporarily. It basically consits definition of PL/SQL identifiers. This
part of the code is optional.
 Execution section starts with BEGIN and ends with END keyword. This is a mandatory section and
here the program logic is written to perform any task like loops and conditional statements. It supports
all DML commands, DDL commands and SQL*PLUS built-in functions as well.
 Exception section starts with EXCEPTION keyword. This section is optional which contains
statements that are executed when a run-time error occurs. Any exceptions can be handled in this
section.

An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us
the exception block which raises the exception thus helping the programmer to find out the fault and
resolve it.

There are two types of exceptions defined in PL/SQL


.
 User defined exception.
 System defined exceptions.
54
Syntax:
WHEN exception THEN
statement;

DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;

When other keyword should be used only at the end of the exception handling block as no exception
handling part present later will get executed as the control will exit from the block after executing the
WHEN OTHERS.

Exceptions:

1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows. For eg:
2. TOO_MANY_ROWS: It is raised WHEN a SELECT INTO statement returns more than one
row.
3. VALUE_ERROR: This error is raised WHEN a statement is executed that resulted in an
arithmetic, numeric, string, conversion, or constraint error. This error mainly results from
programmer error or invalid data input.
4. ZERO_DIVIDE: It raises exception WHEN dividing with zero.

SQL> select * from stud;

SID SUB1
---------- ----------
1 20
2 30
4 17

55
Without Exception:
SQL> set serveroutput on
SQL> declare
2 m number(5);
3 myerror exception;
4 begin
5 select sub1 into m from stud where sid=2;
6 if m is null then
7 raise myerror;
8 else
9 dbms_output.put_line(m);
10 end if;
11 exception
12 when no_data_found then
13 dbms_output.put_line('error of data');
14 when too_many_rows then
15 dbms_output.put_line('error of too many rows');
16 when myerror then
17 dbms_output.put_line('error found null');
18 end;
19 /

30

PL/SQL procedure successfully completed.

With Exception:
SQL> set serveroutput on
SQL> declare
2 m number(5);
3 myerror exception;
4 begin
5 select sub1 into m from stud where sid=3;
6 if m is null then
7 raise myerror;
8 else
9 dbms_output.put_line(m);
10 end if;
11 exception
12 when no_data_found then
13 dbms_output.put_line('error of data');
14 when too_many_rows then
15 dbms_output.put_line('error of too many rows');
16 when myerror then
17 dbms_output.put_line('error found null');
18 end;
19 /
error of data

56
PL/SQL procedure successfully completed.

57

You might also like