Database Design for Bus Transportation
Database Design for Bus Transportation
Problem Statement: Consider Bus Entity and apply all the concepts of database management.
To design and implement a database management system for a Bus Transportation Entity that efficiently
handles operations such as:
1. Maintaining details of buses, drivers, and routes.
2. Managing schedules and ticket bookings for passengers.
3. Tracking availability of seats and providing real-time updates.
4. Generating reports on bus performance, passenger counts, and revenue.
5. Ensuring data integrity and reducing redundancy in operations.
To apply the core concepts of database management systems, including data modeling, normalization, relational
schema design, and query processing, to solve real-world challenges faced by a bus transportation system.
Steps to Implement
1. Entity Identification:
o Bus: BusID, BusNumber, Capacity, BusType (AC/Non-AC).
o Route: RouteID, Source, Destination, Distance.
o Driver: DriverID, Name, LicenseNumber, ContactNumber.
o Schedule: ScheduleID, BusID, RouteID, DepartureTime, ArrivalTime.
o Passenger: PassengerID, Name, ContactNumber, Email.
o Ticket: TicketID, ScheduleID, PassengerID, SeatNumber, BookingStatus.
2. Create the Database Schema:
o Define tables and relationships between entities.
o Ensure normalization to eliminate data redundancy.
3. Perform Operations:
o Insert, update, and delete records for buses, routes, drivers, and passengers.
o Query the database to retrieve schedules, seat availability, and booking details.
4. Test with Real-Life Scenarios:
o Test for common queries such as available buses for a route, driver schedules, or revenue reports.
5. Generate Reports:
o Daily and monthly ticket sales.
o Driver performance and bus utilization.
Experiment 2: Conceptual Designing using ER Diagrams (Identifying entities, attributes, keys and
relationships between entities, cardinalities, generalization, specialization etc.)
A) Analyze the problem carefully and come up with the entities in it. Identify what data has to be
persisted in the database. This contains the entities, attributes etc... Identify the primary keys for
all the entities. Identify the other keys like candidate keys, partial keys if any.
E-R Model:
Definition: An entity-relationship (ER) diagram is a specialized graphic that illustrates
the interrelationships between entities in a database. (or)
The E-R model is a top-down approach to database design that is based on uniquely
identifiable object. It begins by identifying that are uniquely distinguishable called entities
and relationship among these entities.
Entity: It is a 'thing' in the real world with anindependentexistence. (or)
A real word object that can be distinguished from other objects is called an entity.
There are two types of entities:
1) StrongEntity
2) WeakEntity
Entity set: It is a collection of all entities of particular entity type in the database.
Extension of entity type: The collections of entities of a particular entity type are grouped
together into an entity set.
Attribute: It is a particular property, which describes the entity.(or) Each entity &
relationship has a property called Attributes.
The difference symbols which are used to draw E-R models:
2. Ellipse (Attributes)
Now we will identify the attributes for each entity and construct the E-R Model.
1. BUS Entity:
Dep_Time Destination
Bus_No
Source
BUS
2. TICKET Entity:
The attributes are:
i. Ticket_No
ii. Journey_Date
iii. Age
iv. Sex
v. Source
vi. Destination
vii. Dep_Time
The E-R Model is as follows:
Sex
Age
Source
Journey_Date
Destination
Ticket_No
Dep_Time
TICKET
3. PASSENGER Entity:
Name Age
Ticket_No Sex
PNR_No PPNo
PASSENGER
In the above figure PNR_No is the Primary Key and Ticket_No is Foreign Key
4. RESERVATION Entity:
The attributes are:
i. PNR_No
ii. Journey_Date
iii. No_Of_Seats
iv. Address
v. Contact_No
vi. Status
The E-R Model is as follow:
No_Of_Seats
Address
Journey_Date Contact_No
PNR_No Status
RESERVATION
5. CANCELLATION Entity:
i. PNR_No
ii. Journey_Date
iii. No_Of_Seats
iv. Address
v. Contact_No
vi. Status
No_OF_Seat Address
Journey_Date Contact_No
Status
PNR_No
CANCELLATION
The following diagram depicts the relationship exists between BUS Entity and PASSENGER Entity.
Dep_Time Destination
Bus_No Source
BUS
Travel
in
PASSENGER
PPNo
PNR_No
Ticket_No
Sex
Name
Age
The relationship between BUS Entity and PASSENGER Entity is strong relationship.
Because the two entities consists of primary keys. Here the two entities are strong entities.
So the relationship is strong relationship.
Relationship between PASSENGER Entity and RESERVATION Entity:
The following diagram depicts the relationship exists between PASSENGER Entity and
RESERVATION Entity.
Name Age
Ticket_No Sex
PNR_No PPNo
PASSENGER
Takes
RESERVATION
PNR_No Status
Journey_Date Contact_No
No_Of_Seats Address
The relationship between PASSENGER Entity and RESERVATION Entity is weak relationship.
Because the one entity consists of primary key and another entity consists of foreign key.
Here the one entity is strong entity (single border rectangle) and another entity is weak entity
(double border rectangle). The relationship between strong entity and weak entity is weak relationship.
Relationship between PASSENGER Entity and CANCELLATION Entity:
The following diagram depicts the relationship exists between PASSENGER Entity
Nam Ag
e e
Ticket_N Se
o x
PNR_N PPN
o o
PASSENGER
Cancels
CANCELLATION
PNR_No Status
Journey_Date Contact_No
No_Of_Seats Address
The relationship between PASSENGER Entity and CANCELLATION Entity is weak relationship.
Because the one entity consists of primary key and another entity consists of foreign key.
Here the one entity is strong entity (single border rectangle) and another entity is weak entity (double border
rectangle).
The relationship between strong entity and weak entity is weak relationship.
Experiment 3: Converting ER Model to Relational Model (Represent entities and relationships in
Tabular form, Represent attributes as columns, identifying keys) tables created from ER Model.
A) Represent all the entities (Strong, Weak) in tabular fashion. Represent relationships in a tabular
fashion. There are different ways of representing relationships as tables based on the cardinality.
Represent attributes as columns in tables or as tables based on the requirement. Different types of
attributes (Composite, Multivalve and Derived) have different way of representation.
Relationship:-
It is defined as an association among several entities. A relationship can be one-to- one,
one-to-many (or) many-to-many.
A Collection of similar relationships is called a relationship set and is denoted by a Rhombus.
• Unary Relationship---Where the association is within a single entity
• Binary Relationship---A relationship that associates two entities
• Ternary Relationship---A relationship that association three entities
• Quaternary Relationship—A relationship that associates with four entities
Attribute: It is a particular property, which describes the entity. (or) Each entity & relationship
has a property called Attributes.
1) Simple Attribute -- These attributes are also called as atomic attribute. These cannot be
subdivided further.
2) Composite Attributes -- An attribute which can be further divided into smaller components
are called Composite Attribute.
3) Single-Valued Attributes -- Certain Attribute take only a single value in all instances.
4) Multi-Valued Attributes -- Attributes that can have more than one value at a time for an instance.
5) Stored & Derived Attributes -- Some attributes need not be stored but can be derived
from available other attributes.
The following are the tabular representations of the entities used in this company.
1. BUS EntityTable:
SQL>CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar (15),
Destination varchar (15), Weekday varchar (10));
Table Created.
SQL>insert into Bus values('AP01','Hyderabad','Karimnagar',’Sunday’);
1 rowcreated.
SQL>insert into Bus values('AP02','Delhi','Mumbai',’Monday’);
1 rowcreated.
SQL>insert into Bus values('AP03','Chennai','Srinagar',’Wednesday’);
1 rowcreated.
SQL>insert into Bus values('AP04','Bangalore','Hyderabad',’Sunday’);
1 rowcreated.
SQL>insert into Bus values('AP05','Karimnagar','Warangal',’Friday’);
1 rowcreated.
3. PASSENGER EntityTable:
SQL> CREATE TABLE Passenger(PNR_No NUMERIC (9) primary key, Ticket_No Numeric(9),
Name varchar (15),Age number(4),Sex Char(10),PPNO varchar (15),Category varchar (8));
Table created.
SQL> insert into Passenger values(1000,01,'Anitha',35,'F',10,’A/C’);
1 row created.
SQL> insert into Passenger values(2000,02,'Haritha',30,'F',20,’NONA/C’);
1 rowcreated.
SQL> insert into Passenger values(3000,03,'Srilatha',22,'F',30, ’A/C’);
1 rowcreated.
SQL> insert into Passenger values(4000,04,'Chaitanya',25,'M',40, ’A/C’);
1 rowcreated.
SQL> insert into Passenger values(5000,05,'Saketh',28,'M',50, ’NONA/C’) ;
1 row created.
SQL> insert into Passenger values(6000,06,'Anirudh',27,'M',60, ’NONA/C’);
1 row created.
SQl> Select * from Passenger;
4. CANCELLATION EntityTable:
Normalization: Database designed based on the E-R model may have some amount of inconsistency,
ambiguity and redundancy. To resolve these issues some amount of refinement is required. This
refinement process is called normalization.
Let us now consider the “transportation table”.
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date Age Sex Source Destination Dep_Time
2345 20-08-2024 25 F Anantapur Kurnool 10:30am
5678 25-08-2024 20 M Hyderabad Chennai 07:00pm
2457 30-08-2024 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2024 28 F Kadapa Hyderabad 10:30pm
PASSENGER
PNR_No Ticket_No Name Age Sex PPNo
1 2345 Varuni 25 F 9003345678
2 5678 Rahul 20 M 9247212345
3 2457 Ajay 32 M 9989892731
4 4679 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2024 2 Anantapur 9003345678 Yes
3 25-08-2024 1 Bangalore 9989892731 No
2 30-08-2024 2 Hyderabad 9885252069 Yes
4 05-09-2024 2 Kadapa 9247212345 No
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2024 1 Bangalore 9989892731 No
The above table shows the data file of the transportation in a table format. To reduce the anomalies
normalization is applied
1ST NORMAL FORM:
A relation R is said to be in the first normal form (1NF) if and only if all the attributes of the relation R are
atomic in nature.
Consider the Transportation table to reproduce the table. The following table shows the table in 1NF.
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date Age Sex Source Destination Dep_Time
2345 20-08-2024 25 F Anantapur Kurnool 10:30am
5678 25-08-2024 20 M Hyderabad Chennai 07:00pm
2457 30-08-2024 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2024 28 F Kadapa Hyderabad 10:30pm
PASSENGER
PNR_No Ticket_No Name Age Sex PPNo
1 2345 Varuni 25 F 9003345678
2 5678 Rahul 20 M 9247212345
3 2457 Ajay 32 M 9989892731
4 4679 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2024 2 Anantapur 9003345678 Yes
3 25-08-2024 1 Bangalore 9989892731 No
2 30-08-2024 2 Hyderabad 9885252069 Yes
4 05-09-2024 2 Kadapa 9247212345 No
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2024 1 Bangalore 9989892731 No
In the new form, all the attributes are atomic, meaning that they are not further decomposable.
Key Attributes:
In a given relationship if the attribute X uniquely defines all other attributes, then the attribute
X is a key attribute.
To make the table 2NF we have to remove all the partial dependencies
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date
2345 20-08-2024
5678 25-08-2024
2457 30-08-2024
4679 05-09-2024
PASSENGER
PNR_No Name Age Sex PPNo
1 Varuni 25 F 9003345678
2 Rahul 20 M 9247212345
3 Ajay 32 M 9989892731
4 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2024 2 Anantapur 9003345678 Yes
3 25-08-2024 1 Bangalore 9989892731 No
2 30-08-2024 2 Hyderabad 9885252069 Yes
4 05-09-2024 2 Kadapa 9247212345 No
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2024 1 Bangalore 9989892731 No
3RD NORMAL FORM:
A relation R is said to be in third normal form if and only if
1. It is in2NF
2. No transitive dependency exists between non-key attributes and keyattributes.
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date
2345 20-08-2024
5678 25-08-2024
2457 30-08-2024
4679 05-09-2024
PASSENGER
PNR_No Name Age Sex PPNo
1 Varuni 25 F 9003345678
2 Rahul 20 M 9247212345
3 Ajay 32 M 9989892731
4 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2024 2 Anantapur 9003345678 Yes
3 25-08-2024 1 Bangalore 9989892731 No
2 30-08-2024 2 Hyderabad 9885252069 Yes
4 05-09-2024 2 Kadapa 9247212345 No
Here the reservation table is split into two tables in order to remove transitive dependency. The following
tables shows the 3rd normalform.
1. Reservation status table
PNR_No Journey_Date Status
1 20-08-2024 Yes
3 25-08-2024 No
2 30-08-2024 Yes
4 05-09-2024 No
2. Reservation details table
PNR_No No_of_seats Address Contact_No
1 2 Anantapur 9003345678
3 1 Bangalore 9989892731
2 2 Hyderabad 9885252069
4 2 Kadapa 9247212345
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2024 1 Bangalore 9989892731 No
Here the cancellation table is split into two tables in order to remove transitive dependency. The following
tables shows the 3rd normal form.
1. Cancellation status table
Experiment 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
A) Installation of MySQL. In this week you will learn creating databases. How to create table
altering the database, dropping table and databases if not required. You will also try truncate,
rename
commands etc…
Example for creation of a table.
Create table passenger (passport id Integer primary key, name char(50) null, age
integer, Sex char);
DDL commands:
1. The Create Table Command: - it defines each column of the table uniquely.
Each column has minimum of three attributes, a name, data type andsize.
Syntax: Create table <table name> (<col1> <datatype>(<size>),<col2>
<datatype><size>));
Ex: Create table emp(empno integer(4) primary key, ename char(10));
2. Modifying the structure of tables:Alter command is used to add the column to the
already createdtable.
a) add newcolumns
Syntax: Alter table <tablename> add(<new col><datatype(size),<new
col>datatype(size));
Ex: alter table emp add(sal number(7,2));
3. Dropping a column from atable:
Syntax: Alter table <tablename> drop column <col>;
Ex: alter table emp drop column sal;
5. Renaming the tables:It is used to change the table name which was alreadycreated.
Syntax: Rename <oldtable> to <new table>;
Ex: rename emp to emp1;
3. Truncating the tables:This DDL will support to delete all the rows of a table for
permanent
Syntax: Truncate table <tablename>;
Ex: trunc table emp1;
4. Destroying [Link] command is used to destroy the existing table (or) aview.
Syntax: Drop table <tablename>;
Ex: drop table emp;
BUS:
SQL> CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar (15),
Destination varchar (15));
Table Created.
SQL> desc Bus
-
BusNo varchar2(10)
Source varchar2(15)
Destination varchar2(15)
SQL> Alter table Bus add (Weekday varchar(10));
TableAltered.
SQL> desc Bus
Name Null? Type
--
BusNo varchar2(10)
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
SQL> Alter table Bus modify (BusNovarchar(10)); Table
Altered.
SQL> Alter table Bus drop column BusNo;
Table Altered.
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
SQL> Drop table bus;
Table Dropped.
SQL> Rename Bus to Bus1;
Table Renamed.
SQL> desc Bus1
Name Null? Type
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
SQL>Truncate table bus;
Table Truncated.
PASSENGER:
SQL> CREATE TABLE Passenger (PNR_No NUMERIC (9) primary key, Ticket_No
Numeric(9),Name varchar (15),Age number(4),Sex Char(10),PPNO varchar (15));
Table created.
PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Table Renamed.
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
DELETE – Deletes all records from a table, the space for the records remain
1. SELECTCommand:
The SELECT Command is used to retrieve data from the database. The syntax of the command is as follows.
SELECT A1,A2,……,An
P;
Example:
2. INSERT Command:
The INSERT Command is used to insert data into a relation, we either specify a tuple to be inserted or write a
query whose result is a set of tuples to be inserted. The syntax is as follows.
To insert a single value into the table the following syntax isused.
SQL> INSERT INTO tablenameVALUES(value list);
To insert the multiple values into the table the following syntax isused.
2. UPDATE Command:
UPDATE Command is used to update the existing data within the table. In certain situations we may wish to
change a value in a tuple (row) without changing all values in the table. For this purpose, the update statement
can be used. The syntax of the command is as follows.
1 row updated.
3. DELETE Command:
DELETE Command is used to delete all records from a table, the space for the records remain. The syntax of
the command is as follows.
Example:
SQL> DELETE FROM Cancellation WHEREPNR_No=1;
1 row deleted.
Experiment 7: Practicing Queries using ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT,
CONSTRAINTS
Output:
Output:
4. Display the sorted list of passenger names.
Output:
5. Find the ticket numbers of the passengers whose name starts with ‘A’ and endswith
‘A’.
Output:
6. Find the names of passengers whose age between 30 and45.
SQL>SELECT Name FROM Passenger WHERE Age >=30 and Age <=50;
Output:
9. Display the details of passengers who are travelling either in A/c or Non-A/c (using inoperator).
Output:
Experiment 8: Practicing Subqueries (Nested, Correlated) and Joins (Inner, Outer, and Equi)
A) In SQL, subqueries and joins are powerful tools to retrieve and manipulate data from multiple tables.
Below, we'll cover:
We'll explore examples of each, explain their functionality, and provide the expected output based on sample
data.
1. Subqueries
A subquery is a query nested inside another query. There are two types of subqueries:
Nested Subquery: A subquery that is placed inside a SELECT, INSERT, UPDATE, or DELETE statement.
Correlated Subquery: A subquery that references columns from the outer query.
A nested subquery is a query that returns a single value or a set of values that are used by the outer query.
Syntax:
Example:
Explanation:
The inner query (SELECT MAX(Age) FROM Students) finds the maximum age from the Students table.
The outer query retrieves the Name and Age of students whose age is equal to the maximum age.
Hypothetical Data:
Name Age
John 22
Alice 24
Bob 23
Output:
Name Age
Alice 24
The result shows Alice, the student with the maximum age.
A correlated subquery references columns from the outer query and is executed once for each row processed by
the outer query.
Syntax:
Example:
Explanation:
For each row in the outer query (Students s), the inner query computes the average age of students in the
same department (Department = [Link]).
The outer query retrieves students whose age is greater than the average age in their department.
Hypothetical Data:
Output:
Name Age
Alice 24
Carol 26
The result shows Alice and Carol, whose ages are greater than the average age in their respective
departments.
2. Joins
A JOIN is used to combine records from two or more tables in a database. There are different types of joins based
on how the data is retrieved.
Syntax:
Example:
Explanation:
The query returns the EmployeeID, Name, and Department for employees, joining the Employees and
Departments tables on the DepartmentID.
Hypothetical Data:
Employees Table:
Departments Table:
DepartmentID Department
101 HR
102 IT
103 Sales
Output:
The query returns the matching records between the Employees and Departments tables.
An OUTER JOIN returns all rows from one table and the matched rows from the other table. If there is no match,
the result is NULL on the side that does not have a match.
LEFT OUTER JOIN: Returns all rows from the left table and matched rows from the right table.
RIGHT OUTER JOIN: Returns all rows from the right table and matched rows from the left table.
FULL OUTER JOIN: Returns all rows when there is a match in either the left or right table.
Explanation:
The query returns all employees, along with their departments if they are available. If an employee is not
assigned to a department, the department will be NULL.
Hypothetical Data:
Employees Table:
Departments Table:
DepartmentID Department
101 HR
103 Sales
Output:
An EQUI JOIN is a type of inner join where the matching condition is based on equality (=).
Example:
Explanation:
The query performs an equi join by matching DepartmentID from both the Employees and Departments
tables.
Output:
The output is the same as for the INNER JOIN because an equi join is essentially an inner join with an equality
condition.
1. Subqueries:
o Nested Subquery: A subquery inside another query, usually in the WHERE clause.
o Correlated Subquery: A subquery that references columns from the outer query, executing once for
each row.
2. Joins:
o INNER JOIN: Returns matching rows from both tables.
o OUTER JOIN: Returns all rows from one table and matching rows from the other table (or NULL
if no match exists).
o EQUI JOIN: A specific type of inner join using equality in the ON condition.
Name Age
Alice 24
Name Age
Alice 24
Carol 26
Experiment 9: Practice Queries using COUNT, SUM, AVG, MAX, MIN, GROUP BY, HAVING,
VIEWS Creation and Dropping.
A) You are going to practice queries using Aggregate Functions (COUNT, SUM, AVG, MAX and
MIN), GROUP BY, HAVING and Creation and Dropping of Views.
1. Write a query to display the information present in the passenger and cancellation tables(using
UNIONoperator).
Output:
2. Display the number of days in a week on which the 9wo1 bus is available.
Output:
Output:
4. Find the number of tickets booked for each pnr_no using GROUP B CLAUSE (use
GROUP BY onpnr_no).
Output:
5. Write a query to count the number of tickets for the buses , which travelled after the
date 14/13/2009(use HAVINGCLAUSES).
Output:
Output:
7. Find the number of tickets booked in each class where the number of seats is
greater than 1 (use GROUP BY ,WHERE and HAVINGVLAUSES).
Output:
Experiment 10: Practicing on Triggers - creation of trigger, Insertion using trigger, Deletion using
trigger Updating using trigger
A) Update Trigger.
Practice Triggers using above database.
DELIMITER //
CREATE TRIGGER insert_trig BEFORE INSERT ON Passenger
FOR EACH ROW
BEGIN
IF [Link]<0 THEN
SET [Link]=0;
END IF;
END //
DELIMITER ;
Output:
Trigger created
Insert into Passenger values (4,4895, ‘Ajay’, 12, ‘M’, 9985642589, ‘A/c’, 3),( 5,5568, ‘Madhu’, -23, ‘F’,
8845623587, ‘Non-A/c’, 1);
The inserted Age -23 is inserted as 0.
To understand and implement stored procedures in a database, learn how to create, execute, and
modify them.
Steps to Implement
Step 1: Create a Stored Procedure
Stored procedures are reusable SQL statements stored in the database and can perform
operations like data retrieval or modifications.
SQL Code Example:
sql
Copy code
DELIMITER //
DELIMITER ;
Explanation:
DELIMITER //: Changes the default SQL delimiter to // so the database knows where the
procedure ends.
CREATE PROCEDURE GetBusDetails(): Creates a procedure named GetBusDetails.
The SELECT statement retrieves details of buses from the Bus table.
DELIMITER ;: Restores the default SQL delimiter.
DELIMITER ;
Explanation:
DROP PROCEDURE IF EXISTS GetBusDetails;: Deletes the old procedure if it exists.
The modified procedure now filters the results to show only AC buses.
Write a program for declare a cursor that defines a resultset .Open the cursor to
establish the resultset.
Fetch the data into local variable as needed from the cursor ,one row at a
[Link] the cursor when
done.
DELIMITER //
CREATE PROCEDURE
not_reserved () BEGIN
DECLARE pnr, seats,
pnonumeric; DECLARE jdate
date;
DECLARE address, stat varchar (20);
CREATE cur CURSOR FOR SELECT * FROM Reservation_details WHERE Status=
‘No’;
OPEN cur;
Experiment 13: Creating Forms and Working with Different Objects, Graphics, and
Reports
To create forms for data entry, generate reports using SQL queries, and include graphical objects
to enhance the presentation of data.
Steps to Perform
1. Create a Database Table:
sql
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Department VARCHAR(30),
Salary INT
);
2. Insert Sample Data:
sql
INSERT INTO Employee (EmployeeID, Name, Department, Salary) VALUES
(1, 'John Doe', 'HR', 50000),
(2, 'Jane Smith', 'Finance', 60000),
(3, 'Robert Brown', 'IT', 70000);
3. Create a Form for Data Entry (GUI)
o Use DBMS software (e.g., Microsoft Access, Oracle APEX, or MySQL
Workbench) to design a form.
o Add fields for EmployeeID, Name, Department, and Salary.
o Enable validation for fields (e.g., EmployeeID must be unique).
4. Generate a Report:
Use the following SQL query to generate a report of employees earning more than
₹50,000.
sql
SELECT * FROM Employee WHERE Salary > 50000;
5. Include a Graph:
o Use the Salary column to create a bar graph representing the salaries of
employees by department.
o Generate the graph using tools like MS Excel or integrated DBMS tools.
Expected Output
Form Output:
A graphical user interface to input or modify employee data.
Report Output (SQL):
EmployeeID Name Department Salary
2 Jane Smith Finance 60000
3 Robert Brown IT 70000
Graph:
A bar graph with departments on the x-axis and salaries on the y-axis.
Experiment 15: To perform select; update, insert and delete operation in a table.
CREATE,INSERT , UPDATE, DELETE, RENAME, TRUNCATE, ON TABLES
SQL>CREATE TABLE STUDENT(SNO NUMBER(5),SNAME VARCHAR2(15),DOJ
DATE);
OUTPUT:-TABLE CREATED
SQL> INSERT INTO STUDENT100VALUES(&SNO,'&SNAME','&DOJ');
OUTPUT:-
Enter value for sno: 501
Enter value for sname: ABI
Enter value for doj: 12-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(501,'ABI','12-OCT-07')
1 row created.
SQL> /
Enter value for sno: 502
Enter value for sname: ASHOK
Enter value for doj: 03-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(502,'ASHOK','03-OCT-07')
1 row created.
SQL> /
Enter value for sno: 503
Enter value for sname: BHAVYA
Enter value for doj: 10-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(503,'BHAVYA','10-OCT-07')
1 row created.
SQL> /
Enter value for sno: 504
Enter value for sname: AKASH
Enter value for doj: 05-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(504,'AKASH','05-OCT-07')
1 row created.
SQL> /
Enter value for sno: 505
Enter value for sname: NIKHIL
Enter value for doj: 08-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(505,'NIKHIL','08-OCT-07')
1 row created.
SQL> RENAME STUDENT TO CSESTUDENT;
OUtPUT:-Table renamed.
OUTPUT:-Table altered.
OUTPUT:-
OUTPUT:-Table dropped.
(NOT NULL)
Table created.
SQL> DESC STUD;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROLLNO NOT NULL NUMBER(6)
NAME VARCHAR2(10)
BRANCH VARCHAR2(6)
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
1 row created.
(UNIQUE)
Table created.
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated
(PRIMARY KEY)
SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) PRIMARY KEY ,NAME
VARCHAR2(10),BRANCH VARCHAR2(6));
Table created.
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated
(CHECK)
Table created.
1 row created.
SQL> /
Enter value for rno: 565
Enter value for name: rohit
Enter value for sal: 35000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(565,'rohit',35000)
insert into stud values(565,'rohit',35000)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.NO_CK) violated
( FOREIGN KEY )
SOL>create table adm(stuid number(6) constraint stuid_pk primary key,sname varchar2(15),per
number(5));
Table created.
1 row created.
SQL> /
Enter value for stuid: 2
Enter value for sname: rohit
Enter value for per: 89
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(2,'rohit',89)
1 row created.
SQL> /
Enter value for stuid: 3
Enter value for sname: sachin
Enter value for per: 99
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(3,'sachin',99)
1 row created.
SQL> /
Enter value for stuid: 4
Enter value for sname: naveen
Enter value for per: 70
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(4,'naveen',70)
1 row created.
Table created.
1 row created.
SQL> /
Enter value for stuid: 5
Enter value for branch: cse
Enter value for sec: b
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(5,'cse','b')
insert into course values(5,'cse','b')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found
SQL> delete from adm where stuid=1;
*ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found
1 row deleted.
1 row deleted.
SQL>select * from adm;
OUTPUT:-
OUTPUT:-
View created.
OUTPUT:-
OUTPUT:-
1 row updated.
OUTPUT:-
OUTPUT:-
OUTPUT:-
Table dropped.
Experiment 16: To make use of different clauses viz where, group by, having, order by,
union, intersection, set difference.
Let's walk through the expected outputs for the SQL queries mentioned in the previous
explanation, considering hypothetical data for each case.
Query:
Hypothetical Data:
Name Age
John 19
Alice 21
Bob 23
Carol 20
Dave 22
Output:
Name Age
Alice 21
Bob 23
Dave 22
This query retrieves only those students whose age is greater than 20.
Query:
Hypothetical Data:
Output:
Department NumberOfEmployees
HR 2
IT 2
Sales 1
The GROUP BY groups employees by department and counts how many employees are
in each department.
Query:
Hypothetical Data:
Output:
Department AverageSalary
IT 57500
Sales 70000
The query groups employees by department and calculates the average salary for each
department, showing only those departments with an average salary greater than 50,000.
Hypothetical Data:
Name Age
John 19
Alice 21
Bob 23
Carol 20
Dave 22
Output:
Name Age
Bob 23
Dave 22
Alice 21
Carol 20
John 19
The query orders the students by age in descending order, from the oldest to the
youngest.
Query:
SELECT Name
FROM Employees
WHERE Department = 'Sales'
UNION
SELECT Name
FROM Employees
WHERE Department = 'HR';
Hypothetical Data:
Output:
Name
John
Bob
Dave
The UNION combines the names of employees from the HR and Sales departments,
eliminating duplicates. Alice and Carol are excluded since they are in departments that
are not HR or Sales.
Query:
SELECT Name
FROM Employees
WHERE Department = 'Sales'
INTERSECT
SELECT Name
FROM Employees
WHERE Age > 30;
Hypothetical Data:
Output:
Name
Bob
The query finds employees who work in the Sales department and are older than 30.
Only Bob satisfies both conditions.
SELECT Name
FROM Employees
WHERE Department = 'Sales'
EXCEPT
SELECT Name
FROM Employees
WHERE Age > 30;
Hypothetical Data:
Output:
Name
Dave
The query returns employees who are in the Sales department and are not older than 30.
John and Bob are excluded as they are older than 30.
Query:
Hypothetical Data:
Output:
The query groups sales by employee and calculates the total sales for each, showing only
those with total sales greater than 1000. The results are sorted in descending order by
TotalSales.
To understand and implement various SQL constraints and demonstrate how they work using a
database table.
Definition of Constraints
SQL constraints are rules applied to table columns to enforce data integrity and reliability.
Common constraints include:
1. NOT NULL: Ensures a column cannot have a NULL value.
2. UNIQUE: Ensures all values in a column are distinct.
3. PRIMARY KEY: A combination of NOT NULL and UNIQUE. Identifies each record in
a table uniquely.
4. FOREIGN KEY: Establishes a link between the columns of two tables.
5. CHECK: Ensures all values in a column satisfy a specific condition.
6. DEFAULT: Assigns a default value to a column if no value is provided.
Implementation Example
Step 1: Create a Table with Constraints
SQL Code Example:
sql
CREATE TABLE Bus (
BusID INT PRIMARY KEY, -- PRIMARY KEY Constraint
BusNumber VARCHAR(15) UNIQUE, -- UNIQUE Constraint
Capacity INT NOT NULL, -- NOT NULL Constraint
BusType VARCHAR(10) DEFAULT 'AC',-- DEFAULT Constraint
RouteID INT, -- Foreign Key Column
CONSTRAINT chk_Capacity CHECK (Capacity > 10) -- CHECK Constraint
);
Explanation of Constraints Used:
1. PRIMARY KEY: Ensures BusID uniquely identifies each record.
2. UNIQUE: Ensures no duplicate BusNumber.
3. NOT NULL: Ensures Capacity cannot be NULL.
4. DEFAULT: Assigns AC as the default BusType if no value is provided.
5. CHECK: Ensures Capacity is always greater than 10.
Experiment 18: To use oracle function viz aggregate, numeric, conversion, string function.
FUNCTIONS:
AGGREGATE FUNCTIONS
output:-
ENO ENAME JOB SAL
---------- ---------- ---------- ----------
1001 STEVE SALESMAN 1500
1002 ADAM CLERK 1000
1003 EVE MANAGER 5220
1004 JAMES DIRECTOR 7000
output:-
COUNT(*)
----------
4
output:-
SUM(SAL)
----------
14720
output:-
AVG(SAL)
----------
3680
output:-
MAX(SAL)
----------
7000
SQL> SELECT MIN(SAL) FROM EMP;
output:-
MIN(SAL)
----------
1000
OUTPUT:-
14 rows selected.
OUTPUT:-
DEPTNO MAX(SAL)
---------- ----------
10 5000
20 3000
30 2850
OUTPUT:-
DEPTNO MIN(SAL)
---------- ----------
10 1300
20 800
30 950
OUTPUT:-
DEPTNO MAX(SAL)
---------- ----------
30 2850
OUTPUT:-
DEPTNO MIN(SAL)
---------- ----------
10 1300
OUTPUT:-
DEPTNO COUNT(*)
---------- ----------
10 3
20 5
30 6
3 rows selected.
CONVERSION FUNCTIONS(TO_CHAR)
OUTPUT:-ORACLECORPORATION
OUTPUT:-*********ORACLE
OUTPUT:-ORACLE*********
OUTPUT:-MITHSS
OUTPUT:-SSMITH
OUTPUT:-dbms
OUTPUT:-DBMS
OUTPUT:-Oracle Corporation
OUTPUT:-8
OUTPUT:-14
DATE FUNCTIONS
OUTPUT:-29-DEC-08
OUTPUT:-05-JAN-09
OUTPUT:-28-FEB-09
OUTPUT:-31-DEC-08
OUTPUT:-
OUTPUT:-10-JAN-07
OUTPUT:-10-JAN-07
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;
OUTPUT:-28-DEC-08
OUTPUT:-01-DEC-08
SQL>SELECT TRUNC(SYSDATE,'YEAR')FROM DUAL;
OUTPUT:-01-JAN-08
OUTPUT:-28-DEC-08
OUTPUT:-01-JAN-09
OUTPUT:-01-JAN-09
NUMBER FUNCTIONS
OUTPUT:-
ROUND(12.36) ROUND(14.63)
------------ ------------
12 15
OUTPUT:-
FLOOR(12.87) FLOOR(11.23)
------------ ------------
12 11
OUTPUT:-
CEIL(16.23) CEIL(12.78)
----------- -----------
17 13
OUTPUT:-
TRUNC(56.63)
------------
56
OUTPUT:-
MOD(11,4)
----------
3
OUTPUT:-
POWER(2,3)
----------
8
OUTPUT:-
OUTPUT:-
ABS(12) ABS(-89)
---------- ----------
12 89
OUTPUT:-
SQRT(25)
--------
A JOIN in SQL is used to combine rows from two or more tables based on a related column
between them. JOINs are a fundamental concept for working with relational databases, allowing
you to retrieve and combine data spread across multiple tables.
There are several types of joins in SQL, but the most common ones are:
1. INNER JOIN
2. LEFT JOIN (or LEFT OUTER JOIN)
3. RIGHT JOIN (or RIGHT OUTER JOIN)
4. FULL JOIN (or FULL OUTER JOIN)
5. CROSS JOIN
A JOIN in SQL is used to combine rows from two or more tables based on a related column
between them. JOINs are a fundamental concept for working with relational databases, allowing
you to retrieve and combine data spread across multiple tables.
There are several types of joins in SQL, but the most common ones are:
1. INNER JOIN
2. LEFT JOIN (or LEFT OUTER JOIN)
3. RIGHT JOIN (or RIGHT OUTER JOIN)
4. FULL JOIN (or FULL OUTER JOIN)
5. CROSS JOIN
Each type of join works differently depending on how you want to retrieve data.
1. INNER JOIN
The INNER JOIN returns only the rows where there is a match in both tables.
Example:
employees table:
departments table:
department_id department_name
1 Sales
2 HR
3 IT
Explanation:
This query joins the employees and departments tables based on the department_id
column. It only returns employees who belong to departments listed in the departments
table.
Expected Output:
name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
The LEFT JOIN (or LEFT OUTER JOIN) returns all the rows from the left table (the first
table in the query) and the matched rows from the right table. If there’s no match, the result is
NULL on the side of the right table.
Example:
Explanation:
This query returns all employees, even if they don't belong to a department (i.e., when no
matching row exists in the departments table). If no match is found, department_name
will be NULL.
Expected Output:
name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
In this case, all employees belong to a department, so the output is similar to the INNER JOIN.
If you had an employee like Eve who doesn't belong to any department:
employees table:
name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
Eve NULL
The RIGHT JOIN (or RIGHT OUTER JOIN) is the opposite of the LEFT JOIN. It returns
all rows from the right table and the matched rows from the left table. If there’s no match, NULL
values will appear on the left table side.
Example:
This query returns all departments, even if no employees belong to them (i.e., when
there’s no match in the employees table).
Expected Output:
name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
NULL Marketing
Here, we have the Marketing department without any employees, so it shows as NULL for the
name.
A FULL JOIN (or FULL OUTER JOIN) returns all rows when there’s a match in either left
(employees) or right (departments) table. If there’s no match, NULL values are returned for the
columns from the non-matching table.
Example:
Explanation:
This query combines the result of both LEFT JOIN and RIGHT JOIN, so you get all
employees and all departments, even if there’s no match between the two.
Expected Output:
name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
Eve NULL
NULL Marketing
Here, Eve does not belong to any department, and the Marketing department has no employees,
so we get NULL in both columns for those rows.
5. CROSS JOIN
A CROSS JOIN returns the Cartesian product of both tables. This means it returns all possible
combinations of rows from the two tables. This join doesn’t require any condition and can result
in a large number of rows.
Example:
Explanation:
This query returns all possible combinations of employees and departments. If there are 4
employees and 3 departments, the result will have 12 rows (4 * 3).
Expected Output:
name department_name
Alice Sales
Alice HR
Alice IT
Alice Marketing
Bob Sales
Bob HR
Bob IT
Bob Marketing
Charlie Sales
Charlie HR
Charlie IT
Charlie Marketing
David Sales
David HR
David IT
David Marketing
Eve Sales
name department_name
Eve HR
Eve IT
Eve Marketing
sql
Copy code
CREATE DATABASE CompanyDB;
USE CompanyDB;
sql
-- Insert departments
INSERT INTO departments (department_id, department_name, location)
VALUES
(1, 'Sales', 'New York'),
(2, 'HR', 'Los Angeles'),
(3, 'IT', 'New York'),
(4, 'Marketing', 'Chicago');
-- Insert employees
INSERT INTO employees (employee_id, name, salary, department_id, manager_id)
VALUES
(1, 'Alice', 60000, 1, NULL),
(2, 'Bob', 75000, 1, 1),
(3, 'Charlie', 85000, 2, NULL),
(4, 'David', 50000, 3, NULL),
(5, 'Eva', 90000, 3, 4),
(6, 'Frank', 45000, 4, 3);
Query:
Display each employee's name, salary, and the average salary of their department.
sql
SELECT name, salary,
(SELECT AVG(salary) FROM employees WHERE department_id = e.department_id) AS
avg_department_salary
FROM employees e;
Explanation:
The subquery calculates the average salary for each employee’s department.
Expected Output:
Query:
Find employees who earn more than the average salary of all employees.
sql
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
Explanation:
The subquery calculates the overall average salary of all employees, and the main query
retrieves employees whose salary is above that average.
Expected Output:
name salary
Bob 75000.00
Charlie 85000.00
Eva 90000.00
sql
SELECT name, department_id
FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE location =
'New York');
Explanation:
The subquery returns department IDs with the location 'New York', and the main query
retrieves employees working in those departments.
Expected Output:
name department_id
Alice 1
Bob 1
Charlie 3
Eva 3
4. Correlated Subquery
Query:
Find employees whose salary is greater than the average salary in their own department.
sql
SELECT name, salary, department_id
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id =
e.department_id);
Explanation:
The subquery calculates the average salary for each department. The outer query checks
if an employee's salary is greater than the average salary in their respective department.
Expected Output:
Query:
Find the average salary of employees who earn more than 50,000 in each department.
sql
Explanation:
The subquery filters employees who earn more than 50,000, and the outer query
calculates the average salary for each department in this filtered list.
Expected Output:
department_id avg_salary
1 67500.00
2 85000.00
3 67500.00
Query:
Find employees who are managers (those who manage other employees).
sql
SELECT name
FROM employees e
WHERE EXISTS (SELECT 1 FROM employees WHERE manager_id = e.employee_id);
Explanation:
The subquery checks if there are any employees whose manager_id matches the
employee_id of the employee in the outer query. If so, the employee is considered a
manager.
Expected Output:
name
Alice
Eva
Query:
Increase the salary of employees in the 'Sales' department by 10%.
sql
Copy code
UPDATE employees
SET salary = salary * 1.10
WHERE department_id = (SELECT department_id FROM departments WHERE
department_name = 'Sales');
Explanation:
The subquery finds the department ID for the 'Sales' department, and the UPDATE
statement increases the salary of employees in that department by 10%.
Query:
Delete employees who work in departments located in 'Los Angeles'.
sql
Copy code
DELETE FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE location =
'Los Angeles');
Explanation:
The subquery finds the department IDs with the location 'Los Angeles', and the DELETE
statement removes employees from those departments.