Dbms Practical File
Dbms Practical File
AIM:- Create an ER diagram for a library management system that includes entity types,
attributes, keys, relationships, and instances.
ER Diagram is known as Entity-Relationship Diagram, it is used to analyze the structure of the Database. It
shows relationships between entities and their attributes.An ER Model provides a means of communication.
The Library Management System database keeps track of readers with the following considerations –
The system keeps track of the staff with a single point authentication system comprising login Id and
password.
Staff maintains the book catalog with its ISBN, Book title, price(in INR), category(novel, general,
story), edition, author Number and details.
A publisher has publisher Id, Year when the book was published, and name of the book.
Readers are registered with their user_id, email, name (first name, last name), Phone no (multiple entries
allowed), communication address. The staff keeps track of readers.
Readers can return/reserve books that stamps with issue date and return date. If not returned within the
prescribed time period, it may have a due date too.
Staff also generate reports that has readers id, registration no of report, book no and return/issue info.
This Library ER diagram illustrates key information about the Library, including entities such as staff,
readers, books, publishers, reports, and authentication system.
Book Entity : It has authno, isbn number, title, edition, category, price. ISBN is the Primary Key for
Book Entity.
Reader Entity : It has UserId, Email, address, phone no, name. Name is composite attribute of firstname
and lastname. Phone no is multi valued attribute. UserId is the Primary Key for Readers entity.
Publisher Entity : It has PublisherId, Year of publication, name. PublisherID is the Primary Key.
Authentication System Entity : It has LoginId and password with LoginID as Primary Key.
Reports Entity : It has UserId, Reg_no, Book_no, Issue/Return date. Reg_no is the Primary Key of
reports entity.
Staff Entity : It has name and staff_id with staff_id as Primary Key.
Reserve/Return Relationship Set : It has three attributes: Reserve date, Due date, Return date.
Relationships between Entities –
A reader can reserve N books but one book can be reserved by only one reader. The relationship 1:N.
A publisher can publish many books but a book is published by only one publisher. The relationship
1:N.
AIM :-Convert the ER diagram into relational schemas and define the primary and
foreign keys.
Converting an Entity-Relationship (ER) diagram to a Relational Model is a crucial step in database design.
The ER model represents the conceptual structure of a database, while the Relational Model is a physical
representation that can be directly implemented using a Relational Database Management System (RDBMS)
like Oracle or MySQL.
Binary Relationship with 1:1 cardinality and partial participation of both entities
A male marries 0 or 1 female and vice versa as well. So it is 1:1 cardinality with partial participation
constraint from both. First Convert each entity and relationship to tables.
Similarly Female table corresponds to Female Entity with key as F-Id. Marry Table represents relationship
between Male and Female (Which Male marries which female). So it will take attribute M-Id from Male and
F-Id from Female.
Male Marry Female
M1 – M1 F2 F1 –
M2 – M2 F1 F2 –
M3 – F3 –
PROGRAM - 3
CODE :-
CREATE TABLE Users (
);S
)
CREATE TABLE Products (
);
CREATE TABLE Orders (
user_id NUMBER,
);
order_idNUMBER ,
product_idNUMBER ,
price DECIMAL(10,2)
);
CREATE TABLE Payments (
order_idNUMBER(10) UNIQUE,
);
Program - 4
AIM:- Create a database for a hospital management system. Define tables for doctors,
patients, appointments, and prescriptions.
CODE :-
CREATE TABLE Doctors (
first_nameVARCHAR(100),
last_nameVARCHAR(100),
specialty VARCHAR(100),
phone_numberVARCHAR(15),
email VARCHAR(100)
);
first_nameVARCHAR(100),
last_nameVARCHAR(100),
dob DATE,
phone_numberVARCHAR(15),
email VARCHAR(100),
address VARCHAR(255),
doctor_id NUMBER,
);
doctor_id NUMBER,
patient_id NUMBER,
appointment_date DATE,
);
CREATE TABLE Prescriptions (
appointment_id NUMBER,
doctor_id NUMBER,
patient_id NUMBER,
medicine_name VARCHAR2(255),
dosage VARCHAR2(100),
);
PROGRAM - 5
AIM :- Perform basic operations such as inserting, updating, and deleting records.
CODE :-
INSERT INTO Doctors VALUES (1, 'Alice', 'Brown', 'Cardiologist', '1112223333',
'[email protected]');
INSERT INTO Doctors VALUES (2, 'Bob', 'Smith', 'Neurologist', '2345678901', '[email protected]');
INSERT INTO Doctors VALUES (4, 'David', 'Lee', 'Pediatrician', '4567890123', '[email protected]');
INSERT INTO Doctors VALUES (6, 'Frank', 'Garcia', 'ENT', '6789012345', '[email protected]');
INSERT INTO Doctors VALUES (8, 'Henry', 'Davis', 'Oncologist', '8901234567', '[email protected]');
INSERT INTO Prescriptions VALUES (302, 202, 2, 102, 'Ibuprofen', '200mg twice daily');
INSERT INTO Prescriptions VALUES (303, 203, 3, 103, 'Cetirizine', '10mg at night');
INSERT INTO Prescriptions VALUES (304, 204, 4, 104, 'Paracetamol', '500mg every 6 hours');
INSERT INTO Prescriptions VALUES (305, 205, 5, 105, 'Amoxicillin', '250mg three times daily');
INSERT INTO Prescriptions VALUES (306, 206, 6, 106, 'Loratadine', '10mg daily');
INSERT INTO Prescriptions VALUES (307, 207, 7, 107, 'Metformin', '500mg twice daily');
INSERT INTO Prescriptions VALUES (308, 208, 8, 108, 'Losartan', '50mg daily');
UPDATE Doctors
WHERE doctor_id = 1;
AIM :- Write queries to retrieve data from multiple tables using INNER JOIN, LEFT
JOIN, RIGHT JOIN, and FULL OUTER JOIN.
CODE :-
1. INNER JOIN
SELECT
a.appointment_id,
d.first_name AS doctor_name,
p.first_name AS patient_name,
a.appointment_date
FROM Appointments a
2. LEFT JOIN
SELECT
p.patient_id,
p.first_name AS patient_name,
a.appointment_id,
a.appointment_date
FROM Patients p
3. RIGHT JOIN
SELECT
a.appointment_id,
p.first_name AS patient_name,
a.appointment_date
FROM Patients p
p.patient_id,
p.first_name AS patient_name,
a.appointment_id,
a.appointment_date
FROM Patients p
UNION
SELECT
p.patient_id,
p.first_name AS patient_name,
a.appointment_id,
a.appointment_date
FROM Patients p
AIM :- Create a query to find patients who have visited a specific doctor using JOIN.
CODE :-
SELECT
p.patient_id,
p.first_name,
p.last_name,
d.first_name AS doctor_first_name,
d.last_name AS doctor_last_name,
a.appointment_date
FROM Patients p
WHERE d.doctor_id = 1;
PROGRAM - 8
AIM :- Create a view to display the total number of patients attended by each doctor.
CODE :-
CREATE VIEW DoctorPatientCount AS
SELECT
d.doctor_id,
FROM Doctors d
AIM:- Add an index to optimize the search for patients by their last names.
CODE:-
CREATE INDEX idx_patients_lastname ON Patients(last_name);
Aim:- Write a PL/SQL program to implement a banking transaction system that transfers
money between two accounts. Use COMMIT and ROLLBACK statements.
CODE:-
CREATE TABLE accounts (
account_name VARCHAR2(100),
balance NUMBER
);
COMMIT;
DECLARE
v_sender_balance NUMBER;
BEGIN
FROM account
FOR UPDATE;
IF v_sender_balance<v_transfer_amt THEN
ROLLBACK;
ELSE
UPDATE account
UPDATE account
COMMIT;
END IF;
EXCEPTION
ROLLBACK;
DBMS_OUTPUT.PUT_LINE('Transaction failed due to error: ' || SQLERRM);
END;
/
PROGRAM - 11
AIM:- Create a cursor to fetch and display all overdue book records from a library
database.
CODE:-
CREATE TABLE BOOKS (
TITLE VARCHAR2(100),
AUTHOR VARCHAR2(100),
PUBLISHER VARCHAR2(100),
YEAR_PUBLISHED NUMBER
);
INSERT INTO BOOKS VALUES (1, 'The Great Gatsby', 'F. Scott Fitzgerald', 'Scribner', 1925);
INSERT INTO BOOKS VALUES (2, '1984', 'George Orwell', 'Secker & Warburg', 1949);
INSERT INTO BOOKS VALUES (3, 'To Kill a Mockingbird', 'Harper Lee', 'J.B. Lippincott & Co.', 1960);
NAME VARCHAR2(100),
EMAIL VARCHAR2(100),
JOIN_DATE DATE
);
INSERT INTO MEMBERS VALUES (101, 'Alice Johnson', '[email protected]', TO_DATE('2022-01-15',
'YYYY-MM-DD'));
BORROW_DATE DATE,
DUE_DATE DATE,
RETURN_DATE DATE
);
DECLARE
CURSOR overdue_books_cur IS
SELECT bb.BORROW_ID,
b.TITLE,
m.NAME AS MEMBER_NAME,
bb.BORROW_DATE,
bb.DUE_DATE
FROM BORROWED_BOOKS bb
overdue_recoverdue_books_cur%ROWTYPE;
BEGIN
OPEN overdue_books_cur;
LOOP
FETCH overdue_books_cur INTO overdue_rec;
DBMS_OUTPUT.PUT_LINE('-------------------------------------------');
END LOOP;
CLOSE overdue_books_cur;
END;
/
PROGRAM - 12
AIM:- Develop a trigger to automatically update the stock count when a new product is
added to an inventory database.
CODE:-
CREATE TABLE PRODUCT_DB (
PRODUCT_NAME VARCHAR2(100),
QUANTITY NUMBER
);
TOTAL_STOCK NUMBER
);
COMMIT;
BEGIN
UPDATE INVENTORY_SUMMARY
END;
/
INSERT INTO PRODUCT_DB (PRODUCT_ID, PRODUCT_NAME, QUANTITY)
AIM:- Write and execute queries in relational algebra for the following operations:
selection, projection, union, intersection, difference, Cartesian product, and join for a
student database.
CODE:-
CREATE TABLE Student_db (
Name VARCHAR2(50),
Age NUMBER,
DeptID NUMBER
);
DeptName VARCHAR2(50)
);
INSERT INTO Student_db VALUES (1, 'Alice', 20, 101);
SELECT * FROMStudent_db
INTERSECT
SELECT * FROM MoreStudents;
✅ Difference (-): Students not in MoreStudents
SELECT * FROMStudent_db
MINUS
SELECT * FROM MoreStudents;
Functional Dependencies
1. StudentID → StudentName
- A course ID uniquely determines the course name and the instructor teaching it.
3. InstructorID → InstructorName
- If a course is taught by only one instructor, then the combination of student and course determines the
instructor.
PROGRAM - 15
AIM:- Normalize the database to 1NF, 2NF, 3NF, and BCNF, showing each step of
decomposition.
Original Table: `ENROLLMENT`
1. `StudentID → StudentName`
3. `InstructorID → InstructorName`
1NF Requirement:
2NF Requirement: Table must be in 1NF and no partial dependencies (non-prime attributes depend only on
part of a composite key).
1. STUDENT(StudentID, StudentName)
3NF Requirement: Table is in 2NF, and no transitive dependencies (non-prime → non-prime via another non-
prime).
1. INSTRUCTOR(InstructorID, InstructorName)
BCNF Requirement: For every non-trivial FD, theleft side must be a superkey.
STUDENT(StudentID, StudentName)
INSTRUCTOR(InstructorID, InstructorName)
1. STUDENT(StudentID, StudentName)
3. INSTRUCTOR(InstructorID, InstructorName)
AIM:- Write an inefficient query for fetching data from a large database. Use EXPLAIN
PLAN to analyze it and optimize the query using indexes and appropriate joins.
CODE :-
CREATE TABLE EMP (
EMP_NAME VARCHAR(100),
DEPT_ID INT,
SALARY DECIMAL(10, 2)
);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (101, 'Alice Johnson',
1, 75000);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (102, 'Bob Smith', 2,
60000);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (103, 'Charlie Lee', 1,
72000);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (104, 'Diana Clark',
3, 80000);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (105, 'Evan Davis', 2,
55000);
INSERT INTO EMPLOYEES (EMP_ID, EMP_NAME, DEPT_ID, SALARY) VALUES (106, 'Frank Miller',
3, 67000);
CREATE TABLE DEPT (
DEPT_NAME VARCHAR2(50)
);
SELECT e.EMP_NAME
FROM EMP e
WHERE e.DEPT_ID IN (
SELECT d.DEPT_ID
FROM DEPT d
);
Analyze with EXPLAIN PLAN
SELECT e.EMP_NAME
FROM EMP e
WHERE e.DEPT_ID IN (
SELECT d.DEPT_ID
FROM DEPT d
);
You will likely see a full table scan on both EMPLOYEES and DEPARTMENTS, making the query slow for
large datasets.
SELECT e.EMP_NAME
FROM EMP e
JOIN DEPT d ON e.DEPT_ID = d.DEPT_ID
WHERE d.DEPT_NAME = 'Human Resources';
Uses a JOIN instead of a subquery, which allows the optimizer to use indexed access paths.
Takes advantage of the newly created indexes, reducing full table scans.