0% found this document useful (0 votes)
0 views49 pages

Dbms Practical File

The document outlines a series of programs related to database management, including creating ER diagrams, converting them to relational schemas, and implementing database schemas for various applications such as library management, e-commerce, and hospital management systems. It details the creation of tables, defining primary and foreign keys, performing basic operations, and writing SQL queries for data retrieval and manipulation. Additionally, it covers normalization processes and the use of PL/SQL for banking transactions.

Uploaded by

didrumadro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views49 pages

Dbms Practical File

The document outlines a series of programs related to database management, including creating ER diagrams, converting them to relational schemas, and implementing database schemas for various applications such as library management, e-commerce, and hospital management systems. It details the creation of tables, defining primary and foreign keys, performing basic operations, and writing SQL queries for data retrieval and manipulation. Additionally, it covers normalization processes and the use of PL/SQL for banking transactions.

Uploaded by

didrumadro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

INDEX

SR.NO PROGRAM TITLE DATE SIGNATURE


1. Create an ER diagram for a library management system
that includes entity types, attributes, keys, relationships,
and instances.
2. Convert the ER diagram into relational schemas and define
the primary and foreign keys.
3. Implement a database schema in a DBMS for an e-
commerce application. Define the constraints, such as
NOT NULL, UNIQUE, CHECK, and FOREIGN KEY.
4. Create a database for a hospital management system.
Define tables for doctors, patients, appointments, and
prescriptions.
5. Perform basic operations such as inserting, updating, and
deleting records.
6. Write queries to retrieve data from multiple tables using
INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL
OUTER JOIN
7. Create a query to find patients who have visited a specific
doctor using JOIN.
8. Create a view to display the total number of patients
attended by each doctor.
9. Add an index to optimize the search for patients by their
last names.
10. Write a PL/SQL program to implement a banking
transaction system that transfers money between two
accounts. Use COMMIT and ROLLBACK statements
11. Create a cursor to fetch and display all overdue book
records from a library database.
12. Develop a trigger to automatically update the stock count
when a new product is added to an inventory database.
13. Write and execute queries in relational algebra for the
following operations: selection, projection, union,
intersection, difference, Cartesian product, and join for a
student database.

14. Identify functional dependencies in a given database (e.g.,


a university database).
15. Normalize the database to 1NF, 2NF, 3NF, and BCNF,
showing each step of decomposition.
16. 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.
PROGRAM - 1

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.

It allows for understanding the relationships between entities.


Entities and their Attributes –

 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.

 Staff keeps track of readers. The relationship is M:N.

 Staff maintains multiple reports. The relationship 1:N.

 Staff maintains multiple Books. The relationship 1:N.

 Authentication system provides login to multiple staffs. The relation is 1:N.


PROGRAM -2

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.

Male table corresponds to Male Entity with key as M-Id.

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

M-Id Other Male Attribute M-Id F-Id F-Id Other FemaleAttribute

M1 – M1 F2 F1 –

M2 – M2 F1 F2 –

M3 – F3 –
PROGRAM - 3

AIM :- Implement a database schema in a DBMS for an e-commerce application. Define


the constraints, such as NOT NULL, UNIQUE, CHECK, and FOREIGN KEY.

CODE :-
CREATE TABLE Users (

user_id NUMBER PRIMARY KEY,

first_name VARCHAR2 (50) NOT NULL,

last_name VARCHAR2 (50) NOT NULL,

email VARCHAR2 (100) UNIQUE,

password VARCHAR2 (255) NOT NULL,

phone_number VARCHAR2 (15) UNIQUE,

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);S

CREATE TABLE Categories (

category_id NUMBER PRIMARY KEY,

name VARCHAR2 (100) UNIQUE NOT NULL,

description VARCHAR2 (100) NOT NULL

)
CREATE TABLE Products (

product_id NUMBER PRIMARY KEY,

name VARCHAR2 (255) NOT NULL,

description VARCHAR2 (20) NOT NULL,

price DECIMAL(10,2) NOT NULL CHECK (price > 0),

stock_quantity NUMBER NOT NULL CHECK (stock_quantity>= 0),

category_id NUMBER NOT NULL,

FOREIGN KEY (category_id) REFERENCES Categories(category_id) ON DELETE SET NULL

);
CREATE TABLE Orders (

order_id NUMBER PRIMARY KEY,

user_id NUMBER,

total_amountDECIMAL(10,2) CHECK (total_amount>= 0),

created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

FOREIGN KEY (user_id) REFERENCES Users(user_id) ON DELETE CASCADE

);

CREATE TABLE Order_Items (

order_item_id NUMBER PRIMARY KEY,

order_idNUMBER ,

product_idNUMBER ,

quantity NUMBER NOT NULL CHECK (quantity > 0),

price DECIMAL(10,2)

FOREIGN KEY (product_id) REFERENCES Products(product_id) ON DELETE CASCADE

);
CREATE TABLE Payments (

payment_idNUMBER(10) PRIMARY KEY,

order_idNUMBER(10) UNIQUE,

payment_method VARCHAR2(20) CHECK (payment_method IN ('Credit Card', 'PayPal', 'Bank Transfer',


'Cash on Delivery')),

payment_status VARCHAR2(20) DEFAULT 'Pending' CHECK (payment_status IN ('Pending', 'Completed',


'Failed', 'Refunded')),

transaction_id VARCHAR2(100) NOT NULL UNIQUE,

created_at DATE DEFAULT SYSDATE NOT NULL,

CONSTRAINT fk_order FOREIGN KEY (order_id) REFERENCES Order_Items (order_item_id) ON


DELETE CASCADE

);
Program - 4

AIM:- Create a database for a hospital management system. Define tables for doctors,
patients, appointments, and prescriptions.

CODE :-
CREATE TABLE Doctors (

doctor_id NUMBER PRIMARY KEY,

first_nameVARCHAR(100),

last_nameVARCHAR(100),

specialty VARCHAR(100),

phone_numberVARCHAR(15),

email VARCHAR(100)

);

CREATE TABLE Patients (

patient_id NUMBER PRIMARY KEY,

first_nameVARCHAR(100),

last_nameVARCHAR(100),

dob DATE,

phone_numberVARCHAR(15),

email VARCHAR(100),
address VARCHAR(255),

doctor_id NUMBER,

FOREIGN KEY (doctor_id) REFERENCES Doctors(doctor_id) ON DELETE SET NULL

);

CREATE TABLE Appointments (

appointment_id NUMBER PRIMARY KEY,

doctor_id NUMBER,

patient_id NUMBER,

appointment_date DATE,

FOREIGN KEY (doctor_id) REFERENCES Doctors(doctor_id) ON DELETE CASCADE,

FOREIGN KEY (patient_id) REFERENCES Patients(patient_id) ON DELETE CASCADE

);
CREATE TABLE Prescriptions (

prescription_id NUMBER PRIMARY KEY ,

appointment_id NUMBER,

doctor_id NUMBER,

patient_id NUMBER,

medicine_name VARCHAR2(255),

dosage VARCHAR2(100),

FOREIGN KEY (appointment_id) REFERENCES Appointments(appointment_id) ON DELETE


CASCADE,

FOREIGN KEY (doctor_id) REFERENCES Doctors(doctor_id) ON DELETE CASCADE,

FOREIGN KEY (patient_id) REFERENCES Patients(patient_id) ON DELETE CASCADE

);
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 (3, 'Cathy', 'Johnson', 'Dermatologist', '3456789012',


'[email protected]');

INSERT INTO Doctors VALUES (4, 'David', 'Lee', 'Pediatrician', '4567890123', '[email protected]');

INSERT INTO Doctors VALUES (5, 'Ella', 'Martinez', 'Orthopedic', '5678901234',


'[email protected]');

INSERT INTO Doctors VALUES (6, 'Frank', 'Garcia', 'ENT', '6789012345', '[email protected]');

INSERT INTO Doctors VALUES (7, 'Grace', 'Walker', 'Gynecologist', '7890123456',


'[email protected]');

INSERT INTO Doctors VALUES (8, 'Henry', 'Davis', 'Oncologist', '8901234567', '[email protected]');

INSERT INTO Patients VALUES (101, 'John', 'Doe', TO_DATE('1990-06-15', 'YYYY-MM-DD'),


'9876543210', '[email protected]', '123 Main St', 1);

INSERT INTO Patients VALUES (102, 'Jane', 'Smith', TO_DATE('1985-09-25', 'YYYY-MM-DD'),


'9876543211', '[email protected]', '456 Elm St', 2);
INSERT INTO Patients VALUES (103, 'Emily', 'Clark', TO_DATE('1992-12-10', 'YYYY-MM-DD'),
'9876543212', '[email protected]', '789 Oak St', 3);

INSERT INTO Patients VALUES (104, 'Michael', 'Wilson', TO_DATE('1980-03-30', 'YYYY-MM-DD'),


'9876543213', '[email protected]', '321 Pine St', 4);

INSERT INTO Patients VALUES (105, 'Sarah', 'Lopez', TO_DATE('2000-01-20', 'YYYY-MM-DD'),


'9876543214', '[email protected]', '654 Maple St', 5);

INSERT INTO Patients VALUES (106, 'Chris', 'Taylor', TO_DATE('1975-07-07', 'YYYY-MM-DD'),


'9876543215', '[email protected]', '987 Cedar St', 6);

INSERT INTO Patients VALUES (107, 'Nancy', 'Hall', TO_DATE('1995-11-11', 'YYYY-MM-DD'),


'9876543216', '[email protected]', '246 Birch St', 7);

INSERT INTO Patients VALUES (108, 'Robert', 'Allen', TO_DATE('1988-04-18', 'YYYY-MM-DD'),


'9876543217', '[email protected]', '135 Walnut St', 8);

INSERT INTO Appointments VALUES (201, 1, 101, TO_DATE('2025-05-05', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (202, 2, 102, TO_DATE('2025-05-06', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (203, 3, 103, TO_DATE('2025-05-07', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (204, 4, 104, TO_DATE('2025-05-08', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (205, 5, 105, TO_DATE('2025-05-09', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (206, 6, 106, TO_DATE('2025-05-10', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (207, 7, 107, TO_DATE('2025-05-11', 'YYYY-MM-DD'));

INSERT INTO Appointments VALUES (208, 8, 108, TO_DATE('2025-05-12', 'YYYY-MM-DD'));


INSERT INTO Prescriptions VALUES (301, 201, 1, 101, 'Aspirin', '100mg once daily');

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

SET phone_number = '9115223733'

WHERE doctor_id = 1;

DELETE FROM Prescriptions

WHERE prescription_id = 301;


PROGRAM - 6

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

INNER JOIN Doctors d ON a.doctor_id = d.doctor_id

INNER JOIN Patients p ON a.patient_id = p.patient_id;

2. LEFT JOIN
SELECT

p.patient_id,

p.first_name AS patient_name,

a.appointment_id,
a.appointment_date

FROM Patients p

LEFT JOIN Appointments a ON p.patient_id = a.patient_id;

3. RIGHT JOIN
SELECT

a.appointment_id,

p.first_name AS patient_name,

a.appointment_date

FROM Patients p

RIGHT JOIN Appointments a ON p.patient_id = a.patient_id;


4. FULL OUTER JOIN
SELECT

p.patient_id,

p.first_name AS patient_name,

a.appointment_id,

a.appointment_date

FROM Patients p

LEFT JOIN Appointments a ON p.patient_id = a.patient_id

UNION

SELECT

p.patient_id,

p.first_name AS patient_name,

a.appointment_id,

a.appointment_date

FROM Patients p

RIGHT JOIN Appointments a ON p.patient_id = a.patient_id;


PROGRAM - 7

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

INNER JOIN Appointments a ON p.patient_id = a.patient_id

INNER JOIN Doctors d ON a.doctor_id = d.doctor_id

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,

d.first_name || ' ' || d.last_name AS doctor_name,

COUNT(DISTINCT a.patient_id) AS total_patients_attended

FROM Doctors d

LEFT JOIN Appointments a ON d.doctor_id = a.doctor_id

GROUP BY d.doctor_id, d.first_name, d.last_name;

SELECT * FROM DoctorPatientCount;


PROGRAM - 9

AIM:- Add an index to optimize the search for patients by their last names.

CODE:-
CREATE INDEX idx_patients_lastname ON Patients(last_name);

SELECT * FROM Patients WHERE last_name = 'Smith';


Program - 10

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_id NUMBER PRIMARY KEY,

account_name VARCHAR2(100),

balance NUMBER

);

INSERT INTO accounts VALUES (101, 'Alice', 1000);

INSERT INTO accounts VALUES (102, 'Bob', 500);

COMMIT;

PL/SQL Program: Transfer Money Between Two Accounts

DECLARE

v_sender_idNUMBER := 101; -- ID of the sender

v_receiver_idNUMBER := 102; -- ID of the receiver


v_transfer_amt NUMBER := 500; -- Amount to be transferred

v_sender_balance NUMBER;

BEGIN

SELECT balance INTO v_sender_balance

FROM account

WHERE account_id = v_sender_id

FOR UPDATE;

IF v_sender_balance<v_transfer_amt THEN

DBMS_OUTPUT.PUT_LINE('Insufficient funds. Transaction rolled back.');

ROLLBACK;

ELSE

-- Deduct amount from sender

UPDATE account

SET balance = balance - v_transfer_amt

WHERE account_id = v_sender_id;

-- Add amount to receiver

UPDATE account

SET balance = balance + v_transfer_amt

WHERE account_id = v_receiver_id;

COMMIT;

DBMS_OUTPUT.PUT_LINE('Transaction successful. Amount transferred: ' || v_transfer_amt);

END IF;

EXCEPTION

WHEN OTHERS THEN

-- Handle unexpected errors and rollback

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 (

BOOK_ID NUMBER PRIMARY KEY,

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);

CREATE TABLE MEMBERS (

MEMBER_ID NUMBER PRIMARY KEY,

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'));

INSERT INTO MEMBERS VALUES (102, 'Bob Smith', '[email protected]', TO_DATE('2022-03-10',


'YYYY-MM-DD'));

CREATE TABLE BORROWED_BOOKS (

BORROW_ID NUMBER PRIMARY KEY,

BOOK_ID NUMBER REFERENCES BOOKS(BOOK_ID),

MEMBER_ID NUMBER REFERENCES MEMBERS(MEMBER_ID),

BORROW_DATE DATE,

DUE_DATE DATE,

RETURN_DATE DATE

);

INSERT INTO BORROWED_BOOKS VALUES (1001, 1, 101, TO_DATE('2025-04-01', 'YYYY-MM-DD'),


TO_DATE('2025-04-15', 'YYYY-MM-DD'), NULL);

INSERT INTO BORROWED_BOOKS VALUES (1002, 2, 102, TO_DATE('2025-03-25', 'YYYY-MM-DD'),


TO_DATE('2025-04-08', 'YYYY-MM-DD'), TO_DATE('2025-04-07', 'YYYY-MM-DD'));
SET SERVEROUTPUT ON;

DECLARE

-- Define a cursor to select overdue records

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

JOIN BOOKS b ON bb.BOOK_ID = b.BOOK_ID

JOIN MEMBERS m ON bb.MEMBER_ID = m.MEMBER_ID

WHERE bb.RETURN_DATE IS NULL

AND bb.DUE_DATE< SYSDATE;

overdue_recoverdue_books_cur%ROWTYPE;

BEGIN

OPEN overdue_books_cur;

LOOP
FETCH overdue_books_cur INTO overdue_rec;

EXIT WHEN overdue_books_cur%NOTFOUND;

-- Display the overdue record

DBMS_OUTPUT.PUT_LINE('Borrow ID : ' || overdue_rec.BORROW_ID);

DBMS_OUTPUT.PUT_LINE('Book Title : ' || overdue_rec.TITLE);

DBMS_OUTPUT.PUT_LINE('Member Name : ' || overdue_rec.MEMBER_NAME);

DBMS_OUTPUT.PUT_LINE('Borrow Date : ' || TO_CHAR(overdue_rec.BORROW_DATE, 'DD-MON-


YYYY'));

DBMS_OUTPUT.PUT_LINE('Due Date : ' || TO_CHAR(overdue_rec.DUE_DATE, 'DD-MON-


YYYY'));

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_ID NUMBER PRIMARY KEY,

PRODUCT_NAME VARCHAR2(100),

QUANTITY NUMBER

);

CREATE TABLE INVENTORY_SUMMARY (

TOTAL_STOCK NUMBER

);

INSERT INTO INVENTORY_SUMMARY (TOTAL_STOCK) VALUES (0);

COMMIT;

CREATE OR REPLACE TRIGGER trg_update_stock

AFTER INSERT ON PRODUCT_DB

FOR EACH ROW

BEGIN

UPDATE INVENTORY_SUMMARY

SET TOTAL_STOCK = TOTAL_STOCK + :NEW.QUANTITY;

END;

/
INSERT INTO PRODUCT_DB (PRODUCT_ID, PRODUCT_NAME, QUANTITY)

VALUES (101, 'Laptop', 5);

SELECT * FROM INVENTORY_SUMMARY;


PROGRAM -13

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 (

StudentID NUMBER PRIMARY KEY,

Name VARCHAR2(50),

Age NUMBER,

DeptID NUMBER

);

CREATE TABLE Departments (

DeptID NUMBER PRIMARY KEY,

DeptName VARCHAR2(50)

);
INSERT INTO Student_db VALUES (1, 'Alice', 20, 101);

INSERT INTO Student_db VALUES (2, 'Bob', 22, 102);

INSERT INTO Student_db VALUES (3, 'Charlie', 21, 101);

INSERT INTO Student_db VALUES (4, 'David', 23, 103);

INSERT INTO Student_db VALUES (5, 'Eve', 20, 102);

INSERT INTO Departments VALUES (101, 'Computer Science');

INSERT INTO Departments VALUES (102, 'Mathematics');

INSERT INTO Departments VALUES (103, 'Physics');

select * from Student_db;

select * from Departments;

Relational Algebra Operations in SQL


✅ Selection (σ): Students aged 22 or older

SELECT * FROM Student_db


WHERE Age >= 22;

✅ Projection (π): Project Name and Age only

SELECT Name, Age FROM Student_db;

✅ Union (⋃): Combine two student lists

Create another table for union:

CREATE TABLE MoreStudents (


StudentID NUMBER PRIMARY KEY,
Name VARCHAR2(50),
Age NUMBER,
DeptID NUMBER
);

INSERT INTO MoreStudents VALUES (6, 'Frank', 24, 101);


INSERT INTO MoreStudents VALUES (7, 'Grace', 22, 104);
COMMIT;

Now perform union:

SELECT * FROM Student_db


UNION
SELECT * FROM MoreStudents;

✅ Intersection (⋂): Students in both tables

SELECT * FROMStudent_db
INTERSECT
SELECT * FROM MoreStudents;
✅ Difference (-): Students not in MoreStudents

SELECT * FROMStudent_db
MINUS
SELECT * FROM MoreStudents;

✅ Cartesian Product (×): All combinations of Students and Departments

SELECT * FROMStudent_db, Departments;


✅ Join (⨝): Natural Join on DeptID

SELECT S.StudentID, S.Name, S.Age, D.DeptName


FROMStudent_db S
JOIN Departments D ON S.DeptID = D.DeptID;
PROGRAM - 14

AIM:- Identify functional dependencies in a given database (e.g., a university database).

Assume we have a relation (table) called:

ENROLLMENT(StudentID, StudentName, CourseID, CourseName, InstructorID, InstructorName, Grade)

Functional Dependencies

1. StudentID → StudentName

- A student ID uniquely identifies a student’s name.

2. CourseID → CourseName, InstructorID

- A course ID uniquely determines the course name and the instructor teaching it.

3. InstructorID → InstructorName

- An instructor ID uniquely identifies an instructor’s name.

4. (StudentID, CourseID) → Grade

- A student receives a unique grade in each course.

5. (StudentID, CourseID) → InstructorID

- 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`

ENROLLMENT(StudentID, StudentName, CourseID, CourseName, InstructorID, InstructorName, Grade)

Assumed Functional Dependencies:

From our previous discussion:

1. `StudentID → StudentName`

2. `CourseID → CourseName, InstructorID`

3. `InstructorID → InstructorName`

4. `(StudentID, CourseID) → Grade`

Step 1: First Normal Form (1NF)

1NF Requirement:

Eliminate multi-valued or composite attributes.

No changes needed for 1NF.

Step 2: Second Normal Form (2NF)

2NF Requirement: Table must be in 1NF and no partial dependencies (non-prime attributes depend only on
part of a composite key).

- Candidate key: (StudentID, CourseID)

- Partial dependencies exist:

- StudentID → StudentName(depends only on part of the key)

- CourseID → CourseName, InstructorID

Decompose into 2NF

1. STUDENT(StudentID, StudentName)

- From StudentID → StudentName

2. COURSE(CourseID, CourseName, InstructorID)


- From CourseID → CourseName, InstructorID

3. ENROLLMENT(StudentID, CourseID, Grade)

- Only full dependency remains: (StudentID, CourseID) → Grade

At this stage, all partial dependencies have been removed.

Step 3: Third Normal Form (3NF)

3NF Requirement: Table is in 2NF, and no transitive dependencies (non-prime → non-prime via another non-
prime).

From COURSE(CourseID, CourseName, InstructorID) we still have:

- InstructorID → InstructorName⇒ transitive dependency if we add InstructorName.

Decompose into 3NF

Assume we included InstructorName in the COURSE table. Then:

1. INSTRUCTOR(InstructorID, InstructorName)

- From InstructorID → InstructorName

2. COURSE(CourseID, CourseName, InstructorID)

- Now free of transitive dependencies

Now all relations are in 3NF.

Step 4: Boyce-Codd Normal Form (BCNF)

BCNF Requirement: For every non-trivial FD, theleft side must be a superkey.

Let’s check all current tables:

STUDENT(StudentID, StudentName)

- StudentIDis a key ⇒✔️ in BCNF

COURSE(CourseID, CourseName, InstructorID)

- CourseID → CourseName, InstructorID⇒CourseID is a key ⇒✔️

INSTRUCTOR(InstructorID, InstructorName)

- InstructorID → InstructorName⇒InstructorID is a key ⇒✔️

ENROLLMENT(StudentID, CourseID, Grade)


- (StudentID, CourseID) is the key ⇒✔️

All tables are already in BCNF.

Final BCNF Schema

1. STUDENT(StudentID, StudentName)

2. COURSE(CourseID, CourseName, InstructorID)

3. INSTRUCTOR(InstructorID, InstructorName)

4. ENROLLMENT(StudentID, CourseID, Grade)

Would you like an ER diagram to visualize these relationships?


PROGRAM - 16

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_ID INT PRIMARY KEY,

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_ID NUMBER PRIMARY KEY,

DEPT_NAME VARCHAR2(50)

);

INSERT INTO DEPT (DEPT_ID, DEPT_NAME) VALUES (1, 'Human Resources');

INSERT INTO DEPT (DEPT_ID, DEPT_NAME) VALUES (2, 'Finance');

INSERT INTO DEPT (DEPT_ID, DEPT_NAME) VALUES (3, 'Engineering');

INSERT INTO DEPT (DEPT_ID, DEPT_NAME) VALUES (4, 'Marketing');


This inefficient query uses a nested subquery and no indexes:

SELECT e.EMP_NAME

FROM EMP e

WHERE e.DEPT_ID IN (

SELECT d.DEPT_ID

FROM DEPT d

WHERE d.DEPT_NAME = 'Human Resources'

);
Analyze with EXPLAIN PLAN

EXPLAIN PLAN FOR

SELECT e.EMP_NAME

FROM EMP e

WHERE e.DEPT_ID IN (

SELECT d.DEPT_ID

FROM DEPT d

WHERE d.DEPT_NAME = 'Human Resources'

);

You will likely see a full table scan on both EMPLOYEES and DEPARTMENTS, making the query slow for
large datasets.

Optimized Version Using Joins and Indexes

Step 1: Create indexes to speed up filtering and joining


CREATE INDEX idx_dept_nameON DEPT(DEPT_NAME);
CREATE INDEX idx_dept_id_empON EMP(DEPT_ID);
Step 2: Use an inner join instead of subquery

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.

You might also like