Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views18 pages

Dbms Lab File

Uploaded by

heddie82
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)
10 views18 pages

Dbms Lab File

Uploaded by

heddie82
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/ 18

Government Engineering College, Khagaria

(Dept. of Science & Technology, Govt. of Bihar)

LAB FILE: Database Management System (DBMS)


PAPER CODE: 155502P

Submitted by: Submitted to:


Name : Sohan Kumar Das Mr. Abhishek Kumar
Reg. no : 22155154019 (Asst. Professor)
Branch : CSE(IOT) Dept. of CSE

Signature
INDEX
Subject: Database Management System Code : 155502P

Semester: 5th Discipline : CSE(IoT)

S. No. Details of Experiments (s) Faculty Signature

Student should decide on a case study and formulate the problem


1. statement for ER Diagram.

Conceptual Designing using ER Diagrams (Identifying entities,


attributes, keys and relationships between entities, cardinalities,
2. generalization, specialization etc.)

Converting ER Model to Relational Model (Represent entities and


3. relationships in Tabular form, Represent attributes as columns,
identifying keys)

Normalization -To remove the redundancies and anomalies in the above


4. relational tables, Normalize up to Third Normal Form.

Creation of Tables using SQL- Overview of using SQL tool, Data types
in SQL, Creating Tables (along with Primary and Foreign keys), Altering
5. Tables and Dropping Tables.

6. Practicing DML commands- Insert, Select, Update, Delete.

Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS,


7. UNION, INTERSECT, CONSTRAINTS etc.

Practicing Sub queries (Nested, Correlated) and Joins (Inner, Outer and
8.
Equi).

Practice Queries using COUNT, SUM, AVG, MAX, MIN, GROUP


9. BY, HAVING, VIEWS Creation and Dropping.

Practicing on Triggers - creation of trigger, Insertion using trigger,


10.
Deletion using trigger, Updating using trigger.
1. Student should decide on a case study and formulate the problem
statement for ER Diagram.
Experiment 1: Case Study Selection & Problem Statement for ER Diagram

Aim: Design a relational database management system for a hospital to efficiently


manage patients, doctors, admissions, treatments, billing, and departmental organization.

Problem Statement: A mid-sized hospital seeks to digitize its administrative and clinical
processes. The goal is to manage patient records, doctors’ schedules,
admissions/discharges, treatments/medications, billing for services, and track
departmental staff and facilities.

Requirements Gathering
Functional Requirements:
• Register/update/delete/search patients and doctors
• Admit, transfer, and discharge patients
• Assign patients to doctors and departments
• Record treatments, medications, and investigations
• Generate bills for hospital services
• Support sophisticated queries on admissions, doctors, outstanding bills, etc.

Non-Functional Requirements:
• Data integrity, security, and privacy
• Multi-user support and concurrency
• Accurate, up-to-date information retrieval
2. Conceptual Designing using ER Diagrams (Identifying entities,
attributes, keys and relationships between entities, cardinalities,
generalization, specialization etc.)

Experiment 2: Conceptual Designing Using ER Diagram

Aim: Model the hospital’s core data entities and relationships.

Identified Entities and Attributes


Entity Attributes
PatientID (PK), Name, Gender, DOB, Address, Phone, Email,
Patient BloodGroup, RegistrationDate
DoctorID (PK), Name, Specialty, Phone, Email, DepartmentID
Doctor (FK), HireDate
Department DepartmentID (PK), DepartmentName, Floor, Phone
AdmissionID (PK), PatientID (FK), DepartmentID (FK),
Admission DoctorID (FK), AdmitDate, DischargeDate, Status
TreatmentID (PK), AdmissionID (FK), TreatmentDate,
Treatment Description, Medication, Notes
BillID (PK), AdmissionID (FK), BillingDate, Amount, Paid,
Bill DueDate

Key Attribute Types:


• Primary Key: Unique identifier such as PatientID, AdmissionID
• Foreign Key: References linking related records

Relationships & Cardinalities:


• Patient–Admission: One patient can have multiple admissions, each related to the
patient (1:M).
• Doctor–Admission: Each admission is managed by one doctor; a doctor can supervise
many admissions (1:M).
• Department–Admission: Each admission is assigned to one department; a department
has many admissions (1:M).
• Admission–Treatment: Each admission can have multiple treatments (1:M).
• Admission–Bill: Each admission has one bill; each bill relates to one admission (1:1).
• Doctor–Department: Each doctor belongs to one department (M:1).

Description of ER Diagram:
• Entities: Patient, Doctor, Department, Admission, Treatment, Bill
• Attributes: Each listed above; PKs underlined, FKs marked
• Relationships:
• Patient (1) – (M) Admission
• Admission (1) – (M) Treatment
• Admission (1) – (1) Bill
• Department (1) – (M) Admission, (1) – (M) Doctor
• Doctor (1) – (M) Admission
ER Diagram:
3. Converting ER Model to Relational Model (Represent entities and
relationships in Tabular form, Represent attributes as columns,
identifying keys)

Experiment 3: ER to Relational Model Conversion


Aim: Generate normalized relational tables with appropriate keys and constraints.
Table Attributes & Data Types Primary Key Foreign Keys
PatientID INT, Name VARCHAR(100),
Gender CHAR(1), DOB DATE, Address
VARCHAR(200), Phone VARCHAR(15),
Email VARCHAR(100) UNIQUE,
BloodGroup VARCHAR(5),
Patient RegistrationDate DATE PatientID –
DoctorID INT, Name VARCHAR(100),
Specialty VARCHAR(50), Phone
VARCHAR(15), Email VARCHAR(100)
UNIQUE, DepartmentID INT, HireDate DepartmentID →
Doctor DATE DoctorID Department.DepartmentID
DepartmentID INT, DepartmentName
VARCHAR(50), Floor INT, Phone
Department VARCHAR(15) DepartmentID –
PatientID→Patient.PatientID
AdmissionID INT, PatientID INT, ,
DepartmentID INT, DoctorID INT, DepartmentID→Departmen
AdmitDate DATE, DischargeDate DATE, t.DepartmentID,
Admission Status VARCHAR(20) AdmissionID DoctorID→Doctor.DoctorID
TreatmentID INT, AdmissionID INT,
TreatmentDate DATE, Description
VARCHAR(150), Medication AdmissionID→Admission.A
Treatment VARCHAR(150), Notes VARCHAR(200) TreatmentID dmissionID
BillID INT, AdmissionID INT, BillingDate
DATE, Amount DECIMAL(10,2), Paid AdmissionID→Admission.A
Bill BOOLEAN, DueDate DATE BillID dm
Sample Tables:
Department Table
4. Normalization -To remove the redundancies and anomalies in the
above relational tables, Normalize up to Third Normal Form.

Aim: Remove redundancies and anomalies by normalizing tables to 3NF

Theory: Apply 1NF (atomic values), 2NF (no partial dependencies), 3NF (no transitive
dependencies).

Original (UNF):

• 1NF (Atomic Values, Filled): Split repeating groups into rows.


• 2NF (Remove Partial Dependencies, Filled): Separate into tables.
• 3NF (Remove Transitive Dependencies, Filled): Ensure no non-key dependencies.

Normalized Tables: Doctor Table


5. Creation of Tables using SQL- Overview of using SQL tool, Data types
in SQL, Creating Tables (along with Primary and Foreign keys),
Altering Tables and Dropping Tables.

Aim: Create tables with data types, primary keys, foreign keys, altering, and dropping.

Theory: Use CREATE TABLE with constraints; ALTER and DROP for modifications.

Overview of SQL Tool:


SQL (Structured Query Language) is used to create and manipulate relational databases.
Popular SQL tools include:
• MySQL Workbench
• Oracle SQL Developer
• SQLite
• pgAdmin (PostgreSQL)
• Command-line MySQL/MariaDB

Creating Tables with Primary and Foreign Keys:

-- Create Department Table


CREATE TABLE Department (
DepartmentID INT PRIMARY KEY,
DeptName VARCHAR(100) NOT NULL,
Location VARCHAR(100)
);

-- Create Doctor Table


CREATE TABLE Doctor (
DoctorID INT PRIMARY KEY,
FirstName VARCHAR(100),
LastName VARCHAR(100),
Specialization VARCHAR(100),
DepartmentID INT,
ContactNumber VARCHAR(15),
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
-- Create Patient Table
CREATE TABLE Patient (
PatientID INT PRIMARY KEY,
FirstName VARCHAR(100),
LastName VARCHAR(100),
DOB DATE,
Gender VARCHAR(10),
Address VARCHAR(200),
Phone VARCHAR(20),
InsuranceInfo VARCHAR(200)
);

-- Insert Sample Data into Department


INSERT INTO Department VALUES
(1, 'Cardiology', '3rd Floor'),
(2, 'Neurology', '4th Floor');

-- Insert Sample Data into Doctor


INSERT INTO Doctor VALUES
(101, 'John', 'Smith', 'Cardiologist', 1, '9876543210'),
(102, 'Emily', 'Johnson', 'Neurologist', 2, '8765432109');

-- Insert Sample Data into Patient


INSERT INTO Patient VALUES
(201, 'Alice', 'Brown', '1985-06-12', 'Female', '123 Main St', '7894561230', 'BlueCross'),
(202, 'Bob', 'Smith', '1978-11-01', 'Male', '456 Oak Ave', '9871234560', 'MediCare');

-- Alter Patient Table (Add Email Column)


ALTER TABLE Patient ADD Email VARCHAR(100);

-- Drop Patient Table (Example - Use with Caution)


DROP TABLE Patient;
6. Practicing DML commands- Insert, Select, Update, Delete.’

Aim: Practice data manipulation: INSERT, SELECT, UPDATE, DELETE

Theory: DML modifies table data.

SQL Queries with Filled Data:

INSERT:

INSERT INTO Department VALUES (1, 'Cardiology', '3rd Floor');


INSERT INTO Doctor VALUES (101, 'John', 'Smith', 'Cardiologist', 1, '9876543210');
INSERT INTO Patient VALUES (201, 'Alice', 'Brown', '1985-06-12', 'Female', '123 Main St',
'7894561230', 'BlueCross');

SELECT:

SELECT * FROM Patient;

Sample Filled Output Table (After INSERT - Patient):

UPDATE:

UPDATE Patient SET Phone = '9871234560' WHERE PatientID = 201;

DELETE:

DELETE FROM Patient WHERE PatientID = 201;


7. Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS,
UNION, INTERSECT, CONSTRAINTS etc.

Experiment 7: Advanced SQL Queries and Constraints

Objective:
Practice advanced SQL features:
• ANY, ALL
• IN, EXISTS, NOT EXISTS
• UNION, INTERSECT
• Use of CONSTRAINTS like UNIQUE, CHECK, DEFAULT, etc.

SQL Queries with Constraints and Filled Data:

CREATE TABLE Patient (


PatientID INT PRIMARY KEY,
Gender VARCHAR(10) CHECK (Gender IN ('Male', 'Female', 'Other'))
);
INSERT INTO Patient VALUES (201, 'Female'), (202, 'Male');

ANY/ALL Example:

SELECT PatientID FROM Billing WHERE Amount > ANY (SELECT Amount FROM Billing WHERE
Status = 'Unpaid');

IN/EXISTS Example:

SELECT FirstName FROM Patient WHERE EXISTS (SELECT 1 FROM Appointment WHERE
Appointment.PatientID = Patient.PatientID);

UNION/INTERSECT Example:

SELECT FirstName FROM Patient WHERE Gender = 'Female' UNION SELECT FirstName FROM Patient
WHERE InsuranceInfo IS NOT NULL;

Sample Filled Table (Billing):


8. Practicing Sub queries (Nested, Correlated) and Joins (Inner, Outer
and Equi).

Objective
To understand and practice:

• Nested and Correlated Subqueries


• INNER JOIN
• LEFT / RIGHT OUTER JOIN
• EQUI JOIN

Nested Subquery Example:

SELECT PatientID FROM Patient WHERE PatientID IN (SELECT PatientID FROM Billing
WHERE Amount > 10000);

Correlated Subquery Example:

SELECT p1.FirstName FROM Patient p1 WHERE Amount = (SELECT MAX(p2.Amount) FROM Billing
p2 WHERE p1.PatientID = p2.PatientID);

Inner Join Example:

SELECT p.FirstName, d.FirstName AS DocName FROM Appointment a JOIN Patient p ON


a.PatientID = p.PatientID JOIN Doctor d ON a.DoctorID = d.DoctorID;

Sample Filled Output Table (Join):


9. Practice Queries using COUNT, SUM, AVG, MAX, MIN, GROUP BY,
HAVING, VIEWS Creation and Dropping.

Aim: To practice using SQL aggregate functions, grouping data, and creating/managing
views in a Hospital Management System database

Theory: Aggregate functions perform calculations on a set of rows and return a single
summary value. GROUP BY is used with aggregate functions to group rows that have the
same values in specified columns. HAVING filters these groups based on a
condition. VIEWS are virtual tables based on the result-set of an SQL statement, which
can simplify complex queries.

SQL Setup and Queries:


This script sets up the necessary tables and then demonstrates each function.

-- Setup: Create and Populate Tables


CREATE TABLE Department (
DepartmentID INT PRIMARY KEY,
DeptName VARCHAR(100) NOT NULL
);

CREATE TABLE Doctor (


DoctorID INT PRIMARY KEY,
FirstName VARCHAR(100),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);

CREATE TABLE Patient (


PatientID INT PRIMARY KEY,
FirstName VARCHAR(100),
Age INT
);

CREATE TABLE Appointment (


AppointmentID INT PRIMARY KEY,
PatientID INT,
DoctorID INT,
AppointmentDate DATE,
FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
FOREIGN KEY (DoctorID) REFERENCES Doctor(DoctorID)
);

CREATE TABLE Billing (


BillID INT PRIMARY KEY,
PatientID INT,
Amount DECIMAL(10, 2),
BillDate DATE,
Status VARCHAR(50),
FOREIGN KEY (PatientID) REFERENCES Patient(PatientID)
);

-- Insert Sample Data


INSERT INTO Department VALUES (1, 'Cardiology'), (2, 'Neurology'), (3, 'Orthopedics');
INSERT INTO Doctor VALUES (101, 'John', 1), (102, 'Emily', 2), (103, 'Michael', 1);
INSERT INTO Patient VALUES (201, 'Alice', 45), (202, 'Bob', 52), (203, 'Charlie', 38), (204, 'David',
65);
INSERT INTO Appointment VALUES (1, 201, 101, '2025-07-20'), (2, 202, 102, '2025-07-21'), (3, 203,
101, '2025-07-22');
INSERT INTO Billing VALUES (1, 201, 5000.00, '2025-07-20', 'Paid'), (2, 202, 7500.00, '2025-07-21',
'Unpaid'), (3, 203, 4500.00, '2025-07-22', 'Paid'), (4, 204, 12000.00, '2025-07-23', 'Paid');

-- 1. Aggregate Functions: COUNT, SUM, AVG, MAX, MIN


-- Count total patients
SELECT COUNT(*) AS TotalPatients FROM Patient;

-- Calculate total revenue from all bills


SELECT SUM(Amount) AS TotalRevenue FROM Billing;

-- Find the average billing amount


SELECT AVG(Amount) AS AverageBillAmount FROM Billing;

-- Find the highest and lowest billing amounts


SELECT MAX(Amount) AS HighestBill, MIN(Amount) AS LowestBill FROM Billing;

-- 2. GROUP BY: Group results based on a column


-- Count the number of doctors in each department
SELECT DepartmentID, COUNT(DoctorID) AS NumberOfDoctors
FROM Doctor
GROUP BY DepartmentID;

-- 3. HAVING: Filter grouped results


-- Find departments with more than one doctor
SELECT DepartmentID, COUNT(DoctorID) AS NumberOfDoctors
FROM Doctor
GROUP BY DepartmentID
HAVING COUNT(DoctorID) > 1;

-- 4. VIEWS: Create, use, and drop a virtual table


-- Create a view for high-value paid bills
CREATE VIEW HighValueBills AS
SELECT PatientID, Amount, BillDate
FROM Billing
WHERE Amount > 5000 AND Status = 'Paid';

-- Select data from the view


SELECT * FROM HighValueBills;

-- Drop the view


DROP VIEW HighValueBills;
Final Output Tables:

Aggregate Functions Output


10. Practicing on Triggers - creation of trigger, Insertion using
trigger,

Aim: To understand and implement SQL triggers for INSERT, UPDATE,


and DELETE operations to maintain an audit trail for a Hospital Management System.
Theory: A trigger is a stored procedure in a database that automatically executes when a
specific event occurs in a database table (e.g., an INSERT, UPDATE, or DELETE).
Triggers are often used to maintain data integrity or to create an audit log of changes.
SQL Setup and Queries:
This script creates a main table (Admission) and an audit table (Admission_Audit). It
then defines triggers to log all DML actions performed on the Admission table.
-- Step 1: Create Tables
-- Main table to track patient admissions
CREATE TABLE Admission (
AdmissionID INT PRIMARY KEY,
PatientID INT,
RoomNumber VARCHAR(10),
AdmissionDate DATE
);

-- Audit table to log all changes to the Admission table


CREATE TABLE Admission_Audit (
AuditID INT AUTO_INCREMENT PRIMARY KEY,
ActionType VARCHAR(10),
AdmissionID INT,
PatientID INT,
RoomNumber VARCHAR(10),
ActionTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Step 2: Trigger for INSERT


-- This trigger logs a new record in Admission_Audit after an admission is created.
DELIMITER $$
CREATE TRIGGER trg_after_admission_insert
AFTER INSERT ON Admission
FOR EACH ROW
BEGIN
INSERT INTO Admission_Audit (ActionType, AdmissionID, PatientID, RoomNumber)
VALUES ('INSERT', NEW.AdmissionID, NEW.PatientID, NEW.RoomNumber);
END$$
DELIMITER ;

-- Step 3: Trigger for UPDATE


-- This trigger logs a new record when an admission record is updated.
DELIMITER $$
CREATE TRIGGER trg_after_admission_update
AFTER UPDATE ON Admission
FOR EACH ROW
BEGIN
INSERT INTO Admission_Audit (ActionType, AdmissionID, PatientID, RoomNumber)
VALUES ('UPDATE', NEW.AdmissionID, NEW.PatientID, NEW.RoomNumber);
END$$
DELIMITER ;

-- Step 4: Trigger for DELETE


-- This trigger logs a new record when an admission record is deleted.
DELIMITER $$
CREATE TRIGGER trg_after_admission_delete
AFTER DELETE ON Admission
FOR EACH ROW
BEGIN
INSERT INTO Admission_Audit (ActionType, AdmissionID, PatientID, RoomNumber)
VALUES ('DELETE', OLD.AdmissionID, OLD.PatientID, OLD.RoomNumber);
END$$
DELIMITER ;

-- Step 5: Demonstrate the Triggers


-- Insert new admissions (this will fire the INSERT trigger)
INSERT INTO Admission VALUES (1, 201, '101A', '2025-08-01');
INSERT INTO Admission VALUES (2, 202, '102B', '2025-08-02');

-- Update an admission record (this will fire the UPDATE trigger)


UPDATE Admission SET RoomNumber = '105C' WHERE AdmissionID = 2;

-- Delete an admission record (this will fire the DELETE trigger)


DELETE FROM Admission WHERE AdmissionID = 1;

-- Final check of the tables


SELECT * FROM Admission;
SELECT * FROM Admission_Audit;

Final Output Tables:

You might also like