dbmsfile.pdf (1)
dbmsfile.pdf (1)
1 Introduction to database.
7 To implement views.
2
Experiment – 1
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.
?
➢
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 –
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.
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:
-- SQL Queries:
CONCLUSION / LEARNING:
After this experiment, we learnt the different commands in SǪL.
Experiment –
4 OBJECTIVE:
To implement Data Definition Language (DDL)
2.3) Check
2.4) Unique
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
2) DROP Table
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
5) PRIMARY KEY
A column is called primary key (PK) that uniquely identifies each row in the table.
6) FOREIGN KEY
The UNIǪUE constraint ensures that all values in a column are different.
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)
);
• ALTER TABLE
studentsDROP COLUMN
DOB;
3. Drop
DROP TABLE students;
);
DDL commands are essential for managing the structure of databases. This experiment
demonstrates how to create, alter, drop, and truncate tables using DDL commands.
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
• INSERT
• UPDATE
• DELETE
• 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
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-
Learning Outcome:
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:
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-
Output:
2. Complex View-
Orders.CustomerID;
Output:
3. Updateable View-
FROM Customers;
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:
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;
2. String Functions:
a. SELECT UPPER(CustomerName) AS CustomerName FROM Customers;
4. Date functions:
a. SELECT DATE(OrderDate) AS OrderDate FROM Orders;
b. SELECT YEAR(OrderDate) AS OrderYear FROM Orders;
Learning Outcome:
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
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 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)
);
DATE, DoctorReferred
VARCHAR(255),Diagnosis
VARCHAR(255),
DepartmentName VARCHAR(255),
FOREIGN KEY (DepartmentName) REFERENCES DEPARTMENT(DepartmentName)
);
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)
);
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),
);
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
);
Experiment –
: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:
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)
);
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)
);
38
Experiment – 11
:Case Study
Library 3
Management System – ER diagram and SQL queries
ER Diagram:
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)
);
40
Experiment –
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:
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 );
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
);
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)
);
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)
);
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:
-- 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