DBMS Lab programs 4th sem
DBMS Lab programs 4th sem
Dept Of CSE
–
II B. TECH IV SEMESTER
CSE
CMR College Of Engineering & Technology
Dept Of CSE
CO-REQUISITES:
“Database Management System”
COURSE OBJECTIVES:
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 trig
CSE
CMR College Of Engineering & Technology
Dept Of CSE
List of Experiments:
1. Concept design with E-R Model
Draw an ER diagram for the following
a. There are two entity sets Employee and Department. These entity sets are
participating in a relationship works in. The relationship set is converted into
relation with attributes EmpNo from Employee relation, D_id from Department
relation and Since, the attribute of the relationship set itself.
2. Relational Model
a. Convert the above ER diagram into Relational Model
3. Normalization
DDLcommands
5.Practicing
DMLcommands
1.a. Create a user and grant all permissions to the user.
b. Insert the any three records in the employee table and use rollback. Check the result.
c. Add primary key constraint and not null constraint to the employee table.
d. d.Insert null values to the employee table and verify the result.
2.a. Create a user and grant all permissions to the user.
b. Insert values in the department table and use commit.
c. Add constraints like unique and not null to the department table.
d. Insert repeated values and null values into the table.
3.a. Create a user and grant all permissions to the user.
b. Insert values into the table and use commit.
c. Delete any three records in the department table and use rollback.
d. Add constraint primary key and foreign key to the table
4.a. Create a user and grant all permissions to the user.
b. Insert records in the sailor table and use commit.
c. Add save point after insertion of records and verify save point.
d. Add constraints not null and primary key to the sailor table.
5.a. Create a user and grant all permissions to
the user.
b. Use revoke command to remove user
permissions.
c. Change password of the user created.
d. Add constraint foreign key and not null.
CSE
CMR College Of Engineering & Technology
Dept Of CSE
c. Add constraint primary key , foreign key and not null to the reserves table
d. Delete constraint not null to the table column
6.A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
6.B. Nested, Correlated subqueries
A. Find the Sid’s of sailors who have reserved a red or a green boat.
B. Find the names of sailors who have reserved a red and a green boat.
C. Find the names of sailors who have reserved a red but not green boats.
D. Find all sids of sailors who have a rating of 10 or reserved boat 104.
E. Find the names of sailors who have reserved boat 103 using independent nested
query.
F. Find the names of sailors who have reserved a red boat.
G. Find the names of sailors who have not reserved a red boat.
1. Find the names of sailors who have reserved boat number 103 using correlated
nestedquery.
H. Find sailors whose rating is better than some sailor called ‘Horatio’.
I. Find the sailors with the highest rating.
1. Find the names of sailors who have reserved both a red and a green boat using
nestedqueries.
J. Find the names of sailors who have reserved all boats.
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and
dropping of Views.
a. who is the youngest sailor
b. Find the name of the sailor who have maximum rating
c. What is the average rating of all Sailors
d. how many sailors are there with the rating above 7
e. The following SQL lists the number of customers in each country, sorted high to low
f. The following SQL lists the number of customers in each country, sorted high to low
(Only include countries with more than 5 customers):
2. Creation of insert trigger, delete trigger, update trigger practice triggers using the
passenger database. Passenger (Passport_ id INTEGER PRIMARY KEY, Name
CSE
CMR College Of Engineering & Technology
Dept Of CSE
VARCHAR (50) Not NULL, Age Integer Not NULL, Sex Char, Address
VARCHAR (50) Not NULL);
a. Write a Insert Trigger to check the Passport_id is exactly six digits or not.
b. Write a trigger on passenger to display messages ‘1 Record is inserted’, ‘1 record
is deleted’, ‘1 record is updated’ when insertion, deletion and updation are done on
passenger respectively.
10.Usage of Cursors
a. Display the employee names and their salary for the accepted department number.
b. Display the top N earners for an accepted department number.
c. To write a Cursor to display the list of employees who are working as a Managers or
Analyst.
d. write a Cursor to find employee with given job and deptno.
e. Write a PL/SQL block using implicit cursor that will display message, the salaries
of all the employees in the ‘employee’ table are updated. If none of the employee’s
salary are updated we get a message 'None of the salaries were updated'. Else we
get a message like for example, 'Salaries for 1000 employees are updated' if there
are 1000 rows in ‘employee’table.
11.Packages
a. creates HR package which contains Hire and Fire functions.
Hire function adds the details of employee and Fire function deletes the details of Employee.
CSE
CMR College Of Engineering & Technology
Dept Of CSE
a. There are two entity sets Employee and Department. These entity sets are participating in a
relationship works in. The relationship set is converted into relation with attributes
EmpNo from Employee relation, D_id from Department relation and Since, the attribute of the
relationship set itself.
2.Relational Model
a. Convert the above ER diagram into Relational Model.
2.Relational Model
+------------+ +--------------+
| Employee | | Department |
+------------+ +--------------+
| EmpNo | | D_id |
| Name | | Name |
| ... | | ... |
+------------+ +--------------+
| |
| works in |
|---------------------|
| Since |
|---------------------|
|
+------------+
| Works_in |
+------------+
| EmpNo (FK) |
| D_id (FK) |
| Since |
CMR College Of Engineering & Technology
Dept Of CSE
To convert the Entity-Relationship (ER) diagram into a relational model, we need to
translate each entity set and relationship set into a table, considering the attributes and
relationships involved. Here's how we can do it:
Employee Table:
Attributes: EmpNo (Primary Key), Name, and any other relevant attributes.
Department Table:
Attributes: D_id (Primary Key), Name, and any other relevant attributes.
Department(D_id PRIMARY KEY, Name, ...)
Works_in Table: Attributes: EmpNo (Foreign Key referencing Employee), D_id (Foreign
Key referencing Department), Since
3. Normalization
c) Normalize the given Relation. Consider the given schema is in first normal form and
Schema(Student id ,Student name, Project Id, Project name, City, country, ZIP)
Primarykey(Student id,Project id)
Fd’s: Project Id- Project
name country-ZIP,ZIP
1. First Normal Form (1NF): Ensure that each attribute contains atomic values, meaning no
multi-valued attributes or repeating groups. The given table seems to be in 1NF already, as
there are no multi-valued attributes.
2. Second Normal Form (2NF): Make sure that every non-prime attribute is fully functionally
dependent on the primary key.
The primary key seems to be (Eid, ProjId). Let's create two relations:
Relation 1: (Eid, E.Name, Ph.no, EmpCity, City Zip) Relation 2: (ProjId, ProjName, ProjLeader)
3. Third Normal Form (3NF): Ensure that there are no transitive dependencies.
Relation 1: (Eid, E.Name, Ph.no, EmpCity, City Zip) Relation 2: (ProjId, ProjName, ProjLeader)
These relations are now in 2NF and 3NF, respectively, and they are normalized.
b. To normalize the given table to Boyce-Codd Normal Form (BCNF), we need to start by identifying
the candidate keys and then decompose the relation to eliminate any dependencies that violate BCNF.
1. Identify Candidate Keys: We have the following candidate keys based on the given
functional dependencies:
{Eid, ProjId}
{EmpCity}
2. Decompose into BCNF: We need to check if there are any dependencies where the
determinant is not a superkey.
a. Eid -> EName, Ph.no, EmpCity, CityZip
This dependency is fine as Eid is a part of the candidate key.
b. ProjId -> ProjName, ProjLeader
This dependency is also fine as ProjId is a part of the candidate key.
c. EmpId, ProjId -> ProjLeader
Since {EmpId, ProjId} is a candidate key, this dependency is also fine.
d. EmpCity -> CityZip
This dependency is problematic. EmpCity is not a superkey, and CityZip is not a subset
of any candidate key. So, we need to decompose this dependency.
e. ProjId -> ProjLeader
This dependency is already fine.
3. Decompose Dependency (d): We decompose the relation using the problematic dependency
EmpCity -> CityZip.
New Relation 1: (EmpCity, CityZip)
Original Relation: (Eid, EName, Ph.no, EmpCity, CityZip, ProjId, ProjName, ProjLeader, EmpId)
4. Final Relations: We have two relations now:
Relation 1: (EmpCity, CityZip)
Relation 2: (Eid, EName, Ph.no, EmpCity, ProjId, ProjName, ProjLeader, EmpId)
Both relations are in BCNF, as each determinant is a superkey.
So, after normalization, we have decomposed the original relation into two relations, ensuring that
each relation satisfies BCNF.
4.Practicing DDL commands
a.Create a table called Employee with the following structure.
Name Type
Empno int
Ename Varchar2(10)
Job Varchar2(10)
Mgr int
Sal int
b.Add a column commission with domain to the Employee table with Alter command.
c. Truncate the rows from Employee table
CMR College Of Engineering & Technology
Dept Of CSE
d. Drop table;.
SOLUTION:
SQL> create table employee(empno int,ename varchar2(10),job
varchar2(10),mgr int,sal int);
Table created.
SQL> desc employee;
Name Null? Type
EMPNO
Integer
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR Integer
SAL Integer
Name Type
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
CMR College Of Engineering & Technology
Dept Of CSE
COMMISSION NUMBER
Syntax:
DROP TABLE table_name;
TRUNCATE:
Syntax: TRUNCATE TABLE table_name;
CMR College Of Engineering & Technology
Dept Of CSE
b. Insert the any three records in the employee table and use rollback. Check the
result.
1. A table named employee with appropriate columns (e.g., id, name, department, etc.) is created by using
following syntax
START TRANSACTION;
ROLLBACK;
SQL
SELECT * FROM employee;
This query should now show an empty table, as the rollback has undone the previous inserts.
c. Add primary key constraint and not null constraint to the employee table.
d. Insert null values to the employee table and verify the result.
c. Add constraints like unique and not null to the department table.
-- Add unique constraint to the 'name' column
ALTER TABLE department
ADD CONSTRAINT unique_department_name UNIQUE (name);
c. Delete any three records in the department table and use rollback.
-- Begin transaction
START TRANSACTION;
c. Add save point after insertion of records and verify save point.
-- Begin transaction
START TRANSACTION;
-- Add a savepoint
SAVEPOINT after_insertion;
d. Add constraints not null and primary key to the sailor table.
CMR College Of Engineering & Technology
Dept Of CSE
ALTER TABLE SAILORS
MODIFY SID INT PRIMARY KEY,
MODIFY SNAME VARCHAR(20) NOT NULL,
MODIFY AGE INT NOT NULL,
MODIFY RATING INT NOT NULL;
-- Add a savepoint
SAVEPOINT update_savepoint;
c. Add constraint primary key , foreign key and not null to the reserves table
-- Add primary key constraint to the (SID, BID) combination
ALTER TABLE RESERVES
ADD CONSTRAINT pk_reserves PRIMARY KEY (SID, BID);
-- Add foreign key constraint to the 'SID' column referencing the 'SID' column in
the 'SAILORS' table
ALTER TABLE RESERVES
ADD CONSTRAINT fk_reserves_sid FOREIGN KEY (SID) REFERENCES SAILORS(SID);
-- Add foreign key constraint to the 'BID' column referencing the 'BID' column in
the 'BOATS' table
ALTER TABLE RESERVES
ADD CONSTRAINT fk_reserves_bid FOREIGN KEY (BID) REFERENCES BOATS(BID);
Sailors Data:
INSERT INTO SAILORS VALUES (22,'Dustin',7,45);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (29,'Brutus',1,33);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (31,'Lubber',8,55.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (32,'Andy',8,25.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (58,'Rusty',10,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (64,'Horatio',7,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (71,'Zorba',10,16);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (74,'Horatio',9,35);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (85,'Art',3,25.5);
1 row(s) inserted.
INSERT INTO SAILORS VALUES (95,'Bob',3,63.5);
1 row(s) inserted.
Boats Data:
CMR College Of Engineering & Technology
Dept Of CSE
Insert into Boats values (101,'Interlake','blue');
1 row(s) inserted.
Insert into Boats values (102,'Interlake','red');
1 row(s) inserted.
Insert into Boats values (103,'Clipper','green');
1 row(s) inserted.
Insert into Boats values (104,'Marine','red');
1 row(s) inserted.
Reserves Data:
insert into Reserves values(22,101,'1998-10-10');
1 row(s) inserted.
insert into Reserves values(22,102,'1998-10-10');
1 row(s) inserted.
insert into Reserves values(22,103,'1998-08-10');
1 row(s) inserted.
insert into Reserves values(22,104,'1998-07-10');
1 row(s) inserted.
insert into Reserves values(31,102,'1998-11-10');
1 row(s) inserted.
insert into Reserves values(31,103,'1998-11-10');
1 row(s) inserted.
insert into Reserves values(31,104,'1998-12-11');
1 row(s) inserted.
insert into Reserves values(64,101,'1998-05-09');
1 row(s) inserted.
insert into Reserves values(64,102,'1998-08-09');
1 row(s) inserted.
SELECT * FROM SAILORS;
SELECT * FROM BOATS;
SELECT * FROM RESERVES;
Output:
A. Find the Sid’s of sailors who have reserved a red or a green boat.
SELECT DISTINCT s.SID
FROM Sailors s
JOIN Reserves r ON s.SID = r.SID
JOIN Boats b ON r.BID = b.BID
WHERE b.Color = 'red' OR b.Color = 'green';
CMR College Of Engineering & Technology
Dept Of CSE
B. Find the names of sailors who have reserved a red and a green boat.
SELECT s.SNAME
FROM SAILORS s,reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
b.bcolor=’red’INTERSECT select s1.sname from sailors s1,reserves r1,boats b1 where
s1.sid=r1.sid and r1.bid=b1.bid and b1.bcolor=’green’);
C. Find the names of sailors who have reserved a red but not green boats.
SELECT s.SNAME
FROM sailor s reserves r,boats b where s.sid=r.sid and r.bid=b.bid and
b.bcolor=’red’
EXCEPT
select s1.sname from sailor s1,reserves r1,boats b1 where s1.sid=r1.sid and
r1.bid=b1.bid and b1.bcolor=’green’);
D. Find all sids of sailors who have a rating of 10 or reserved boat 104.
-- Find sailors with rating 10
SELECT SID
FROM SAILORS
WHERE RATING = 10
UNION
E. Find the names of sailors who have reserved boat 103 using independent nested
query.
SELECT SNAME
FROM SAILORS
WHERE SID IN (
SELECT SID
FROM RESERVES
WHERE BID = 103
);
G. Find the names of sailors who have not reserved a red boat.
Select s.sname from sailors s where s.sid NOT IN(select r.sid from reserves r
where r.bid NOT IN(select b.bid from boats b where b.bcolor=’red’));
H. Find the names of sailors who have reserved boat number 103 using
correlat2 ed nested query.
SELECT SNAME
FROM SAILORS s
WHERE EXISTS (
SELECT *
FROM RESERVES r
WHERE r.bid=103 and r.sid=s.sid);
CMR College Of Engineering & Technology
Dept Of CSE
I. Find sailors whose rating is better than some sailor called ‘Horatio’.
Select * from sailors s where s.rating > any(select s1.rating from sailor s1 where
s1.name=’Horatio’);
j. Find the names of sailors who have reserved both a red and a green boat
using nested queries.
SELECT SNAME
FROM SAILORS
WHERE SID IN (
SELECT R1.SID
FROM RESERVES R1
INNER JOIN BOATS B1 ON R1.BID = B1.BID
WHERE B1.BCOLOR = 'red'
) AND SID IN (
SELECT R2.SID
FROM RESERVES R2
INNER JOIN BOATS B2 ON R2.BID = B2.BID
WHERE B2.BCOLOR = 'green'
);
CMR College Of Engineering & Technology
Dept Of CSE
e. The following SQL lists the number of customers in each country, sorted
high to low
mysql> create table customer1(customer_id int,customer_name
varchar(10),contact int,age int,city varchar(10),country varchar(10));
Query OK, 0 rows affected (0.03 sec)
f. The following SQL lists the number of customers in each country, sorted
high to low (Only include countries with more than 5 customers):
create or replace view country_view AS select country,count(*) as
number_of_customers from customer1 group by country having count(*)>5 order by
number_of_customers DESC;
Query OK, 0 rows affected (0.01 sec)
//emp procedure
CREATE TABLE emp (Eid INT PRIMARY KEY, Sal INT);
DROP TABLE emp;
DECLARE
sl INT;
id INT;
BEGIN
id := :id;
esal(id, sl);
END
CMR College Of Engineering & Technology
Dept Of CSE
//greeting procedure
CREATE OR REPLACE PROCEDURE greeting AS
BEGIN
dbms_output.put_line('hello');
END
BEGIN
greeting;
END
//department procedure
CREATE TABLE dept (Did INT PRIMARY KEY, Dname VARCHAR(10));
DROP TABLE dept;
INSERT INTO dept VALUES(101, 'IT');
INSERT INTO dept VALUES(102, 'HR');
INSERT INTO dept VALUES(103, 'Finance');
DECLARE
id INT;
name VARCHAR(10);
BEGIN
id := :id;
depname(id, name);
END;
//isPrimeNumber Procedure
CREATE OR REPLACE PROCEDURE isprime
(A IN INT) IS
FLAG INT := 0;
BEGIN
FOR COUNTER IN 2..A-1 LOOP
IF A MOD COUNTER = 0 THEN dbms_output.put_line('Not Prime'); FLAG:=1; EXIT;
END IF;
END LOOP;
IF FLAG = 0 THEN
dbms_output.put_line('Prime');
END IF;
END isprime;
CMR College Of Engineering & Technology
Dept Of CSE
DECLARE
A INT;
BEGIN
A:= :A;
isprime(A);
END;
DECLARE
A DATE;
day VARCHAR(10);
BEGIN
A:= :A;
day := weekday(A);
dbms_output.put_line('Weekday: '||day);
END;
DECLARE
L INT;
H INT;
cnt INT;
BEGIN
L := :L;
H := :H;
cnt:= sailcount(L,H);
dbms_output.put_line(cnt);
END;
CMR College Of Engineering & Technology
Dept Of CSE
//FUNCTION to return avg age of sailors in a given rating level
CREATE OR REPLACE FUNCTION avgage
(low IN Sailors.Rating%TYPE, high IN Sailors.Rating%TYPE)
RETURN INT IS
cnt INT;
BEGIN
SELECT AVG(Age) INTO cnt FROM Sailors WHERE Rating BETWEEN low AND high;
RETURN cnt;
END avgage;
DECLARE
L INT;
H INT;
cnt INT;
BEGIN
L := :L;
H := :H;
cnt:= avgage(L,H);
dbms_output.put_line(cnt);
END;
Solution
declare
cursor c1 is select * from emp where deptno= :D_NO;
rec emp%rowtype;
begin
open c1;
loop
fetch c1 into rec;
exit when c1%notfound;
dbms_output.put_line('Dept No= '||rec.deptno||' Emp name= '||rec.ename||' Salary='||rec.sal);
end loop;
close c1;
end;
CURSOR top_earners_cursor IS
select * from (select * from emp where deptno=dnum order by sal desc) where rownum<=n;
-- Variables to store employee details fetched by the cursor
CMR College Of Engineering & Technology
Dept Of CSE
name emp.ename%TYPE;
salary emp.sal%TYPE;
BEGIN
-- Open the cursor
OPEN top_earners_cursor;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employees found for the given department.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;
Q3 To write a Cursor to display the list of employees who are working as a Managers or Analyst.
Solution
declare
cursor c4 is select * from emp where job in('MANAGER','ANALYST');
rec emp%rowtype;
begin
open c4;
dbms_output.put_line('....LIST OF EMPLOYEES WHO ARE MANAGERS OR ANALYSTS');
loop
fetch c4 into rec;
exit when c4%notfound;
dbms_output.put_line( 'Emp name= '||rec.ename||' JOB='||rec.job);
end loop;
close c4;
end;
Q4. write a Cursor to find employee with given job and deptno.
solution
declare
CMR College Of Engineering & Technology
Dept Of CSE
dno number(10):= :Dept_No;
j varchar2(32):= :JOB;
cursor c5 is select * from emp where job=j and deptno=dno;
rec emp%rowtype;
begin
open c5;
dbms_output.put_line('....LIST OF EMPLOYEES ----');
loop
fetch c5 into rec;
exit when c5%notfound;
dbms_output.put_line( 'Emp name='||rec.ename||' JOB=' ||rec.job || ' Dept No= '||rec.deptno);
end loop;
close c5;
end;
Q5.Write a PL/SQL block using implicit cursor that will display message, the salaries of all the employees in the employee
table are updated
solution
DECLARE
cnt NUMBER(10) := 0;
BEGIN
UPDATE emp SET sal = sal* 1.1;
cnt:= SQL%ROWCOUNT;
IF cnt = 0 THEN
DBMS_OUTPUT.PUT_LINE('None of the salaries were updated.');
ELSE
DBMS_OUTPUT.PUT_LINE('Salaries for ' || cnt || ' employees are updated.');
END IF;
end;
11.Packages
Step 1:
create table cmrcet_emp(eid number(10) primary key,ename varchar2(32), dept varchar2(32));
Step 2:
CREATE OR REPLACE PACKAGE hr_package AS
PROCEDURE hire(emp_id NUMBER, emp_name VARCHAR2, emp_department VARCHAR2);
PROCEDURE fire(emp_id NUMBER);
END hr_package;
Step 3:
CMR College Of Engineering & Technology
Dept Of CSE
CREATE OR REPLACE PACKAGE BODY hr_package AS
PROCEDURE hire(emp_id NUMBER, emp_name VARCHAR2, emp_department VARCHAR2) IS
BEGIN
-- Insert employee data into the employees table
INSERT INTO cmrcet_emp VALUES (emp_id, emp_name, emp_department);
END hr_package;
Step 4:
begin
hr_package.hire(1,'vivekanand','CSE');
hr_package.fire(1);
end;
CMR College Of Engineering & Technology
Dept Of CSE