Dbms Lab - Manual
Dbms Lab - Manual
Course Objectives:
Introduce ER data model, database design and normalization
Learn SQL basics for data definition and data manipulation
LIST OF EXPERIMENTS:
1. Concept design with E-R Model
2. Relational Model
3. Normalization
4. Practicing DDL commands
5. Practicing DML commands
6. A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
B. Nested, Correlated subqueries
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and
dropping of Views.
8. Triggers (Creation of insert trigger, delete trigger, update trigger)
9. Procedures
10. Usage of Cursors
Course Outcomes:
● Design database schema for a given application and apply normalization
● Acquire skills in using SQL commands for data definition and data manipulation.
● Develop solutions for database applications using procedures, cursors and triggers
TEXT BOOKS:
1. Database Management Systems, Raghurama Krishnan, Johannes Gehrke, Tata
Mc Graw Hill,3rd Edition
2. Database System Concepts, Silberschatz, Korth, McGraw Hill, V edition.
REFERENCE BOOKS:
1. Database Systems design, Implementation, and Management, Peter Rob &
Carlos Coronel 7thEdition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley
Student Edition.
:TASK 1 :
Q.Railway Reservation System -(Redesigning IRCTC database)
a: create a table containing the following data
Train (train Number, name, source, destination, start_time, reach_time, traveltime, distance,
class,days, type)
syntax:
create database dbmslab;
use dbmslab;
create table Train(trainno INT(6) PRIMARY KEY,name VARCHAR(20),source
VARCHAR(20),destination VARCHAR(20),start_time DATETIME,reach_time
DATETIME,traveltime TIME,distance FLOAT(6,2), class VARCHAR(10),days INT(2),type
VARCHAR(5));
Output:
Example for inserting the values into the table & how to show the data present in the table:
:TASK 2 :
Q.Write simple DDL/DML Queries to
1. Remove all the rows from Passenger table permanently.
syntax:
TRUNCATE TABLE passenger;
Output:
9. Change the super fast charge value in train fare as zero, if it is null.
Syntax:
Update train_ticket_fare set superfast_charge=0 where superfast_charge is NULL;
Output:
10. List the passenger names whose tickets are not confirmed.
Syntax:
Select name from passenger where reservation_status="pending";
Output:
13. Find the train names that are from Chennai to Mumbai, but do not have the sourceor
destination in itsname.
Syntax: select name from Train where SOURCE='CHENNAI' AND
DESTINATION='MUMBAI' AND NAME!='*CHENNAI*MUMBAI*' AND NAME!
='*MUMBAI*CHENNAI*';
14. Find the train details that are on Thursday(Use the ADT column created)
Synatx:
Select * from train where days='thursday';
Output:
:TASK 3:
Q.Create (Alter table to add constraint) the necessary foreign keys by identifying the
relationships in the table.
1) Add a suitable constraint to train table to always have train no in the range 10001 to
99999.
Syntax:
alter table Train ADD constraint trainno check(trainno BETWEEN 100001 AND 999999);
Output:
2) Add a suitable constraint for the column of station name, so that does not take
duplicates.
Syntax:
alter table Train_Route add constraint Train_Route_name_unique unique(name);
Output:
3) Change the data type of arrival time, depart time (date ->timestamp or timestamp to
date), and do the necessary process for updating the table with new values.
Syntax:
alter table Train drop column start_time;
alter table train drop column reach_time;
alter table Train add start_time timestamp(0);
alter table Train add reach_time timestamp(0);
update Train set start_time=timestamp('2022-08-15 18:40:00'),reach_time=timestamp('2022-08-
16 8:20:00') where trainno=123442;
update Train set start_time=timestamp('2022-08-11 18:40:00'),reach_time=timestamp('2022-08-
09 6:20:00') where trainno=123422;
update Train set start_time=timestamp('2022-08-16 18:50:00'),reach_time=timestamp('2022-08-
19 8:40:00') where trainno=123456;
Output:
4) Add a suitable constraint for the class column that it should take values only as 1A, 2A,
3A, SL, C.
Syntax:
alter table train add constraint chk_valCHECK(class in(‘1A’,‘2A’,‘3A’,‘SL’,‘C’));
Output:
5) Add a not null constraint for the column distance in train_route.
Syntax:
alter table Train_route change distance distance FLOAT NOT NULL;
Output:
:TASK 4:
Q.Use SQL PLUS functions to.
1. Find the passengers whose date of journey is one month from today.
Syntax:
select date_of_journey from ticket where date_of_journey>date_add(now(),interval 30 day);
Output:
Syntax:
Output:
Output:
Output:
13. Add the column halt time to train route.
Syntax:
alter table train_route add halt_time time;
Output:
Syntax:
update train_route set halt_time=depart_time-arrival_time;
15. Display the arrival time, depart time in the format HH:MI (24 hours and minutes).
Syntax:
output:
TASK-5
QueryingAggregateFunctions(COUNT,SUM,A
VG,MAXandMIN)
Aim:ToPracticeQueriesusingAggregatefunctionsforthefollowing
1. WriteaQuerytodisplaytheinformationpresentinthepassengeran
dcancellationtables
2. Displaythenumberofdaysinaweekon whichtheAP123busisavailable
3. FindnumberofticketsbookedforeachPNR_NousingGROUPBYCLAUSE
4. FindthedistinctPNRNumbersthatarepresent.
1. WriteaQuerytodisplaytheinformationpresentinthepassengerand cancellationtables
MYSQL>CREATETABLECANCELLATION2(PNRNOINTPRIMARYKEY,JOURNEYDAT
EDATETIME,NOOFSEATS INT,ADDRESS VARCHAR(20),CONTACTNO INT,STATUS
VARCHAR(10),FOREIGNKEY(PNRNO)REFERENCESRESERVATION2(PNRNO));
FROMRESERVATIONUNIONSELECT*
FROMCANCELLATION;
2. Displaythe MinimumageofthePassenger
MySQL>SELECTMIN(AGE)asMINAGE FROMPASSENGER;
3. FindnumberofticketsbookedforeachPNR_NousingGROUP BYCLAUSE
MySQL>SELECTPNRNO,SUM(No_of_SEATS)ASSUM_OF_SEATSFROMRE
SERVATION2 GROUPBY PNRNO;
MySQL>SELECTDISTINCTPNR_NOFROM RESERVATION2;
TASK–6
Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT, Constraints
etc.)Aim: PracticethefollowingQueries:
1. DisplayuniquePNR_NOofallpassengers
2. Displayallthenamesofmalepassengers.
3. Displaytheticketnumbersandnames of allthepassengers.
4. Findtheticketnumbersofthepassengerswhosenamestart with‘r’and endswith‘h’.
5. FindthenamesofPassengerswhoseageisbetween30and45.
6. Displayall the passengersnamesbeginningwith‘A’.
7. DisplaythesortedlistofPassengersnames
mysql>insertintopassenger2values(82302,'Smith',23,'M','Hyderabad');Query
values(82303,'Neha',23,'F','Hyderabad');QueryOK, 1rowaffected
(0.01sec)
mysql>insertintopassenger2values(82304,'Neha',35,'F','Hyderabad');Query
mysql>insertintopassenger2values(82306,'Ramu',40,'M','Hyderabad');Query
mysql>insertintopassenger2values(82308,'Aakash',40,'M','Hyderabad');Que
mysql>insertintopassenger2values(82402,'Aravind',42,'M','Hyderabad');Que
mysql>insertintopassenger2values(82403,'Avinash',42,'M','Hyderabad');Qu
mysql>insertintopassenger2values(82502,'Ramesh',23,'M','Hyderabad');Que
mysql>insertintopassenger2values(82602,'Rajesh',23,'M','Hyderabad');Quer
mysql>insertintoreservation2values(10201,'2012-02-
mysql>insertintoreservation2values(10202,'2012-02-
mysql>insertintoreservation2values(10204,'2013-03-
1. DisplayuniquePNR_NOofallreservationMysql>SelectDI
STINCTPNR_NO fromReservation;
PNR_No
10201
10202
10203
10204
2. Displayallthe namesofmalepassengers.
mysql>Selectp.namefrompassenger2p
where
p.passportidIN(selectp2.passportidfrompassenger2p2where
p2.sex='M');
3. Displaytheticketnumbersandnamesofallthepassengers.
mysql>selectt.ticketno,p.namefrompassengertickett,passenger2pwheret.passportid=p.passportid;
4. Findtheticketnumbersofthe passengerswhosenamestartwith‘r’andendswith‘h’.
MySQL>SELECTNameFROMPassengerWHEREnameLIKE‘R%H’
Name
Rajesh
Ramesh
Ramesh
5. Findthe namesofPassengerswhoseageisbetween30 and45.
MySQL>SELECTNameFROMPASSENGERWHEREAGEBETWEEN30AND45
6. Displayallthepassengersnamesbeginningwith‘A’.
MySQL>SELECT*FROMPASSENGERWHERENAME LIKE‘A%’;
Name
Akash
Arivind
Avinash
7. DisplaythesortedlistofPassengersnames
MySQL>SELECTNAMEFROMPASSENGERORDERBYNAME;
TASK 7:
Create a table EMP with the following structure.
Queries:
1. Display all the employees and the departments implementing a left outer join.
2. Display the employee name and department name in which they are working implementing a full outer join.
// MySQL does not support full outer join out of the box, unlike other databases.
5. Write a query to display information about employees who earn more than any employee in dept 30.
Query:
6. Write a query to create and drop View
To create a view:
To drop a view:
TASK 8:
Queries:
DELIMITER //
CREATE PROCEDURE fact(IN x INT)
BEGIN
DECLARE result INT;
DECLARE i INT;
ET result = 1;
SET i = 1;
WHILE i <= x DO
SET result = result * i;
SET i = i + 1;
END WHILE;
SELECT x AS Number, result as Factorial;
END //
Output:
2. Print the Fibonacci series.
Queries:
DELIMITER //
CREATE PROCEDURE nonrec_fib(n INT,OUT out_fib INT)
BEGIN
DECLARE m INT default 0;
DECLARE k INT DEFAULT 1;
DECLARE i INT;
DECLARE tmp INT;
SET m=0;
SET k=1;
SET i=1;
WHILE (i<=n) DO
SET tmp=m+k;
SET m=k;
SET k=tmp;
SET i=i+1;
END WHILE;
SET out_fib=m;
END //
OUTPUT:
TASK 9:
9. Write a cursor for the following: Declare a cursor that defines a result set. Open the
cursor to establish the result set. Fetch the data into local variables as needed from the
cursor, one row at a time. Close the cursor when done.
Example 1:
Queries:
CREATE TABLE Sailors( sid INT, sname VARCHAR(20), rating INT, age FLOAT,
PRIMARY KEY(sid) );
INSERT INTO Sailors VALUES(22,'Dustin',7,45);
INSERT INTO Sailors VALUES(29,'Brutus',1,33);
INSERT INTO Sailors VALUES(31,'Lubber',8,56);
INSERT INTO Sailors VALUES(32,'Andy',8,26);
INSERT INTO Sailors VALUES(58,'Rusty',10,35);
INSERT INTO Sailors VALUES(74,'Horatio',9,35);
INSERT INTO Sailors VALUES(64,'Horatio',7,35);
INSERT INTO Sailors VALUES(95,'Bob',3,64);
INSERT INTO Sailors VALUES(85,'Art',3,26);
INSERT INTO Sailors VALUES(71,'Zorba',10,16);
DELIMITER //
create procedure mycur1(sa_id int)
begin
declare v_sname varchar(30);
declare v_rating int;
declare v_age int;
declare c1 cursor for select sname, rating, age from sailors where sid = sa_id;
open c1;
fetch c1 into v_sname,v_rating,v_age;
select v_sname,v_rating,v_age;
close c1;
end //
OUTPUT:
Example 2
Queries:
DELIMITER //
create procedure mycur2(sa_rating int)
begin
declare v_sname varchar(30);
declare v_sid int;
declare v_age int;
declare c1 cursor for select sid,sname,age from sailors where rating=sa_rating;
open c1;
fetch c1 into v_sid,v_sname,v_age;
select v_sid,v_sname,v_age;
close c1;
end //
OUTPUT:
Example 3
Queries:
DELIMITER //
create procedure mycur3(sa_rating int)
begin
declare finished int default 0;
declare count int default 0;
declare v_sname varchar(30);
declare v_sid int;
declare v_age int;
declare c1 cursor for select sid,sname,age from sailors where rating=sa_rating;
declare continue handler for not found set finished=1;
open c1; getcur : loop fetch c1 into v_sid,v_sname,v_age;
if finished=1 then leave getcur; end if;
set count =count + 1;
select v_sid,v_sname,v_age;
end loop;
close c1;
select count;
end //
OUTPUT:
TASK 10:
10. Write a PL/SQL procedure to: Creation of stored procedure, Execution of procedure
and modification of procedure.
Queries:
CREATE TABLE Sailors( sid INT, sname VARCHAR(20), rating INT, age FLOAT,
PRIMARY KEY(sid) );
INSERT INTO Sailors VALUES(22,'Dustin',7,45);
INSERT INTO Sailors VALUES(29,'Brutus',1,33);
INSERT INTO Sailors VALUES(31,'Lubber',8,56);
INSERT INTO Sailors VALUES(32,'Andy',8,26);
INSERT INTO Sailors VALUES(58,'Rusty',10,35);
INSERT INTO Sailors VALUES(74,'Horatio',9,35);
INSERT INTO Sailors VALUES(64,'Horatio',7,35);
INSERT INTO Sailors VALUES(95,'Bob',3,64);
INSERT INTO Sailors VALUES(85,'Art',3,26);
INSERT INTO Sailors VALUES(71,'Zorba',10,16);
DELIMITER //
create procedure p1(p_age int)
begin
SELECT S.rating, S.age
FROM Sailors S
WHERE S.age >= p_age;
End
call p1(30) //
OUTPUT:
TASK 11:
Update Trigger:
Queries:
CREATE TABLE Boats( bid INT, bname VARCHAR(10), color VARCHAR(10), PRIMARY
KEY(bid));
DESC Boats;
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');
DELIMITER //
create trigger t1 before update on boats
for each row
begin
if new.color='red' then
set new.color=old.color;
else
set new.color=new.color;
end if;
end//
OUTPUT:
Insert Trigger:
Queries:
CREATE TABLE Sailors( sid INT, sname VARCHAR(20), rating INT, age FLOAT,
PRIMARY KEY(sid) );
INSERT INTO Sailors VALUES(22,'Dustin',7,45);
INSERT INTO Sailors VALUES(29,'Brutus',1,33);
INSERT INTO Sailors VALUES(31,'Lubber',8,56);
INSERT INTO Sailors VALUES(32,'Andy',8,26);
INSERT INTO Sailors VALUES(58,'Rusty',10,35);
INSERT INTO Sailors VALUES(74,'Horatio',9,35);
INSERT INTO Sailors VALUES(64,'Horatio',7,35);
INSERT INTO Sailors VALUES(95,'Bob',3,64);
INSERT INTO Sailors VALUES(85,'Art',3,26);
INSERT INTO Sailors VALUES(71,'Zorba',10,16);
DELIMITER //
create trigger t2
before insert on sailors
for each row
begin
if new.age>40 then
set new.rating='10';
else
set new.rating=new.rating;
end if;
end //
OUTPUT:
Delete Trigger:
Queries:
CREATE TABLE Reserves( sid INT, bid INT, day DATE NOT NULL, PRIMARY
KEY(sid,bid), FOREIGN KEY(sid) REFERENCES Sailors(sid) ON DELETE CASCADE,
FOREIGN KEY(bid) REFERENCES Boats(bid) ON DELETE CASCADE);
DESC Reserves;
INSERT INTO Reserves VALUES(22,101,'2012/10/10');
INSERT INTO Reserves VALUES(22,102,'2012/10/9');
INSERT INTO Reserves VALUES(22,103,'2012/08/10');
INSERT INTO Reserves VALUES(22,104,'2012/07/10');
INSERT INTO Reserves VALUES(31,102,'2012/11/10');
INSERT INTO Reserves VALUES(31,103,'2012/06/11');
INSERT INTO Reserves VALUES(31,104,'2012/12/11');
INSERT INTO Reserves VALUES(64,101,'2012/05/09');
INSERT INTO Reserves VALUES(64,102,'2012/08/09');
INSERT INTO Reserves VALUES(74,103,'2012/08/09');
DELIMITER //
create trigger t3 before delete on reserves
for each row
begin
insert into cancel values(old.sid, old.bid, old.day);
end //
OUTPUT:
TASK 12:
Queries:
CREATE TABLE Sailors( sid INT, sname VARCHAR(20), rating INT, age FLOAT,
PRIMARY KEY(sid) );
INSERT INTO Sailors VALUES(22,'Dustin',7,45);
INSERT INTO Sailors VALUES(29,'Brutus',1,33);
INSERT INTO Sailors VALUES(31,'Lubber',8,56);
INSERT INTO Sailors VALUES(32,'Andy',8,26);
INSERT INTO Sailors VALUES(58,'Rusty',10,35);
INSERT INTO Sailors VALUES(74,'Horatio',9,35);
INSERT INTO Sailors VALUES(64,'Horatio',7,35);
INSERT INTO Sailors VALUES(95,'Bob',3,64);
INSERT INTO Sailors VALUES(85,'Art',3,26);
INSERT INTO Sailors VALUES(71,'Zorba',10,16);
SELECT *FROM sailors;
START TRANSACTION;
COMMIT;
SET autocommit = 0;
SAVEPOINT Insertion;
UPDATE sailors SET rating= 10 WHERE age = 35;
SAVEPOINT Updation;
ROLLBACK TO Insertion;
SELECT *FROM sailors;
OUTPUT: