0% found this document useful (0 votes)
3 views

dbmsfile.pdf (1)

The document provides an overview of databases, focusing on relational database systems and SQL queries. It covers various aspects such as database creation, data definition language (DDL), data manipulation language (DML), and the implementation of nested and join queries. Additionally, it includes case studies and practical experiments to illustrate the concepts discussed.

Uploaded by

48 Uma shankar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

dbmsfile.pdf (1)

The document provides an overview of databases, focusing on relational database systems and SQL queries. It covers various aspects such as database creation, data definition language (DDL), data manipulation language (DML), and the implementation of nested and join queries. Additionally, it includes case studies and practical experiments to illustrate the concepts discussed.

Uploaded by

48 Uma shankar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

INDEX

S No. Topic Date Sign

1 Introduction to database.

2 Various types of relational database systems.

3 Creation of a Database and writing SQL queries to retrieve information


from the database.

To implement Data Definition Language:(DDL)


4
To implement Data Manipulation Language:(DML)
5

6 To implement nested queries and join queries

7 To implement views.

8 To implement aggregate functions, string functions, numeric functions and


date functions.

Case Study 1: Hospital Management System – ER diagram and SǪL queries


9

10 Case Study 2: Railways Management System – ER diagram and SQL


queries

11 Case Study 3: Library Management System – ER diagram and SQL


queries
Case Study 4: University Management System – ER diagram and SQL
12
queries
Case Study 5: Airway Reservation System – ER diagram and SQL queries
13

2
Experiment – 1

OBJECTIVE: Introduction to Database.


Theory:
What is a
Database?
A database is a structured collection of data that is organized and stored electronically. Databas
are essential in various applications, such as business, healthcare, finance, and education, for
efficient data management and retrieval.
Components of a Database System:

Data: The information stored in a database.

Database Management System (DBMS): Software that manages and facilitates access to
the database.

Users: Individuals or applications that interact with the database.

Database Application: Software applications that utilize the database to perform specific
tasks.

Types of Databases:
There are different types of databases, including:

Relational Databases: Organize data into tables with rows and columns, and establish
relationships between tables.

NoSQL Databases: Designed for flexible and scalable data storage, suitable for
unstructured or semi-structured data.

Object-Oriented Databases: Store data as objects, with attributes and methods.

Graph Databases: Represent data as graphs with nodes, edges, and properties.
Database Management System: The software which is used to manage databases iscalled Datab
Management System (DBMS). For Example, MySQL, Oracle, etc. are popular commercial
DBMS used in different applications. DBMS allows users the following tasks:

Data Definition: It helps in the creation, modification, and removal of definitions that
define the organization of data in the database.

Data Updating: It helps in the insertion, modification, and deletion of the actual data in the
database.

Data Retrieval: It helps in the retrieval of data from the database which can be used by
applications for various purposes.

User Administration: It helps in registering and monitoring users, enforcing data securit
monitoring performance, maintaining data integrity, dealing with concurrency control, a
recovering information corrupted by unexpected failure.

Why Use DBMS?



To develop software applications in less time.
➢ Data independence and efficientuse of data.
For uniform data administration.
➢ For data integrity and security.
For concurrent access to data, and data recovery
➢ from crashes. To use user-friendly declarative
query language.
Advantages
➢ of DBMS

A DBMS manages data and has many benefits. These are:




Data independence: Application programs should be as free or independent as possible
from details of data representation and storage. DBMS can supply an abstract view of
the data for insulating application code from such facts.

Efficient data access: DBMS utilizes a mixture of sophisticated concepts and
techniques for storing and retrieving data competently. This feature becomes
important in cases where the data is stored on external storage devices.

Data integrity and security: If data is accessed through the DBMS, the DBMS canenforce
integrity constraints on the data.

Data administration: When several users share the data, integrating the administration of
data can offer significant improvements. Experienced professionals understand the
Where
natureisofa the
Database Management
data being managedSystem
and can(DBMS) being Used
be responsible for organizing the data
representation to reduce redundancy and makethe data retrieve efficiently.

?

Social Media: User Profile Databases, Content Recommendation Systems, Social
NetworkAnalysis

Real Estate: Property Management Systems, Real Estate Listings Databases, Tenant and
Lease Management
CONCLUSION / LEARNING:

Universities:
Learned aboutregistration,
the differentresults,
types ofgrades
database and features of database management system.

Sales: products, purchases, customers
Experiment –

2 OBJECTIVE:Various types of relational database systems.

Theory:

RDBMS is a type of DBMS that organizes data in a tabular format with relationships between
tables, while DBMS can use different data organization models and may notenforce strict
relationships between data entities.
In an RDBMS, data is stored in tables, where each table represents a specific entity orconcept.
The tables consist of rows (also known as tuple in RDBMS or records) that represent individual
instances of the entity, and columns that define the attributes or properties of the entity.
The relational model facilitates the establishment of relationships between tables throughkeys.
primary key uniquely identifies each row in a table, while foreign keys establish relationships
between tables by referencing the primary key of another table.

Types of RDBMS (Relational Database Management Systems)


Some of the examples of relational database are:
1. Oracle Database: Oracle Database is a widely used RDBMS known for its scalability,
security, and comprehensive feature set. It offers robust support fordata management,
high availability, and advanced analytics capabilities.
2. MySǪL: MySǪL is a popular open-source RDBMS that is known for its simplicity,speed,
and ease of use. It is widely used in web applications and is known for its scalability,
reliability, and compatibility with various platforms.
3. SǪL Server: Microsoft SǪL Server is a powerful RDBMS developed by Microsoft. Itoffers a
wide range of features, including advanced security, business intelligence tools, and
integration with other Microsoft products and technologies.
4. PostgreSǪL: PostgreSǪL is a feature-rich open-source RDBMS known for its extensibility
and compliance with industry standards. It offers a strong emphasis ondata integrity,
reliability, and support for advanced SǪL features.
5. Azure SǪL: Azure SǪL is a cloud-based relational database service provided byMicrosoft
Azure. It is based on the popular Microsoft SǪL Server database engineand offers a scalable,
secure, and managed platform for hosting and managing relational databases in the cloud.
6. Microsoft Access: Microsoft Access is a relational database management system
(RDBMS) developed by Microsoft. It is primarily designed for small-scale database
applications, allowing users to create and manage databases withoutrequiring extensive
programming knowledge.

Advantages of Relational Database Management System



Data Organization: RDBMS organizes data into tables, rows, and columns, providinga
structured and logical approach to data storage. This allows for efficient data retrieval an
manipulation.

Data Integrity: RDBMS enforces data integrity through constraints and rules. Primary keys,
foreign keys, and other constraints ensure that data is accurate andconsistent, preventing
data inconsistencies or errors.

Data Relationships: RDBMS supports relationships between tables, enabling the
establishment of connections and associations between related data. This facilitates
data analysis, reporting, and querying across multiple tables.

Querying and Reporting: RDBMS provides a standardized query language, such as SǪL,
which allows users to easily retrieve, filter, and analyze data. SǪL's powerful capabilities
enable complex queries, aggregations, sorting, and joining of data frommultiple tables.

Scalability: RDBMS systems can handle large amounts of data and scale
horizontally by distributing data across multiple servers. This enables efficient
management of growing datasets and accommodates increased workload demands.

Security: RDBMS offers robust security features to protect data. Access controls,user
authentication, and encryption mechanisms ensure that only authorized users can access and
modify the data, safeguarding sensitive information.
Features of RDBMS
RDBMS offer a wide range of features that make them suitable for storing, managing, andmanip
structured data. Here are some key features of RDBMS:

Atomicity in RDBMS refers to one of the ACID properties that ensures that a database
transaction is treated as a single indivisible unit of work. Atomicity guarantees that
either all the changes made within a transaction are committed tothe database, or none of
them are.

Consistency in RDBMS refers to one of the ACID properties that ensures the database
remains in a valid and expected state before and after the execution of atransaction. It
guarantees that data meets all predefined rules, constraints, andrelationships defined in
the database schema. Consistency ensures that any changes made to the database during
a transaction preserve these integrity constraints and do not violate any defined rules.

Isolation refers to one of the ACID properties that ensures transactions are executed in
isolation from each other. It guarantees that concurrent transactions donot interfere with
CONCLUSION / LEARNING:
each other, and that each transaction sees a consistent and isolated view of the data.
Learned about the different types and features of Relational Database Systems.

Durability in RDBMS refers to one of the ACID properties that ensures that once a
transaction is committed, its effects are permanently stored and will survive any
subsequent failures, such as power outages, system crashes, or other catastrophicevents.
Experiment – 3
OBJECTIVE:
Creation of a Database and writing SQL queries to retrieve information from the
database.
Theory:
Creating a database involves the following steps:
1. Define the structure of the database, including the tables, columns, data types, and
relationships between tables.
2. Create the database using a database management system (DBMS) such asMySǪL,
PostgreSǪL or SǪL Server.
3. Populate the tables with data.

Once the database has been created, you can write SǪL queries to retrieve informationfrom it.
Some common SǪL queries include:
1. SELECT - statement is used to select data from a database. Example: SELECT *FROM
customers;
2. WHERE - It is used to extract only those records that fulfill a specified condition.
Example: SELECT * FROM customers WHERE country = ‘Mexico’;
3. DELETE - statement is used to delete existing records in a table.
4. OR - operator is used to filter records based on more than one condition, like if youwant to
return all customers from Germany but also those from Spain
5. BETWEEN - operator selects values within a given range. The values can be
numbers, text, or dates.

Code

--Database Creation:
CREATE DATABASE CompanyDB;
USE CompanyDB;
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- Inserting Data:

INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary)


VALUES (1, 'John', 'Doe', 'IT', 50000.00),
(2, 'Jane', 'Smith', 'HR', 45000.00),
(3, 'Michael', 'Johnson', 'Finance', 55000.00);
SELECT * FROM Employees;

-- SQL Queries:

SELECT * FROM Employees WHERE Salary > 50000.00;

CONCLUSION / LEARNING:
After this experiment, we learnt the different commands in SǪL.
Experiment –

4 OBJECTIVE:
To implement Data Definition Language (DDL)

1. Create, Alter, Drop, Truncate


2. To implement constraints:
2.1) Primary Key

2.2) Foreign Key

2.3) Check

2.4) Unique

2.5) Null and not Null

2.6) Default

Theory:
DDL Statements

DDL or Data Definition Language consists of the SǪL commands that can be used
to define the database schema. It simply deals with descriptions of the database
schema and is used to create and modify the structure of database objects in the
database.
1) CREATE

Used to create a Table in the database.

2) DROP Table

It is used to remove an existing table from the database.

3) ALTER Table

It is used to for altering the table structure, such as, to add a column to existing
table, to rename any existing column, to change datatype of any column or to
modify its size and to drop a column from the table.

4) RENAME

Table Using ALTER command, we can rename an existing column of a table.

5) PRIMARY KEY
A column is called primary key (PK) that uniquely identifies each row in the table.

6) FOREIGN KEY

In the relational databases, a foreign key is a field or a column that is used to


establish a link between two tables.
7) DEFAULT

The DEFAULT constraint is used to set a default value for a column.


8) UNIǪUE

The UNIǪUE constraint ensures that all values in a column are different.

9) NOT NULL AND NULL

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to
NOT
accept NULL values.

10) CHECK

The CHECK constraint is used to limit the value range that can be placed in acolumn.

Code:
1. Create
CREATE TABLE STUDENTS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)

);

2. Alter & Rename


• ALTER TABLE student
RENAME COLUMN DateOfBirth to DOB;

• ALTER TABLE
studentsDROP COLUMN
DOB;
3. Drop
DROP TABLE students;

4. Implementation of Primary Key, Check, NOT NULL, unique, default

CREATE TABLE Persons ( ID


int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY(ID)
CHECK (Age>=18)

);

• ALTER TABLE Persons


ALTER LastName SET DEFAULT 'xyz';

• ALTER TABLE Persons


ADD UNIQUE (ID);

Primary key/ unique use output:

Default use output:

Check condition output:


INSERT INTO persons(ID, FirstName, Age)VALUES
(3, 'ajay', 17);
Discussion:

DDL commands are essential for managing the structure of databases. This experiment
demonstrates how to create, alter, drop, and truncate tables using DDL commands.

Finding & Learning:


- Learned how to use DDL commands for database management.

- Understood the significance of DDL in database administration.


Experiment – 5

OBJECTIVE:
To implement Data Manipulation Language:(DML)

1 Select
. Insert
2 Update
. Delete
3
.
Theory:
4
DML. Statements

Data Manipulation Language (DML) commands are used for managing data in database.DML
commands are not auto-committed which means the changes made by DML command are no
permanent to database and can be rolled back.

• SELECT

It is used to retrieve data from the database.

• INSERT

It is used to insert data into the table.

• UPDATE

It is used to update the existing data from the database.

• DELETE

It is used to delete any existing record from the table.

Code & Output:


• SELECT * FROM persons;
• INSERT INTO persons (ID,LastName,FirstName,Age) VALUES (4, 'Sharma2',
'Rahul2', 20);
• UPDATE persons
SET FirstName =
'ajay'WHERE Age = 20;

• DELETE FROM
persons WHERE
Age=20;

Discussion

DML commands are crucial for manipulating data in a database. This experiment
demonstrates how to insert, select, update, and delete data using DML commands.

Learning/ Conclusion
In this experiment, we learnt about Data Manipulation Language (DML) commands. We
implemented the commands- created tables, added columns, inserted data, updated data, dele
rows, dropped tables etc.
Experiment – 6

OBJECTIVE:
To implement nested queries and join queries

1 implementation of nested queries

) implementation of natural join, inner join, left join, full join

2
Theory:
) 1) Nested queries, also known as subqueries, are queries that are embedded within the
context of another SQL query. They can be used in various places within a SQLstatement,
including the ̀`WHERE`, ̀`HAVING`, and ̀`FROM` clauses, and even within another
subquery.

Nested queries can be very powerful, but they can also be more complex
and harder to understand than equivalent queries that use joins. They
can also be slower, especially if the inner query returns a large number of
rows, because thedatabase may need to execute the inner query once for
each row returned by the outer query. However, in many cases, the
database can optimize the query to avoidthis.

2) In SQL, a JOIN operation combines rows from two or more tables based on a relatedcolum
between them. Here are the different types of joins:

1. INNER JOIN: The INNER JOIN keyword selects records that have
matching valuesin both tables.

2. LEFT (OUTER) JOIN: The LEFT JOIN keyword returns all records from the left table
(table1), and the matched records from the right table (table2). The result is NULL on the
right side, if there is no match.

3. RIGHT (OUTER) JOIN: The RIGHT JOIN keyword returns all records from
the righttable (table2), and the matched records from the left table
(table1). The result is NULL on the left side, when there is no match.
4. FULL (OUTER) JOIN: The FULL OUTER JOIN keyword returns all records
when thereis a match in either left (table1) or right (table2) table records.

Code:

1) Nested Ǫuery –
SELECT OrderID, Product
FROM Orders
WHERE CustomerID IN (
SELECT CustomerID
FROM Customers
WHERE CustomerName = 'Rahul'

);

Output:

2)Joins -

1. Natural Join-
SELECT *
FROM Orders
NATURAL JOIN Customers
Output:

2. Inner Join-
SELECT Orders.OrderID, Customers.CustomerName,Orders.Product
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Output:

3. Left Join-
SELECT Customers. CustomerID, Customers. CustomerName,
Orders.Product
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID

Output:

4. Full Join-

SELECT Orders.OrderID, Customers.CustomerName,Orders.Product


FROM Orders
LEFT JOIN Customers ON Orders.CustomerID =Customers.CustomerID
UNION
SELECT Orders.OrderID, Customers.CustomerName,Orders.Product
FROM Orders
RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Output:

Learning Outcome:

The use cases for Joins are,

1. Retrieving Related Data: One of the primary use cases for joins is to retrieve related data
stored across multiple tables. For example, in a database containing separate tables for
"customers" and "orders," a join operation can be used to retrieve a list ofcustomers along
with their corresponding orders.
2. Creating Reports: Joins are frequently used to generate comprehensive reports by combinin
data from multiple tables. For instance, in a database containing tables for "employees" and
"departments," a join operation can be employed to generate areport showing employee
details along with the department they belong to.
3. Filtering Data: Joins can be used to filter data based on conditions specified in thejoin
predicate. For example, an inner join can be used to retrieve only those rows where a match
is found in both tables, effectively filtering out unmatched rows.
4. Aggregating Data: Joins can also be used in conjunction with aggregate functions (e.g., SUM,
AVG, COUNT) to perform calculations on combined data from multiple tables. For
instance, joining tables containing "sales" and "products" data allows forcalculating total
sales for each product.
Experiment – 7

OBJECTIVE:
To implement views.
Theory:

In SQL, a view is a virtual table generated by a stored query. It behaves like a table in that it can
queried, updated, inserted into, or deleted from, but it doesn't store the data itself; instead, it d
retrieves the data from the underlying tables each time it's queried. Views offer several advant
including simplified querying, data abstraction, and enhanced security.
Here are examples of creating different types of views:

1. Simple View: A simple view is based on one table only.


2. Complex View: A complex view is based on more than one table.

3. Updateable View: An updateable view lets you update data in the underlying tables. Not all v
are updateable. To be updateable, a view cannot contain any of the following constructs: a GRO
BY clause, a DISTINCT clause, etc.

Code:
1. Simple View-

CREATE VIEW SimpleView AS

SELECT CustomerName, Product


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Output:
2. Complex View-

CREATE VIEW ComplexView AS

SELECT Customers.CustomerName, Orders.Product,

Orders.OrderID FROM Customers

INNER JOIN Orders ON Customers.CustomerID =

Orders.CustomerID;
Output:

3. Updateable View-

CREATE VIEW UpdateableView AS

SELECT CustomerName, CustomerID

FROM Customers;

Output:

-> Updating/Deleting from view

CREATE VIEW CustomerOrders AS

SELECT Customers.CustomerName, Orders.Product FROM


Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
-- updating
DROP VIEW CustomerOrders; // important to drop to create new view
CREATE VIEW CustomerOrders AS
SELECT Customers.CustomerName, Orders.OrderID FROM
Customers

INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

// inserting the data


INSERT INTO Orders (OrderID, CustomerID, Product) VALUES (4, 1, 'Grapes');
:
Output

Learning Outcome:

i. Data Security and Access Control: Views are often used to restrict access to sensitive data
by granting users access only to specific columns or rows of a table
ii. Simplifying Complex Queries: Views can simplify complex SQL queries by encapsulating
them into a single, easy-to-use entity. This is particularly useful when dealing with multiple
joins, aggregations, or calculations.
iii. Data Abstraction and Virtualization: Views provide a layer of abstraction over the
underlying database schema, allowing users to interact with the data without needing to
understand its complex structure. This abstraction simplifies application development and
maintenance. For instance, a web application may use views to fetch data for display
without directly accessing the underlying tables.
Experiment – 8

OBJECTIVE:
To implement aggregate functions, string functions, numeric functions and date
functions

Theory:

1. Aggregate Functions: Aggregate functions perform a calculation on a set of


values and return a single value.

2. String Functions: String functions are used to manipulate a string or to

change the way the


3.string is displayed.
Numeric Functions: Numeric functions are used to perform operations on numbers.

4. Date Functions: Date functions are used to perform operations on date data types.

Code:
1. Aggregate functions:
a. SELECT COUNT(OrderID) AS NumberOfOrders FROM Orders;

b. SELECT AVG(Price) AS AveragePrice FROM Orders;

c.SELECT MAX(Price) AS HighestPrice FROM orders;


d. SELECT SUM(Price) AS TotalPrice FROM Orders;

2. String Functions:
a. SELECT UPPER(CustomerName) AS CustomerName FROM Customers;

b. SELECT LOWER(CustomerName) AS CustomerName FROM Customers;

c. SELECT LENGTH(CustomerName) AS NameLength FROM Customers;


3. Numeric Functions:
a. SELECT ROUND (Price, 1) AS RoundedPrice FROM Orders;

b. SELECT CEIL(Price) AS RoundedUpPrice FROM Orders;

c. SELECT FLOOR(Price) AS RoundedDownPrice FROM Orders;

4. Date functions:
a. SELECT DATE(OrderDate) AS OrderDate FROM Orders;
b. SELECT YEAR(OrderDate) AS OrderYear FROM Orders;

c. SELECT DATE_ADD(OrderDate, INTERVAL 5 DAY) AS NewDate


FROM Orders;

Learning Outcome:

Practical Use cases of the above functions

1. Financial Analysis:
1) Aggregate functions like SUM and AVG are used to calculate total sales, average
revenue, or total expenses.
2) Numeric functions such as ROUND and ABS are employed for financial calculations,
like rounding off currency values or finding the absolute difference between two values.
3) Date functions are used for analyzing trends over time, calculating interest rates, or
determining payment due dates.
2. E-commerce:
1) String functions are used for manipulating product names, descriptions, or URLs.
2) Aggregate functions help in analyzing sales data to identify popular products, average
order value, or total revenue.
3) Date functions are used for tracking order fulfillment times, analyzing customer behavior
over time, or managing promotional campaigns based on specific dates.
Experiment –

:9Hospital
Case Study
Management System – ER diagram and SǪL queries

:1The hospital has various departments including Orthopedic, Pathology, Emergency,


Dental, Gynecology, etc. Patients visit the Outpatient Department (OPD) to getacard for their
Description
checkup. After examination, the doctor prescribes medicine or admits the patient. Patients can
choose between private or general rooms. Admission requires completing formalities like room
charges. Upon treatment completion, patients are discharged after settling bills. Doctors are
either regular or on-call, with the latter summoned when needed.

ER Diagram:

SǪL
: queries for tables
-- Creating the DEPARTMENT
tableCREATE TABLE
DEPARTMENT (
DepartmentName VARCHAR(255) PRIMARY
KEY,DepartmentLocation VARCHAR(255),
Facilities VARCHAR(255)
);

-- Creating the ALL_DOCTORS


table CREATE TABLE
ALL_DOCTORS (

IdentityNumber VARCHAR(255) PRIMARY


KEY,DepartmentName VARCHAR(255),
FOREIGN KEY (DepartmentName) REFERENCES DEPARTMENT(DepartmentName)

);

-- Creating the DOC_REG


tableCREATE TABLE
DOC_REG (
DoctorNumber VARCHAR(255) PRIMARY
KEY,Name VARCHAR(255),
Ǫualification VARCHAR(255),
Address VARCHAR(255),
PhoneNumber VARCHAR(15),
Salary DECIMAL(10, 2),
DateOfJoining DATE,

FOREIGN KEY (DoctorNumber) REFERENCES ALL_DOCTORS(IdentityNumber)

);
-- Creating the DOC_ON_CALL
tableCREATE TABLE

DOC_ON_CALL (
DoctorNumber VARCHAR(255) PRIMARY
KEY,Name VARCHAR(255),
Ǫualification VARCHAR(255),
FeesPerCall DECIMAL(10, 2),
PaymentDue DECIMAL(10, 2),
Address VARCHAR(255),
PhoneNumber VARCHAR(15),
FOREIGN KEY (DoctorNumber) REFERENCES ALL_DOCTORS(IdentityNumber)

);

-- Creating the PAT_ENTRY table


CREATE TABLE PAT_ENTRY (
PatientNumber INT PRIMARY
KEY,Name VARCHAR(255),
Age INT,
Sex CHAR(1),
Address
VARCHAR(255),City
VARCHAR(255),
PhoneNumber
VARCHAR(15), EntryDate

DATE, DoctorReferred
VARCHAR(255),Diagnosis
VARCHAR(255),
DepartmentName VARCHAR(255),
FOREIGN KEY (DepartmentName) REFERENCES DEPARTMENT(DepartmentName)

);

- Creating the PAT_CHKUP table


CREATE TABLE PAT_CHKUP (
PatientNumber INT PRIMARY
KEY,DoctorNumber
VARCHAR(255),
CheckupDate DATE,
Diagnosis
VARCHAR(255),
Treatment
VARCHAR(255), Status
VARCHAR(255),
FOREIGN KEY (PatientNumber) REFERENCES
PAT_ENTRY(PatientNumber), FOREIGN KEY (DoctorNumb
REFERENCES ALL_DOCTORS(IdentityNumber) er)
);

-- Creating the PAT_ADMIT


tableCREATE TABLE
PAT_ADMIT (
PatientNumber INT PRIMARY KEY, AdvancePayment DECIMAL(10, 2), ModeOfPayment
VARCHAR(255), RoomNumber INT, DepartmentName VARCHAR(255),AdmissionDate DATE,
InitialCondition

VARCHAR(255), Diagnosis
VARCHAR(255), Treatment
VARCHAR(255),
DoctorNumber
VARCHAR(255),
AttendantName
VARCHAR(255),
FOREIGN KEY (PatientNumber) REFERENCES PAT_ENTRY(PatientNumber),
FOREIGN KEY (DepartmentName) REFERENCES
DEPARTMENT(DepartmentName),FOREIGN KEY (DoctorNumber) REFERENCES

ALL_DOCTORS(IdentityNumber)
);

-- Creating the PAT_DIS


tableCREATE TABLE
PAT_DIS (
PatientNumber INT PRIMARY
KEY,TreatmentGiven
VARCHAR(255),
TreatmentAdvice
VARCHAR(255),

PaymentMade DECIMAL(10,
2), ModeOfPayment
VARCHAR(255),
DischargeDate DATE,
FOREIGN KEY (PatientNumber) REFERENCES PAT_ENTRY(PatientNumber)

);
-- Creating the PAT_REG
tableCREATE TABLE
PAT_REG (
PatientNumber INT,
VisitDate DATE,
Diagnosis VARCHAR(255),
Treatment VARCHAR(255),
MedicineRecommended
VARCHAR(255),TreatmentStatus
VARCHAR(255),

FOREIGN KEY (PatientNumber) REFERENCES PAT_ENTRY(PatientNumber)

);

-- Creating the PAT_OPR table


CREATE TABLE PAT_OPR (
PatientNumber INT PRIMARY

KEY,AdmissionDate DATE,
OperationDate DATE,
DoctorNumber
VARCHAR(255),
OperationTheaterNumber INT,
OperationType
VARCHAR(255),
ConditionBefore
VARCHAR(255),
ConditionAfter
VARCHAR(255),
TreatmentAdvice
VARCHAR(255),
FOREIGN KEY (PatientNumber) REFERENCES

PAT_ENTRY(PatientNumber), FOREIGN KEY (DoctorNumber)


REFERENCES ALL_DOCTORS(IdentityNumber)
);

-- Creating the ROOM_DETAILS


tableCREATE TABLE
ROOM_DETAILS (
RoomNumber INT
PRIMARY KEY,RoomType
CHAR(1),
Status CHAR(1),
PatientNumber INT,
PatientName
VARCHAR(255),
ChargesPerDay DECIMAL(10, 2),
FOREIGN KEY (PatientNumber) REFERENCES PAT_ENTRY(PatientNumber)

);
Experiment –

:10 Case Study


Railways Management System – ER diagram and SQL queries

:2Passengers can book their tickets for the train in which seats are available. For this,
passengers have to provide the desired train number and the date for which the ticket is to be bo
Description
Before booking a ticket for a passenger, the validity of the train number and booking date is check
Once the train number and booking date are validated, it is checked whether the seat is available.
yes, the ticket is booked with confirm status and the corresponding ticket is generated, which is
stored along with other details of the passenger. After all the available tickets are booked, certain
numbers of tickets are booked with waiting status. If the waiting lot is also finished, then tickets ar
not booked, and a message of non-availability of seats is displayed.
ER Diagram:

SQL queries for tables:


CREATE TABLE Roles (
role_id INT PRIMARY KEY,
role_name VARCHAR(255),
role_desc VARCHAR(255)
);

36
CREATE TABLE Login (
login_role_id INT,
login_username VARCHAR(255) PRIMARY KEY,
login_user_password VARCHAR(255),
FOREIGN KEY (login_role_id) REFERENCES Roles(role_id)
);

CREATE TABLE User (


user_id INT PRIMARY KEY,
user_name VARCHAR(255),
user_mobile VARCHAR(20),
user_email VARCHAR(255),
user_address TEXT
);

CREATE TABLE Permission (


per_name VARCHAR(255) PRIMARY KEY,
role_id INT,
per_role_id INT,
per_module TEXT,
FOREIGN KEY (role_id) REFERENCES Roles(role_id)
);

CREATE TABLE Customer (


cus_id INT PRIMARY KEY,
cus_mobile VARCHAR(20),
cus_name TEXT,
cus_pass TEXT,
cus_add TEXT
);

37
CREATE TABLE Payment (
pay_desc TEXT,
pay_date DATE,
pay_cu_Id INT,
pay_ru_Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
FOREIGN KEY (pay_cu_Id) REFERENCES Customer(cus_id)
);

CREATE TABLE Booking (


book_Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
book_desc TEXT,
book_type TEXT
);

CREATE TABLE Trains(


trn_Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
trn_name TEXT,
trn_num INTEGER,
trn_type TEXT,
trn_disc TEXT
);

38
Experiment – 11

:Case Study
Library 3
Management System – ER diagram and SQL queries

Description The :Authors


stores information
Table about the authors of books in the library. The
Bookscontains
Table details of the books available in the library. The Members Table stores
information
Table about library members like name, address, contact number, email. The Transactio
records transactions such as book borrowings and returns.

ER Diagram:

SQL queries for tables:


-- Create table for authors
CREATE TABLE authors (
author_id INT AUTO_INCREMENT PRIMARY KEY,
author_name VARCHAR(100) NOT NULL,
nationality VARCHAR(50)
);

39
-- Create table for books
CREATE TABLE books (
book_id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author_id INT,
category VARCHAR(100),
FOREIGN KEY (author_id) REFERENCES authors(author_id)
);

-- Create table for members


CREATE TABLE members (
member_id INT AUTO_INCREMENT PRIMARY KEY,
member_name VARCHAR(100) NOT NULL,
address VARCHAR(255),
contact_number VARCHAR(15),
email VARCHAR(100)
);

-- Create table for transactions


CREATE TABLE transactions (
transaction_id INT AUTO_INCREMENT PRIMARY KEY,
book_id INT,
member_id INT,
issue_date DATE,
return_date DATE,
FOREIGN KEY (book_id) REFERENCES books(book_id),
FOREIGN KEY (member_id) REFERENCES members(member_id)
);

40
Experiment –

:12 Case Study


University Management System – ER diagram and SQL queries

Description: The DEPARTMENT table stores information about the academic departments within the
4
university. The FACULTY table contains details about the faculty members employed by the university. The
COURSE table stores information about the courses offered by the university. The SUBJECTS table contains
details about the subjects taught within the university. The STUDENT table holds information about the
students enrolled in the university. The EXAM table stores details about the exams conducted by the
university. The HOSTEL table contains information about the hostels available for student accommodation
The ROOM table stores details about the rooms within the hostels.

ER Diagram:

SQL queries for tables:


CREATE TABLE DEPARTMENT (
D_id INT PRIMARY KEY AUTO_INCREMENT,
D_name VARCHAR(255) NOT NULL,
State VARCHAR(255) NOT NULL,
City VARCHAR(255) NOT NULL,
Pin_code INT NOT NULL
);

41
CREATE TABLE FACULTY (
F_id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
F_name VARCHAR(255) NOT NULL,
L_name VARCHAR(255) NOT NULL,
Mobile_no VARCHAR(255) NOT NULL,
Salary INT NOT NULL,
living ENUM('on campus', 'off campus') NOT
NULL );

CREATE TABLE COURSE (


Course_id INT PRIMARY KEY
AUTO_INCREMENT, Course_name
VARCHAR(255) NOT NULL
);

CREATE TABLE SUBJECTS (


subject_id INT PRIMARY KEY
AUTO_INCREMENT, subject_name
VARCHAR(255) NOT NULL
);

42
CREATE TABLE STUDENT (
S_id INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(255) NOT NULL,
Address VARCHAR(255) NOT NULL,
Phone_no VARCHAR(255) NOT NULL,
DOB DATE NOT NULL,
Age INT NOT NULL
);

CREATE TABLE EXAM (


Exam_code INT PRIMARY KEY
AUTO_INCREMENT, Date DATE NOT NULL,
Time TIME NOT NULL
);

CREATE TABLE HOSTEL (


Hostel_id INT PRIMARY KEY AUTO_INCREMENT,
Hostel_name VARCHAR(255) NOT NULL,
No_of_seats INT NOT NULL
);

CREATE TABLE ROOM (


Room_id INT PRIMARY KEY AUTO_INCREMENT,
Hostel_id INT NOT NULL,
FOREIGN KEY (Hostel_id) REFERENCES HOSTEL(Hostel_id)
);

43
CREATE TABLE DEPARTMENT_FACULTY (
D_id INT NOT NULL,
F_id INT NOT NULL,
FOREIGN KEY (D_id) REFERENCES DEPARTMENT(D_id),
FOREIGN KEY (F_id) REFERENCES FACULTY(F_id),
PRIMARY KEY (D_id, F_id)
);

CREATE TABLE COURSE_FACULTY (


Course_id INT NOT NULL,
F_id INT NOT NULL,
FOREIGN KEY (Course_id) REFERENCES COURSE(Course_id),
FOREIGN KEY (F_id) REFERENCES FACULTY(F_id),
PRIMARY KEY (Course_id, F_id)
);

CREATE TABLE STUDENT_COURSE (


S_id INT NOT NULL,
Course_id INT NOT NULL,
FOREIGN KEY (S_id) REFERENCES STUDENT(S_id),
FOREIGN KEY (Course_id) REFERENCES COURSE(Course_id),
PRIMARY KEY (S_id, Course_id)
);

44
CREATE TABLE EXAM_SUBJECT (
Exam_code INT NOT NULL,
subject_id INT NOT NULL,
FOREIGN KEY (Exam_code) REFERENCES EXAM(Exam_code),
FOREIGN KEY (subject_id) REFERENCES SUBJECTS(subject_id),
PRIMARY KEY (Exam_code, subject_id)
);

CREATE TABLE STUDENT_EXAM (


S_id INT NOT NULL,
Exam_code INT NOT NULL,
FOREIGN KEY (S_id) REFERENCES STUDENT(S_id),
FOREIGN KEY (Exam_code) REFERENCES EXAM(Exam_code),
PRIMARY KEY (S_id, Exam_code)
);

CREATE TABLE FACULTY_SUBJECT (


F_id INT NOT NULL,
subject_id INT NOT NULL,
FOREIGN KEY (F_id) REFERENCES FACULTY(F_id),
FOREIGN KEY (subject_id) REFERENCES SUBJECTS(subject_id),
PRIMARY KEY (F_id, subject_id)
);

45
CREATE TABLE STUDENT_ROOM (
S_id INT NOT NULL,
Room_id INT NOT NULL,
FOREIGN KEY (S_id) REFERENCES STUDENT(S_id),
FOREIGN KEY (Room_id) REFERENCES ROOM(Room_id),
PRIMARY KEY (S_id, Room_id)
);

46
Experiment – 13

:Case Study
Airway 5
Reservation System – ER diagram and SQL queries

Description Flightdetails,
:The stores flight Table including departure and arrival times, available
Passenger Table codes. The records passenger data like names, emails, and
seats, and airport
Airport Table
passport numbers. The contains airport information, including codes, names,
locations, and facilities. Airlines are trackedAirline
in theTable
, with details like names and contact
Booking
numbers.Table
Bookings are stored in the , linking flight and passenger IDs. Finally,
the Payment Table records payment specifics for each booking. Overall, your system streamlines
flight reservations, passenger management, and payments

ER Diagram:

SQL queries for tables:

-- Flight Table
CREATE TABLE Flight (
FlightID INT PRIMARY KEY,
FlightNumber VARCHAR(20) UNIQUE,
DepartureDateTime DATETIME,
ArrivalDateTime DATETIME,
OriginAirportCode VARCHAR(3),
DestinationAirportCode VARCHAR(3),
AvailableSeats INT,
FOREIGN KEY (OriginAirportCode) REFERENCES Airport(AirportCode),
FOREIGN KEY (DestinationAirportCode) REFERENCES Airport(AirportCode)
);

47
-- Passenger Table
CREATE TABLE Passenger (
PassengerID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
PassportNumber VARCHAR(20)
);

-- Airport Table
CREATE TABLE Airport (
AirportCode VARCHAR(3) PRIMARY KEY,
AirportName VARCHAR(100),
Location VARCHAR(255),
Facilities VARCHAR(255)
);

-- Airline Table
CREATE TABLE Airline (
AirlineID INT PRIMARY KEY,
AirlineName VARCHAR(100),
ContactNumber VARCHAR(20),
OperatingRegion VARCHAR(100)
);

48
-- Booking Table
CREATE TABLE Booking (
BookingID INT PRIMARY KEY,
FlightID INT,
PassengerID INT,
PaymentStatus VARCHAR(20),
FOREIGN KEY (FlightID) REFERENCES Flight(FlightID),
FOREIGN KEY (PassengerID) REFERENCES Passenger(PassengerID)
);

-- Payment Table
CREATE TABLE Payment (
PaymentID INT PRIMARY KEY,
BookingID INT UNIQUE,
PaymentMethod VARCHAR(50),
Amount DECIMAL(10, 2),
TransactionDateTime DATETIME,
FOREIGN KEY (BookingID) REFERENCES Booking(BookingID)
);

49

You might also like