24BCA31P Database Management Systems Lab
List of Practicals:
1. Draw an ER Diagram of Registrar Office
2. Draw an ER Diagram of Hospital Management System
3. Reduce The ER diagram in question no 1 into tables
Column Name Data Type Description
Student_ID INT (PK) Unique ID of student
Name VARCHAR Student name
Major VARCHAR Student’s major
Column Name Data Type Description
Course_ID INT (PK) Unique course ID
Title VARCHAR Course title
Column Name Data Type Description
Section_ID INT (PK) Unique section ID
Semester VARCHAR Semester (e.g., Fall)
Year INT Year (e.g., 2025)
Column Name Data Type Description
Instructor_ID INT (PK) Unique instructor ID
Name VARCHAR Instructor’s name
Column Name Data Type Description
Student_ID INT (PK)(FK) Refers to STUDENT(Student_ID)
Section_ID INT (PK)(FK) Refers to SECTION(Section_ID)
Column Name Data Type Description
Instructor_ID INT (PK)(FK) Refers to INSTRUCTOR(Instructor_ID)
Section_ID INT (PK)(FK) Refers to SECTION(Section_ID)
4. Reduce the ER diagram of question no 2 into tables
Field Data Type Description
DoctorID (PK) INT Unique identifier
Name VARCHAR Doctor's name
Address VARCHAR Doctor's address
Specialization VARCHAR Area of specialization
Qualification VARCHAR Doctor's qualification
Field Data Type Description
PatientID (PK) INT Unique identifier
Name VARCHAR Patient's name
Type VARCHAR In-patient / Out-patient
Date DATE Registration date
Details VARCHAR Additional info
Field Data Type Description
DoctorID (FK) INT References DOCTORS
PatientID (FK) INT References PATIENTS
Disease VARCHAR Disease being treated
Treatment VARCHAR Treatment given
PRIMARY KEY (DoctorID, PatientID) Composite Key
Field Data Type Description
TestID (PK) INT Unique identifier
Type VARCHAR Type of test
Description VARCHAR Description of the test
Field Data Type Description
PatientID (FK) INT References PATIENTS
TestID (FK) INT References TESTS
Date DATE Date the test was conducted
Report TEXT Test report
PRIMARY KEY (PatientID, TestID, Date) Composite Key
Consider the following Schema
Supplier(SID, Sname, branch, city, phone)
Part(PID, Pname, color, price)
Supplies(SID, PID, qty, date_supplied)
5. DDL Commands
Create the above tables
CREATE TABLE Supplier (
SID INT PRIMARY KEY,
Sname VARCHAR(50),
branch VARCHAR(50),
city VARCHAR(50),
phone VARCHAR(15)
);
CREATE TABLE Part (
PID INT PRIMARY KEY,
Pname VARCHAR(50),
color VARCHAR(20),
price DECIMAL(10, 2)
);
CREATE TABLE Supplies (
SID INT,
PID INT,
qty INT,
date_supplied DATE,
PRIMARY KEY (SID, PID, date_supplied),
FOREIGN KEY (SID) REFERENCES Supplier(SID),
FOREIGN KEY (PID) REFERENCES Part(PID)
);
Add a new attribute state in supplier table
ALTER TABLE Supplier
ADD state VARCHAR(50);
Remove attribute city from supplier table
ALTER TABLE Supplier
DROP COLUMN city;
Modify the data type of phone attribute
ALTER TABLE Supplier
MODIFY phone VARCHAR(20);
Change the name of attribute city to address
ALTER TABLE Supplier
RENAME COLUMN city TO address;
Change a table’s name, supplier to sup
RENAME Supplier TO Sup;
Use truncate to delete the contents of supplies table
TRUNCATE TABLE Supplies;
Remove the part table from database
DROP TABLE Part;
6. DML Commands
Insert at least 10 records in tables supplier, part and supplies
-- Supplier Table
INSERT INTO Supplier VALUES (204001, 'Ravi', 'North', 'Delhi',
'9876543210');
INSERT INTO Supplier VALUES (204002, 'Rakesh', 'South',
'Agra', '9812345678');
INSERT INTO Supplier VALUES (204003, 'Vandana', 'East',
'Delhi', '9823456789');
INSERT INTO Supplier VALUES (204004, 'Balkrishna', 'West',
'Mumbai', '9834567890');
INSERT INTO Supplier VALUES (204005, 'Arya', 'North',
'Chennai', '9845678901');
-- Part Table
INSERT INTO Part VALUES (301, 'Bolt', 'Silver', 10.50);
INSERT INTO Part VALUES (302, 'Nut', 'Black', 5.25);
INSERT INTO Part VALUES (303, 'Screw', 'Gold', 2.75);
INSERT INTO Part VALUES (304, 'Washer', 'Grey', 1.50);
INSERT INTO Part VALUES (305, 'Clamp', 'Blue', 6.00);
-- Supplies Table
INSERT INTO Supplies VALUES (204001, 301, 100, '01 JUNE
2024');
INSERT INTO Supplies VALUES(204002, 302, 200, '02 JUNE
2024');
INSERT INTO Supplies VALUES(204003, 303, 150, '03 JUNE
2024');
INSERT INTO Supplies VALUES(204004, 304, 120, '04 JUNE
2024');
INSERT INTO Supplies VALUES(204005, 305, 300, '05 JUNE
2024');
• Show the contents in tables supplier, part and supplies
SELECT * FROM Supplier;
SELECT * FROM Part;
SELECT * FROM Supplies;
• Find the name and city of all suppliers
SELECT Sname, city FROM Supplier;
• Find the name and phoneno of all suppliers who stay in ‘Delhi’
SELECT Sname, phone FROM Supplier WHERE city = 'Delhi';
• Find all distinct branches of suppliers
SELECT DISTINCT branch FROM Supplier;
• Delete the record of the supplier whose SID is 204001
DELETE FROM Supplier WHERE SID = 204001;
• Delete all records of suppliers whose city starts with capital A.
DELETE FROM Supplier WHERE city LIKE 'A%';
• Find the supplier names which have ‘lk’ in any position
SELECT Sname FROM Supplier WHERE Sname LIKE '%lk%';
• Find the supplier name where ‘R’ is in the second position
SELECT Sname FROM Supplier WHERE Upper(Sname) LIKE
'_R%';
• Find the name of supplier whose name starts with ‘V’ and ends
with ‘A’
SELECT Sname FROM Supplier WHERE Sname LIKE 'V%A';
• Change the city of supplier ‘Vandana’ to ‘Goa’
UPDATE Supplier SET city = 'Goa' WHERE Sname = 'Vandana';
• Change the city of all suppliers to ‘BOMBAY’
UPDATE Supplier SET city = 'BOMBAY';
• Delete all records of supplier table
DELETE FROM Supplier;
7. Queries with Constraints
• Create the supplier table with Primary Key Constraint
CREATE TABLE Supplier (
SID INT PRIMARY KEY,
Sname VARCHAR(50),
branch VARCHAR(50),
city VARCHAR(50),
phone VARCHAR(15)
);
• Create supplies table with Foreign key Constraint
CREATE TABLE Supplies (
SID INT,
PID INT,
qty INT,
date_supplied DATE,
FOREIGN KEY (SID) REFERENCES Supplier(SID)
);
• Create a part table with UNIQUE Constraint
CREATE TABLE Part (
PID INT PRIMARY KEY,
Pname VARCHAR(50) UNIQUE,
color VARCHAR(20),
price DECIMAL(10, 2)
);
• Create supplier Table with Check Constraints
CREATE TABLE Supplier (
SID INT PRIMARY KEY,
Sname VARCHAR(50),
branch VARCHAR(50),
city VARCHAR(50),
phone VARCHAR(15),
CHECK (city IN ('Delhi', 'Mumbai', 'Chennai', 'Bangalore',
'Hyderabad'))
);
• Create Supplier table with Default
CREATE TABLE Supplier (
SID INT PRIMARY KEY,
Sname VARCHAR(50),
branch VARCHAR(50),
city VARCHAR(50) DEFAULT 'Delhi',
phone VARCHAR(15)
);
8. Constraint Queries on TCL
Create Savepoints
INSERT INTO Supplier VALUES (201, 'ABC Corp', 'North',
'Mumbai', '9876543210');
SAVEPOINT sp1;
INSERT INTO Part VALUES (301, 'Bolt', 'Silver', 2.5);
SAVEPOINT sp2;
INSERT INTO Supplies VALUES (201, 301, 100, '2025-07-08');
SAVEPOINT sp3;
Rollback to SavePoints
ROLLBACK TO sp2;
Use Commit to save on
INSERT INTO Supplies VALUES (201, 301, 150, '2025-07-09');
SAVEPOINT sp4;
COMMIT;
9. Aggregate Functions:
Find the minimum, maximum, average and sum of costs of parts
SELECT MIN(price) ,MAX(price) ,AVG(price) ,SUM(price) FROM
Part;
Count the total number of parts present
SELECT COUNT(*) FROM Part;
Retrieve the average cost of all parts supplied by ‘Mike’
SELECT AVG(p.price) FROM Supplier s
JOIN Supplies sp ON s.SID = sp.SID
JOIN Part p ON sp.PID = p.PID
WHERE s.Sname = 'Mike';
10. Queries on GROUP BY, HAVING AND ORDER BY Clauses
Display total price of parts of each color
SELECT color, SUM(price) FROM Part GROUP BY color;
Find the branch and the number of suppliers in that branch for
branches which have more than 1 suppliers
SELECT branch, COUNT(*) FROM Supplier GROUP BY branch
HAVING COUNT(*) > 1;
Find all parts sorted by pname in ascending order and cost in descending
order
SELECT * FROM Part ORDER BY Pname ASC, price DESC;
Find the branch and the number of suppliers in that branch
SELECT branch, COUNT(*) FROM Supplier GROUP BY branch;
11. Queries on Analytical, Hierarchical, Recursive nature.
Employee(EmpID, EmpName, Salary, DeptID, ManagerID)
Department(DeptID, DeptName, ParentDeptID)
Find out the 5th highest earning employee details.
SELECT * FROM (
SELECT *, DENSE_RANK() OVER (ORDER BY Salary DESC)
AS rnk
FROM Employee
) AS ranked
WHERE rnk = 5;
Which department has the highest number of employees with a salary
above $80,000, and what percentage of employees in that department
have a salary above $80,000
-- Count of employees earning > 80000 per department
WITH HighEarners AS (
SELECT DeptID, COUNT(*) AS high_earners
FROM Employee
WHERE Salary > 80000
GROUP BY DeptID
),
-- Total employees per department
TotalEmp AS (
SELECT DeptID, COUNT(*) AS total_emp
FROM Employee
GROUP BY DeptID
)
SELECT d.DeptName, h.high_earners,
ROUND((h.high_earners * 100.0) / t.total_emp, 2) AS
percent_high_earners
FROM HighEarners h
JOIN TotalEmp t ON h.DeptID = t.DeptID
JOIN Department d ON d.DeptID = h.DeptID
ORDER BY h.high_earners DESC
LIMIT 1;
Retrieve employee table details using the hierarchy query and display
that hierarchy path starting from the top level indicating if it is a leaf
and there exists a cycle.
WITH RECURSIVE EmpTree AS (
SELECT
EmpID, EmpName, ManagerID,
CAST(EmpName AS CHAR) AS path,
EmpID AS root_id,
0 AS level
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT
e.EmpID, e.EmpName, e.ManagerID,
CONCAT(et.path, ' -> ', e.EmpName),
et.root_id,
et.level + 1
FROM Employee e
JOIN EmpTree et ON e.ManagerID = et.EmpID
WHERE e.EmpID <> et.EmpID -- prevent self-cycle
)
SELECT *,
NOT EXISTS (SELECT 1 FROM Employee e2 WHERE
e2.ManagerID = e1.EmpID) AS is_leaf
FROM EmpTree e1;
What is the average salary for employees in the top 2 departments
with the highest average salary, and what is the hierarchy of
departments and sub-departments for these top 2 departments?
WITH DeptAvg AS (
SELECT DeptID, AVG(Salary) AS avg_salary
FROM Employee
GROUP BY DeptID
ORDER BY avg_salary DESC
LIMIT 2
),
-- Get hierarchy of top 2 departments
DeptHierarchy AS (
SELECT DeptID, DeptName, ParentDeptID, CAST(DeptName
AS CHAR) AS path, 0 AS level
FROM Department
WHERE DeptID IN (SELECT DeptID FROM DeptAvg)
UNION ALL
SELECT d.DeptID, d.DeptName, d.ParentDeptID,
CONCAT(dh.path, ' -> ', d.DeptName),
dh.level + 1
FROM Department d
JOIN DeptHierarchy dh ON d.ParentDeptID = dh.DeptID
)
SELECT * FROM DeptHierarchy;
Use recursion to retrieve the employee table and display the result in
breadth first and depth first order.
WITH RECURSIVE DepthFirst AS (
SELECT EmpID, EmpName, ManagerID, 0 AS level
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmpID, e.EmpName, e.ManagerID, df.level + 1
FROM Employee e
JOIN DepthFirst df ON e.ManagerID = df.EmpID
)
SELECT * FROM DepthFirst ORDER BY level, EmpID;
WITH RECURSIVE BreadthFirst AS (
SELECT EmpID, EmpName, ManagerID, 0 AS level
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmpID, e.EmpName, e.ManagerID, bf.level + 1
FROM Employee e
JOIN BreadthFirst bf ON e.ManagerID = bf.EmpID
)
SELECT * FROM BreadthFirst ORDER BY level;
Write a recursive query to show the equivalent of level,
connect_by_root and connect_by_path
WITH RECURSIVE EmpHierarchy AS (
SELECT EmpID, EmpName, ManagerID,
CAST(EmpID AS CHAR) AS path,
EmpID AS root_id,
0 AS level
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmpID, e.EmpName, e.ManagerID,
CONCAT(eh.path, '->', e.EmpID),
eh.root_id,
eh.level + 1
FROM Employee e
JOIN EmpHierarchy eh ON e.ManagerID = eh.EmpID
)
SELECT EmpID, EmpName, ManagerID, level, root_id, path
FROM EmpHierarchy;
Use recursion to retrieve the employee table and display the result
in depth first order showing id, parent_id, level, root_id, path and
leaf.
WITH RECURSIVE EmpTree AS (
SELECT EmpID AS id, ManagerID AS parent_id,
0 AS level, EmpID AS root_id,
CAST(EmpID AS CHAR) AS path
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmpID, e.ManagerID,
et.level + 1, et.root_id,
CONCAT(et.path, '->', e.EmpID)
FROM Employee e
JOIN EmpTree et ON e.ManagerID = et.id
)
SELECT et.*,
NOT EXISTS (SELECT 1 FROM Employee e WHERE
e.ManagerID = et.id) AS is_leaf
FROM EmpTree et
ORDER BY path;
12. Queries on Operators
Find the pname, phoneno and cost of parts which have cost equal to or
greater than 200 and less than or equal to 600.
SELECT Pname, price
FROM Part
WHERE price >= 200 AND price <= 600;
Find the sname , SID and branch of suppliers who are in ‘local’ branch
or ‘global’ branch
SELECT Sname, SID, branch
FROM Supplier
WHERE branch = 'local' OR branch = 'global';
Find the pname, phoneno and cost of parts for which cost is between
200 and 600
SELECT Pname, price
FROM Part
WHERE price BETWEEN 200 AND 600;
Find the pname and color of parts, which has the word ‘NET’
anywhere in its pname.
SELECT Pname, color
FROM Part
WHERE Pname LIKE '%NET%';
Find the PID and pname of parts with pname either ‘NUT’ or ‘BOLT’
SELECT PID, Pname
FROM Part
WHERE Pname IN ('NUT', 'BOLT');
List the suppliers who supplied parts on ‘1st may2000’, ‘12 JAN
2021’ ,’17 dec 2000’, ’10 Jan 2021’
SELECT DISTINCT s.SID, s.Sname
FROM Supplier s
JOIN Supplies sp ON s.SID = sp.SID
WHERE date_supplied IN (
DATE '2000-05-01',
DATE '2021-01-12',
DATE '2000-12-17',
DATE '2021-01-10'
);
Find all the distinct costs of parts
SELECT DISTINCT price
FROM Part;
13. Join Operators
Perform Inner join on two tables
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
INNER JOIN Supplies sp ON s.SID = sp.SID;
Perform Natural Join on two tables
SELECT *
FROM Supplier
NATURAL JOIN Supplies;
OR
SELECT *
FROM Supplier
JOIN Supplies USING(SID);
Perform Left Outer Join on tables
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
LEFT OUTER JOIN Supplies sp ON s.SID = sp.SID;
Perform Right Outer join on tables
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
RIGHT OUTER JOIN Supplies sp ON s.SID = sp.SID;
Perform Full Outer Join on tables
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
FULL OUTER JOIN Supplies sp ON s.SID = sp.SID;
OR
-- Simulate FULL OUTER JOIN in MySQL
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
LEFT JOIN Supplies sp ON s.SID = sp.SID
UNION
SELECT s.SID, s.Sname, sp.PID, sp.qty
FROM Supplier s
RIGHT JOIN Supplies sp ON s.SID = sp.SID;
14. Set Theory Operators
Show the use of UNION operator with union compatibility
SELECT SID, branch FROM Supplier
UNION
SELECT SID, city FROM Supplier;
Show the use of intersect operator with union compatibility
SELECT SID, branch FROM Supplier
INTERSECT
SELECT SID, city FROM Supplier;
OR
SELECT SID, branch
FROM Supplier
WHERE branch IN (SELECT city FROM Supplier);
Show the use of minus operator with union compatibility
SELECT SID, branch FROM Supplier
MINUS
SELECT SID, city FROM Supplier;
Find the cartesian product of two tables
SELECT *
FROM Supplier, Part;
15. Queries on Set Theory Operators
List all parts except ‘NUT’ and ‘BOLT’ in ascending order of costs
SELECT *
FROM Part
WHERE Pname NOT IN ('NUT', 'BOLT')
ORDER BY price ASC;
display all parts that have not been supplied so far
SELECT *
FROM Part
WHERE PID NOT IN (
SELECT DISTINCT PID
FROM Supplies
);
To display the supplier names who have supplied ‘green’ part
with cost 500 Rupees AND ‘red’ part with cost 400 Rupees.
-- Suppliers who supplied green part costing 500
SELECT DISTINCT s.Sname
FROM Supplier s
JOIN Supplies sp ON s.SID = sp.SID
JOIN Part p ON sp.PID = p.PID
WHERE p.color = 'green' AND p.price = 500
INTERSECT
-- Suppliers who supplied red part costing 400
SELECT DISTINCT s.Sname
FROM Supplier s
JOIN Supplies sp ON s.SID = sp.SID
JOIN Part p ON sp.PID = p.PID
WHERE p.color = 'red' AND p.price = 400;
OR
SELECT s.Sname
FROM Supplier s
WHERE s.SID IN (
SELECT sp.SID
FROM Supplies sp
JOIN Part p ON sp.PID = p.PID
WHERE (p.color = 'green' AND p.price = 500)
)
AND s.SID IN (
SELECT sp.SID
FROM Supplies sp
JOIN Part p ON sp.PID = p.PID
WHERE (p.color = 'red' AND p.price = 400)
);
To display the supplier names who have supplied ‘green’ part
with cost 500 Rupees OR ‘red’ part with cost 400 Rupees.
SELECT DISTINCT s.Sname
FROM Supplier s
JOIN Supplies sp ON s.SID = sp.SID
JOIN Part p ON sp.PID = p.PID
WHERE (p.color = 'green' AND p.price = 500)
OR (p.color = 'red' AND p.price = 400);
To Display the name of suppliers who have supplied all parts that are ‘red’
in color.
SELECT s.Sname
FROM Supplier s
WHERE NOT EXISTS (
SELECT *
FROM Part p
WHERE p.color = 'red'
AND NOT EXISTS (
SELECT *
FROM Supplies sp
WHERE sp.SID = s.SID AND sp.PID = p.PID
)
);
PART – B
PL/SQL Programs(set serveroutput on;)
1. Write a PL/SQL Code to add two numbers
DECLARE
a NUMBER := 15;
b NUMBER := 25;
s NUMBER;
BEGIN
s := a + b;
DBMS_OUTPUT.PUT_LINE('SUM : ' || s);
END;
/
OUTPUT:
SUM : 40
2. Write a PL/SQL code for Fibonacci series
DECLARE
n NUMBER := 10;
a NUMBER := 0;
b NUMBER := 1;
c NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Fibonacci Series up to ' || n || ' terms:');
FOR i IN 1..n LOOP
DBMS_OUTPUT.PUT_LINE(a);
c := a + b;
a := b;
b := c;
END LOOP;
END;
/
OUTPUT:
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34
3. Write a PL/SQL Code for greatest of 3 numbers
DECLARE
a NUMBER := 45;
b NUMBER := 78;
c NUMBER := 62;
large NUMBER;
BEGIN
IF a >= b AND a >= c THEN
large := a;
ELSIF b >= a AND b >= c THEN
large := b;
ELSE
large := c;
END IF;
DBMS_OUTPUT.PUT_LINE('Greatest number is: ' || large);
END;
/
OUTPUT:
Greatest number is : 78
4. Write a PL/SQL code for area and circumference of a circle
DECLARE
r NUMBER := 2;
area NUMBER;
circum NUMBER;
pi CONSTANT NUMBER := 3.14159;
BEGIN
area := pi * r * r;
circum := 2 * pi * r;
DBMS_OUTPUT.PUT_LINE('Radius: ' || r);
DBMS_OUTPUT.PUT_LINE('Area of the circle: ' || area);
DBMS_OUTPUT.PUT_LINE('Circumference of the circle: ' || circum);
END;
/
OUTPUT:
Radius: 2
Area of the circle: 12.56636
Circumference of the circle: 12.56636
5. MongoDB Queries
1. Create a collection and insert documents into it using insertOne() and
insertMany()
// insertOne()
db.suppliers.insertOne(
{ name: "Geeta",city: "Delhi",color: "red",part_name: "P1",price: 150,
phoneno: "12345678"}
);
// insertMany()
db.suppliers.insertMany([
{ name: "Raj", city: "Mumbai", color: "green", part_name: "P2", price: 300,
phoneno: "23456789" },
{ name: "Amit", city: "Lucknow", color: "blue", part_name: "P3", price: 5200,
phoneno: "34567890" }
]);
2. Select all documents in collection
db.suppliers.find();
3. Find the count of all suppliers
db.suppliers.countDocuments();
4. Find all records that have city = ‘Delhi’
db.suppliers.find({ city: "Delhi" });
5. Retrieve all documents that have color equal to ‘red’ or ‘green’
db.suppliers.find({ color: { $in: ["red", "green"] } });
6. Retrieve all documents where part_name is ‘P1’ or price is less than 200.
db.suppliers.find({
$or: [
{ part_name: "P1" },
{ price: { $lt: 200 } }
]
});
7. Update the record of ‘Geeta’ ,set city = ‘Bombay’ and phoneno = ‘11223344’
db.suppliers.updateOne(
{ name: "Geeta" },
{ $set: { city: "Bombay", phoneno: "11223344" } }
);
8. Delete all records where price is greater than 5000
db.suppliers.deleteMany({ price: { $gt: 5000 } });
9. Display only the name and city of the supplier
db.suppliers.find({}, { name: 1, city: 1, _id: 0 });
10. Sort all suppliers on city and display only the first two records.
db.suppliers.find().sort({ city: 1 }).limit(2);