0% found this document useful (0 votes)
68 views86 pages

Database Design for Bus Transportation

The document outlines a series of experiments focused on designing a database management system for a bus transportation entity. It includes steps for identifying entities, creating an ER model, and converting it to a relational model, detailing attributes, primary keys, and relationships between entities like Bus, Ticket, Passenger, Reservation, and Cancellation. The document emphasizes the application of database management concepts such as normalization, query processing, and real-world testing scenarios.

Uploaded by

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

Database Design for Bus Transportation

The document outlines a series of experiments focused on designing a database management system for a bus transportation entity. It includes steps for identifying entities, creating an ER model, and converting it to a relational model, detailing attributes, primary keys, and relationships between entities like Bus, Ticket, Passenger, Reservation, and Cancellation. The document emphasizes the application of database management concepts such as normalization, query processing, and real-world testing scenarios.

Uploaded by

yogesh chowdary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Experiment 1: Students should decide on a case study and formulate the problem statement.

A) Case Study: Bus Entity


A bus entity involves managing various aspects of a bus transportation system. This includes handling
buses, routes, schedules, drivers, passengers, and ticketing. The goal is to design and manage a database
that ensures efficient operations and provides meaningful insights.

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 type: It is a collection (set) of entities that have same attributes.

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:

1. Rectangle (Strong entityset)

2. Ellipse (Attributes)

[Link] (Relationship set)

4. Double Rectangle (Weak Entityset)

5. Undirected Line(Flow ofRelationship)

6. Directed Line (Flow of Relationship)


Super Key:
A Super Key of an entity set is a set of one (or) more attributes whose values uniquely
determine each entity.
Candidate Key:
A Candidate Key of an entity set is a minimal super key. For example:
1) Customer_Idis Candidate Key of Customer
2) Account_ Number is Candidate Key of Account
Primary Key:
Although several Candidate keys may exist, one of the Candidate keys is selected to be the
PrimaryKey.
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same
owner entity. It is sometime called as Discriminator.
The entities for the above company named “Roadway Travels” are as follows
1. Bus
2. Ticket
3. Passenger
4. Reservation
5. Cancellation

Now we will identify the attributes for each entity and construct the E-R Model.

1. BUS Entity:

The attributes are:


i. Bus_No
ii. Source
iii. Destination
iv. Dep_Time
The E-R Model is asfollows:

Dep_Time Destination

Bus_No
Source
BUS

In the above figure Bus_No is the Primary Key

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

In the above figure Ticket_No is the Primary Key

3. PASSENGER Entity:

The attributes are:


i. PNR_No
ii. Ticket_No
iii. Name
iv. Age
v. Sex
vi. PPNo

The E-R Model is as follows:

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

In the above figure PNR_No is the Foreign Key

5. CANCELLATION 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 follows:

No_OF_Seat Address

Journey_Date Contact_No

Status
PNR_No
CANCELLATION

In the above figure PNR_No is the Foreign Key


Relationship between BUS Entity and PASSENGER Entity:

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

and CANCELLATION 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.

SQL> Select * from Bus;

BusNo Source Destination Weekday


AP01 Hyderabad Karimnagar Sunday
AP02 Delhi Mumbai Monday
AP03 Chennai Srinagar Wednesday
AP04 Bangalore Hyderabad Sunday
AP05 Karimnagar Warangal Friday
[Link] Entity Table:

SQL> CREATE TABLE Ticket(Ticket_No NUMERIC(9) Primary Key,Journey_date Date,


Age NUMERIC(4),Sex varchar(10),Source Varchar(10),Arrival_time varchar(6),
Destination Varchar(10),Dep_time varchar(6));
Table created.
SQL> insert into Ticket values(1,’2010-01-01’,35,'F','Hyderabad',9,'Karimnagar',23); 1 row created.
SQL> insert into Ticket values(2,’2010-01-02’,30,'F','Delhi',5,'Mumbai',18);
1 row created.
SQL> insert into Ticket values(3,’2010-01-03’,22,'F','Chennai',6,'Srinagar',16);
1 row created.
SQL> insert into Ticket values(4,’2010-01-04’,25,'M','Bangalore',8,'Hyderabad',14);
1 row created.
SQL> insert into Ticket values(5,’2010-01-05’,28,'M','Karimnagar',5,'Warangal',13);
1 row created.
SQL> Select * from Ticket;

Ticket_ Journey_date Age Sex Source Arrival_ Destination Dep_Tim


No time e
1 2010-01-01 5 F Hyderabad 9 Karimnagar 23
2 2010-01-02 30 F Delhi 5 Mumbai 18
3 2010-01-03 22 F Chennai 6 Srinagar 16
4 2010-01-04 25 M Bangalore 8 Hyderabad 14
5 2010-01-05 28 M Karimnagar 5 Warangal 13

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;

PNR_No Ticket_No Name Age Sex PPNO Category

1000 1 Anitha 35 F 10 A/C


2000 2 Haritha 30 F 20 NONA/C
3000 3 Srilatha 22 F 30 A/C
4000 4 Chaitanya 25 M 40 A/C
5000 5 Saketh 28 M 50 NONA/C
6000 6 Anirudh 27 M 60 NONA/C
4. RESERVATION EntityTable:
SQL> CREATE TABLE Reserve(PNR_No NUMERIC(9),foreign key(PNR_No)
references passenger(PNR_NO), Journey_date date, No_of_seats number(8),
Address Varchar(40),Contact_No NUMERIC(10),Status Char(2));
Table Created.
SQL> insert into reservevalues(1000,'2010-02-01’,5,'Ramanthpur',0123456789,'Y');
1 rowcreated.
SQL> insert into reserve values(2000,’2010-02-02’,2,'KPHB',1234567890,'Y');
1 rowcreated.
SQL> insert into reservevalues(3000,’2010-02-03’,3,'Dilsukhnagar',1234567809,'Y');
1 rowcreated.
SQL> insert into reservevalues(4000,’2010-02-04’,4,'Tarnaka',1234123412,'Y');
1 rowcreated.
SQL> insert into reservevalues(5000,’2010-02-05’,5,'DDCOLONY',1234512345,'Y');
1 rowcreated.

SQL> Select * from Reserve;

PNR_No Journey_date No_of_seats Address Contact_No Status


1000 2010-02-01 1 Ramanthpur 0123456789 Y
2000 2010-02-02 2 KPHB 1234567890 Y
3000 2010-02-03 3 Dilsukhnagar 1234567809 Y
4000 2010-02-04 4 Tarnaka 1234123412 Y
5000 2010-02-05 5 DDCOLONY 1234512345 Y

4. CANCELLATION EntityTable:

SQL> CREATE TABLE Cancellation(PNR_No NUMERIC(9), foreign key(PNR_NO) references


passenger(PNR_NO),Journey_datedate,No_of_seats NUMERIC(8), Address Varchar(40),Contact_No
NUMERIC(10),Status char(2));
Table Created.

SQL> insert into cancellation values(1000,'2010-01-01',5,'Ramanthpur',0123456789,'N');


1 row created.
SQL> insert into cancellation values(2000,'2010-02-02',5,'KPHB',1234567890,'N'); 1 row created.
SQL> insert into cancellation values(3000,'2010-02-03',4,'Dilsukhnagar',12345679,'N');
1 row created.
SQL> insert into cancellation values(4000,'2010-04-04',2,'tarnaka',1234123412,'N');
1 row created.
SQL> insert into cancellation values(5000,'2010-05-05',6,'DDCOLONY',1234512345,'N');
1 row created.
SQL> Select * from Cancellation;

PNR_No Journey_date No_of_seats Address Contact_No Status


1000 2010-01-01 5 Ramanthpur 0123456789 Y
2000 2010-02-02 5 KPHB 1234567890 Y
3000 2010-02-03 4 Dilsukhnagar 1234567809 Y
4000 2010-04-04 2 Tarnaka 1234123412 Y
5000 2010-05-05 6 DDCOLONY 1234512345 Y
Experiment 4: Normalization -To remove the redundancies and anomalies in the above relational
tables, Normalize up to Third Normal Form
A) Database Normalization is a technique for designing relational database tables to minimize duplication
of information and, in doing, to safeguard the database against certain types of logical or structural
problems, namely data anomalies. For example, when multiple instances of a given piece of information
occur in a table, the possibility exists that these instances will not be kept consistent when the data within
the table is updated, leading to a loss of data integrity. A table that is sufficiently normalized is less
vulnerable to problems of this kind. Because its structure reflects the basic assumptions for when multiple
instances of the same information should be represented by a single instance only.

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.

2ND NORMAL FORM:

The relation is said to be in second normal form if and only if:


1. It is in the first normalform
2. No partial dependency exists between non-key attributes and keyattributes.

Key Attributes:

In a given relationship if the attribute X uniquely defines all other attributes, then the attribute

X is a key attribute.

In the above tables Bus_No, Ticket_No, PNR_No are key attributes.


Non-Key Attributes:
In a given relationship R, all the attributes which are not key attributes are called non-key

attributes. The remaining attributes are non-key attributes.

Let us visit again 1NF table.

 Bus_Nois the key attribute forBus


 Ticket_Nois the key attribute forTicket
 PNR_Nois the key attribute forpassenger
 Other attributes like name, age, sex, Journey_Dateetc are non-keyattributes

To make the table 2NF we have to remove all the partial dependencies

 Source, Destination and Dep_Time depends only onBus_No


 Journey_Date depends only onTicket_No
 Ticket_No, Name, Age, Sex, PPNo depends onPNR_No

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

PNR_No Journey_Date Status


3 30-08-2024 No

2. Cancellation details table

PNR_No No_of_seats Address Contact_No


3 1 Bangalore 9989892731

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

Different types of commands in SQL:


A). DDL commands: - To create a database objects
B) DML commands: - To manipulate data of a databaseobjects
C). DQL command: - To retrieve the data from adatabase.
D). DCL/DTL commands: - To control the data of a database…

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;

4. Modifying existing columns:By using modify, we can change the datatype of a


particularfield
Syntax: Alter table <tablename> modify <col><newdatatype>(<newsize>);
Ex: alter table emp modify enamevarchar(15);

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

Name Null? Type

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

SQL> desc Bus


Name Null? Type

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.

SQL> desc Passenger

Name Null? Type

PNR_No Not Null Number(9)


Ticket_No Number(9)
Name varchar2(15)
Age Number(4)
Sex Char(10)
PPNO varchar2(15)

SQL> Alter table Passenger add (Category varchar (8));


Table Altered.
SQL> desc Passenger

Name Null? Type

PNR_No Not Null Number(9)


Ticket_No Number(9)
Name varchar(15)
Age Number(4)
Sex Char(10)
PPNO varchar(15)
Category varchar(8)

SQL> Alter table Passenger modify (PNR_Nonumber(9));


Table Altered.
CANCELLATION:

SQL> CREATE TABLE Cancellation(PNR_No NUMERIC(9), foreign key(PNR_NO)


references passenger(PNR_NO),Journey_datedate,No_of_seats NUMERIC(8), Address
Varchar(40),Contact_No NUMERIC(10));
Table Created.
SQL> desc Cancellation
Name Null? Type

PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)

SQL> Alter table Cancellation add (status char(2));


Table Altered.

SQL> desc Cancellation

Name Null? Type

PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)

SQL> Alter table Cancellation modify (PNR_Nonumber(9));


Table Altered.

SQL> Alter table Cancellation drop column PNR_No;


Table Altered.

SQL> desc Cancellation

Name Null? Type

Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)

SQL> Drop table Cancellation;


Table Dropped.

SQL> Rename Cancellation to Cancellation1;

Table Renamed.

SQL> desc Cancellation1


Name Null? Type

Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)

SQL> Truncate table Cancellation1; Table Truncated.

Experiment 6: Practicing DML commands- Insert, Select, Update, Delete


A) DML Commands are used to for managing data within schema objects.
Some examples: SELECT Retrieve data from the database

INSERT – Insert data into the table

UPDATE – Updates existing data within the table

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

FROM Tablename WHERE

P;

Here A1,A2,……An are the attributes and P is the condition

Example:

 SQL> SELECT * FROMBus;

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.

SQL> INSERT INTO tablenameVALUES(&value1,&value2,………,valueN);


Example:
 SQL> INSERT INTO Bus VALUES (‘1AB’,’Hyderabad’,’Chennai’,’19:00’),
(‘76C’,’Kurnool’,’Warangal’,’05:30’),(‘8FR’,’Delhi’,’Jaipur’,’16:30’);

Values inserted in Bus table.


 SQL> INSERT INTO Cancellation VALUES (1,’2016-0317’,2,’Hyderabad’,9974656891,’No’),
(2,’2016-04-26’,3,’Kurnool’,9654862661,’No’);

Values inserted in Cancellation table.

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.

SQL> UPDATE tablename SET value WHERE condition;


Example:

 SQL> UPDATE Reservation_details SET Status=’Yes’ WHEREPNR_No=1;

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.

SQL> DELETE FROM tablename WHERE condition;

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

A) Practice the following Queries:

1. Display unique PNR_no of allpassengers.

SQL>SELECT PNR_No FROM Passenger;


Output:

2. Display all the name of male passengers.

SQL>SELECT Name FROM Passenger WHERE Sex=’M’;

Output:

3. Display the ticket numbers and names of all thepassengers.

SQL>SELECT Ticket_No, Name FROM Passenger;

Output:
4. Display the sorted list of passenger names.

SQL> SELECT * FROM Passenger ORDER BY NAME;

Output:

5. Find the ticket numbers of the passengers whose name starts with ‘A’ and endswith

‘A’.

SQL>SELECT Ticket_No FROM Passenger WHERE Name LIKE ‘a%%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:

7. Display the bus numbers that travel on Sunday and Monday.


SQL>SELECT Bus_No FROM Bus WHERE Days IN (‘Tuesday’);
Output:
8. Display the source and the destination having journey time more than 10hours.
SQL>SELECT Source, Destination FROM Bus WHERE Hours>=8;
Output:

9. Display the details of passengers who are travelling either in A/c or Non-A/c (using inoperator).

SQL> SELECT * FROM Passenger WHERE Service in(‘A/c’, ‘Non-A/c’);


Output:

10. Display all the passenger names beginning with‘A’.


SQL>SELECT Name FROM Passenger WHERE Name LIKE ‘a%%’;

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:

 Subqueries (Nested & Correlated)


 Joins (Inner Join, Outer Join, and Equi Join)

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.

1.1 Nested Subquery

A nested subquery is a query that returns a single value or a set of values that are used by the outer query.

Syntax:

SELECT column1, column2


FROM table1
WHERE column1 IN (SELECT column1 FROM table2 WHERE condition);

Example:

SELECT Name, Age


FROM Students
WHERE Age = (SELECT MAX(Age) FROM Students);

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.

1.2 Correlated Subquery

A correlated subquery references columns from the outer query and is executed once for each row processed by
the outer query.

Syntax:

SELECT column1, column2


FROM table1 t1
WHERE column1 > (SELECT AVG(column1) FROM table2 t2 WHERE t1.column2 = t2.column2);

Example:

SELECT Name, Age


FROM Students s
WHERE Age > (SELECT AVG(Age) FROM Students WHERE Department = [Link]);

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:

Name Age Department


John 22 HR
Alice 24 IT
Bob 23 HR
Carol 26 IT

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.

2.1 Inner Join


An INNER JOIN returns records that have matching values in both tables.

Syntax:

SELECT column1, column2


FROM table1
INNER JOIN table2
ON [Link] = [Link];

Example:

SELECT [Link], [Link], [Link]


FROM Employees e
INNER JOIN Departments d
ON [Link] = [Link];

Explanation:

 The query returns the EmployeeID, Name, and Department for employees, joining the Employees and
Departments tables on the DepartmentID.

Hypothetical Data:

Employees Table:

EmployeeID Name DepartmentID


1 John 101
2 Alice 102
3 Bob 103

Departments Table:

DepartmentID Department
101 HR
102 IT
103 Sales

Output:

EmployeeID Name Department


1 John HR
2 Alice IT
3 Bob Sales

 The query returns the matching records between the Employees and Departments tables.

2.2 Outer Join

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.

Example: LEFT OUTER JOIN:

SELECT [Link], [Link], [Link]


FROM Employees e
LEFT OUTER JOIN Departments d
ON [Link] = [Link];

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:

EmployeeID Name DepartmentID


1 John 101
2 Alice NULL
3 Bob 103

Departments Table:

DepartmentID Department
101 HR
103 Sales

Output:

EmployeeID Name Department


1 John HR
2 Alice NULL
3 Bob Sales

 Alice does not have a department, so the department is NULL.

2.3 Equi Join

An EQUI JOIN is a type of inner join where the matching condition is based on equality (=).

Example:

SELECT [Link], [Link], [Link]


FROM Employees e
JOIN Departments d
ON [Link] = [Link];

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.

Summary of SQL Joins and Subqueries

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.

Expected Outputs Summary:

Nested Subquery Example Output:

Name Age
Alice 24

Correlated Subquery Example Output:

Name Age
Alice 24
Carol 26

Inner Join Example Output:

EmployeeID Name Department


1 John HR
2 Alice IT
3 Bob Sales

Outer Join (Left) Example Output:

EmployeeID Name Department


1 John HR
2 Alice NULL
3 Bob Sales

Equi Join Example Output:

EmployeeID Name Department


1 John HR
2 Alice IT
3 Bob Sales
.

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

SQL>SELECT PNR_No FROM Passenger UNION SELECT PNR_No FROM Cancellation;

Output:

2. Display the number of days in a week on which the 9wo1 bus is available.

SQL>SELECT count (Days) FROM Bus WHERE Bus_No= ‘8FR’;

Output:

3. Find the distint numbers that are present.


SQL>SELECT DISTINT PNR_No FROM Passenger;

Output:

4. Find the number of tickets booked for each pnr_no using GROUP B CLAUSE (use

GROUP BY onpnr_no).

SQL>SELECT PNR_No, sum(No_of_seats) No_of_seats FROM Reservation_details GROUP BY


PNR_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).

SQL> SELECT sum(No_of_seats) No_of_seats FROM Passenger WHERE Journey_Date BETWEEN


‘2016-03-12’ AND ‘2016-05-23’ HAVING count(PNR_No)>=0;

Output:

6. Find the total no of cancellation seats.


SQL>SELECT sum(No_of_seats) No_of_seats FROM Cancellation;

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

SQL> SELECT PNR_No, Name, sum(No_of_seats) No_of_seats, Service FROM Passenger


WHERE Service IN ('A/c','Non-A/c') GROUP BY Name, PNR_No, Service HAVING
sum(No_of_seats)>2;

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.

NOTE: Triggers can be used on only existing tables.


Experiment 11: Procedures of Creation of Stored Procedures, Execution, and Modification

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

CREATE PROCEDURE GetBusDetails()


BEGIN
SELECT BusID, BusNumber, Capacity, BusType
FROM Bus;
END //

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.

Step 2: Execute the Stored Procedure


SQL Code Example:
sql
Copy code
CALL GetBusDetails();
Output Example:
BusID BusNumber Capacity BusType
101 TS01AB1234 50 AC
102 TS02CD5678 40 Non-AC

Step 3: Modify the Stored Procedure


To modify a procedure, you drop the existing one and recreate it with changes.
SQL Code Example:
sql
DROP PROCEDURE IF EXISTS GetBusDetails;
DELIMITER //

CREATE PROCEDURE GetBusDetails()


BEGIN
SELECT BusID, BusNumber, Capacity, BusType
FROM Bus
WHERE BusType = 'AC';
END //

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.

Step 4: Execute the Modified Procedure


SQL Code Example:
sql
CALL GetBusDetails();
Output Example:
BusID BusNumber Capacity Bus Type
101 TS01AB1234 50 AC
Experiment 12: Cursors- Declaring Cursor, Opening Cursor, Fetching the data, closing the cursor
A) In this week you need to do the following: Declare a cursor that defines the result set.
Open the cursor
that establishes the result set. Fetch the data into local variables as needed from the
cursor, one row at a
time. Close the cursor when done.

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;

FETCH cur INTO pnr, jdate, seats, address, pno,


stat; SELECT ,jdate, seats, address, pno, stat;
CLOSE cur; END //
DELIMITER
Output:
Procedure
created Call
not_reserved();

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 14: To Create a Table, Alter and Drop Table


Objective
To understand the creation, modification, and deletion of database tables using SQL commands.
Steps to Perform
1. Create a Table:
sql
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Course VARCHAR(30),
Age INT
);
2. Insert Sample Data:
sql
INSERT INTO Student (StudentID, Name, Course, Age) VALUES
(101, 'Alice', 'BSc', 20),
(102, 'Bob', 'BCom', 21),
(103, 'Charlie', 'BA', 22);
3. Alter the Table:
Add a new column for Email:
sql
ALTER TABLE Student ADD Email VARCHAR(50);
Update the new column:
sql
UPDATE Student
SET Email = 'alice@[Link]' WHERE StudentID = 101;
UPDATE Student
SET Email = 'bob@[Link]' WHERE StudentID = 102;
UPDATE Student
SET Email = 'charlie@[Link]' WHERE StudentID = 103;
4. Drop the Table:
sql
DROP TABLE Student;
Expected Output
Table After Creation and Insertion:
StudentID Name Course Age
101 Alice BSc 20
102 Bob BCom 21
103 Charlie BA 22
Table After Alteration (Adding Email Column):
StudentID Name Course Age Email
101 Alice BSc 20 alice@[Link]
102 Bob BCom 21 bob@[Link]
StudentID Name Course Age Email
103 Charlie BA 22 charlie@[Link]
After Drop Table:
The Student table is deleted and no longer exists in the database.

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.

SQL>SELECT * FROM CSESTUDENT;


OUTPUT:-

SNO SNAME DOJ


---------- --------------- ---------
501 ABI 12-OCT-07
502 ASHOK 03-OCT-07
503 BHAVYA 10-OCT-07
504 AKASH 05-OCT-07
505 NIKHIL 08-OCT-07

SQL> UPDATE CSESTUDENT SET SNAME='ABILASH' WHERE SNAME='ABI';

OUTPUT:-1 row updated.

SQL> ALTER TABLE CSESTUDENT ADD BRANCH VARCHAR2(6);

OUTPUT:-Table altered.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=501;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=502;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=503;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=504;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=505;


OUTPUT:-1 row updated.

SQL> SELECT * FROM CSESTUDENT;

SNO SNAME DOJ BRANCH


---------- --------------- --------- ------
501 ABILASH 12-OCT-07 CSE
502 ASHOK 03-OCT-07 CSE
503 BHAVYA 10-OCT-07 CSE
504 AKASH 05-OCT-07 CSE
505 NIKHIL 08-OCT-07 CSE

SQL> DELETE FROM CSESTUDENT WHERE SNO=501;

OUTPUT:-1 row deleted.

SQL> SELECT * FROM CSESTUDENT;

OUTPUT:-

SNO SNAME DOJ BRANCH


---------- --------------- --------- ------
502 ASHOK 03-OCT-07 CSE
503 BHAVYA 10-OCT-07 CSE
504 AKASH 05-OCT-07 CSE
505 NIKHIL 08-OCT-07 CSE
502 ASHOK 03-OCT-07 CSE

SQL> DROP TABLE CSESTUDENT;

OUTPUT:-Table dropped.

CREATING TABLES WITH CONSTRAINTS

(NOT NULL)

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) NOT NULL,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.
SQL> DESC STUD;
Name Null? Type
----------------------------------------- -------- ----------------------------
ROLLNO NOT NULL NUMBER(6)
NAME VARCHAR2(10)
BRANCH VARCHAR2(6)

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: ABHILASH
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'ABHILASH','CSE')

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> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ------
501 ABHILASH CSE
502 ABI CSE

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
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(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

(UNIQUE)

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) UNIQUE ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

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.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

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

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
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(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

SQL> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ------
501 ABHILASH CSE
502 ABI CSE

(CHECK)

SQL> create table stud(rno number(5),name varchar2(10),sal number(10) constraint no_ck


check(sal between 10000 and 30000));

Table created.

SQL> insert into stud values(&rno,'&name',&sal);


Enter value for rno: 567
Enter value for name: sachin
Enter value for sal: 29000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(567,'sachin',29000)

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.

SQL> insert into adm values(&stuid,'&sname',&per);


Enter value for stuid: 1
Enter value for sname: abi
Enter value for per: 80
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(1,'abi',80)

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.

SQL> select * from adm;


STUID SNAME PER
---------- --------------- ----------
1 abi 80
2 rohit 89
3 sachin 99
4 naveen 70

SQL> create table course(stuid number(6) constraint sid_fk references adm(stuid),branch


varchar2(5),sec varchar2(10));

Table created.

SQL> insert into course values(&stuid,'&branch','&sec');


Enter value for stuid: 1
Enter value for branch: cse
Enter value for sec: a
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(1,'cse','a')

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

SQL> delete from course where stuid=1;

1 row deleted.

SQL> delete from adm where stuid=1;

1 row deleted.
SQL>select * from adm;

STUID SNAME PER


----- --------------- - ----------
2 rohit 89
3 sachin 99
4 naveen 70

CREATING AND DROPING OF VIEWS

SQL> select * from emp2;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hollywood
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> create view emp22 as select * from emp2;

OUTPUT:-

View created.

SQL> select * from emp22;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hollywood
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> update emp22 set city='hyd' where ename='coyote';

OUTPUT:-
1 row updated.

SQL> select * from emp2;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hyd
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> select * from emp22;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hyd
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> drop table emp2;

OUTPUT:-
Table dropped.

SQL> select * from emp22;

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.

1. Example: WHERE Clause

Query:

SELECT Name, Age


FROM Students
WHERE Age > 20;

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.

2. Example: GROUP BY Clause

Query:

SELECT Department, COUNT(*) AS NumberOfEmployees


FROM Employees
GROUP BY Department;

Hypothetical Data:

EmployeeID Name Department


1 John HR
2 Alice IT
3 Bob HR
EmployeeID Name Department
4 Carol IT
5 Dave Sales

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.

3. Example: HAVING Clause

Query:

SELECT Department, AVG(Salary) AS AverageSalary


FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 50000;

Hypothetical Data:

EmployeeID Name Department Salary


1 John HR 45000
2 Alice IT 55000
3 Bob HR 52000
4 Carol IT 60000
5 Dave Sales 70000

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.

4. Example: ORDER BY Clause


Query:

SELECT Name, Age


FROM Students
ORDER BY Age DESC;

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.

5. Example: UNION Clause

Query:

SELECT Name
FROM Employees
WHERE Department = 'Sales'
UNION
SELECT Name
FROM Employees
WHERE Department = 'HR';

Hypothetical Data:

EmployeeID Name Department


1 John HR
2 Alice IT
3 Bob Sales
EmployeeID Name Department
4 Carol IT
5 Dave Sales

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.

6. Example: INTERSECTION Clause

Query:

SELECT Name
FROM Employees
WHERE Department = 'Sales'
INTERSECT
SELECT Name
FROM Employees
WHERE Age > 30;

Hypothetical Data:

EmployeeID Name Department Age


1 John HR 35
2 Alice IT 28
3 Bob Sales 32
4 Carol IT 40
5 Dave Sales 25

Output:

Name
Bob

 The query finds employees who work in the Sales department and are older than 30.
Only Bob satisfies both conditions.

7. Example: SET DIFFERENCE (EXCEPT) Clause


Query:

SELECT Name
FROM Employees
WHERE Department = 'Sales'
EXCEPT
SELECT Name
FROM Employees
WHERE Age > 30;

Hypothetical Data:

EmployeeID Name Department Age


1 John HR 35
2 Alice IT 28
3 Bob Sales 32
4 Carol IT 40
5 Dave Sales 25

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.

Combined Example with Multiple Clauses

Query:

SELECT EmployeeID, Name, SUM(SalesAmount) AS TotalSales


FROM Sales
WHERE Department = 'Sales'
GROUP BY EmployeeID, Name
HAVING SUM(SalesAmount) > 1000
ORDER BY TotalSales DESC;

Hypothetical Data:

EmployeeID Name Department SalesAmount


1 John Sales 500
2 Alice Sales 1500
3 Bob Sales 600
4 Carol Sales 300
EmployeeID Name Department SalesAmount
5 Dave Sales 2000

Output:

EmployeeID Name TotalSales


5 Dave 2000
2 Alice 1500

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

Experiment 17: To study different constraints. [SQL FUNCTION]

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.

Step 2: Insert Data into the Table


SQL Code Example:
sql
INSERT INTO Bus (BusID, BusNumber, Capacity, RouteID)
VALUES (1, 'TS01AB1234', 50, 101);

INSERT INTO Bus (BusID, BusNumber, Capacity, BusType, RouteID)


VALUES (2, 'TS02CD5678', 40, 'Non-AC', 102);

-- Attempt to insert invalid data to test constraints


INSERT INTO Bus (BusID, BusNumber, Capacity, RouteID)
VALUES (3, 'TS01AB1234', 8, 103); -- Violates UNIQUE and CHECK constraints
Output of the Third Query:
javascript
Error: Duplicate entry 'TS01AB1234' for key 'BusNumber'
Error: CHECK constraint failed: Capacity must be > 10
Step 3: Add a Foreign Key Constraint
To demonstrate the FOREIGN KEY, create another table Route.
SQL Code Example:
sql
CREATE TABLE Route (
RouteID INT PRIMARY KEY,
RouteName VARCHAR(50)
);

ALTER TABLE Bus


ADD CONSTRAINT fk_RouteID FOREIGN KEY (RouteID)
REFERENCES Route(RouteID);

Step 4: Insert Data to Test FOREIGN KEY


SQL Code Example:
sql
INSERT INTO Route (RouteID, RouteName)
VALUES (101, 'Hyderabad to Secunderabad'),
(102, 'Secunderabad to Warangal');

INSERT INTO Bus (BusID, BusNumber, Capacity, RouteID)


VALUES (3, 'TS03EF9012', 60, 105); -- Invalid RouteID
Output of the Fourth Query:
sql
Error: Cannot add or update a child row: a foreign key constraint fails

Experiment 18: To use oracle function viz aggregate, numeric, conversion, string function.
FUNCTIONS:

AGGREGATE FUNCTIONS

SQL> SELECT * FROM EMP;

output:-
ENO ENAME JOB SAL
---------- ---------- ---------- ----------
1001 STEVE SALESMAN 1500
1002 ADAM CLERK 1000
1003 EVE MANAGER 5220
1004 JAMES DIRECTOR 7000

SQL> SELECT COUNT(*)FROM EMP;

output:-

COUNT(*)
----------
4

SQL> SELECT SUM(SAL) FROM EMP;

output:-

SUM(SAL)
----------
14720

SQL> SELECT AVG(SAL) FROM EMP;

output:-

AVG(SAL)
----------
3680

SQL> SELECT MAX(SAL) FROM EMP;

output:-

MAX(SAL)
----------
7000
SQL> SELECT MIN(SAL) FROM EMP;

output:-

MIN(SAL)
----------
1000

SQL>select * from emp;

OUTPUT:-

EMPNO ENAME JOB SAL DEPTNO


---------- ---------- --------- ---------- ----------
7369 SMITH CLERK 800 20
7499 ALLEN SALESMAN 1600 30
7521 WARD SALESMAN 1250 30
7566 JONES MANAGER 2975 20
7654 MARTIN SALESMAN 1250 30
7698 BLAKE MANAGER 2850 30
7782 CLARK MANAGER 2450 10
7788 SCOTT ANALYST 3000 20
7839 KING PRESIDENT 5000 10
7844 TURNER SALESMAN 1500 30
7876 ADAMS CLERK 1100 20
7900 JAMES CLERK 950 30
7902 FORD ANALYST 3000 20
7934 MILLER CLERK 1300 10

14 rows selected.

APPLYING BY GROUP BY ---

SQL> select deptno,max(sal) from emp group by deptno;

OUTPUT:-
DEPTNO MAX(SAL)
---------- ----------
10 5000
20 3000
30 2850

SQL> select deptno,min(sal) from emp group by deptno;

OUTPUT:-

DEPTNO MIN(SAL)
---------- ----------
10 1300
20 800
30 950

SQL> select deptno,max(sal) from emp group by deptno having max(sal)<3000;

OUTPUT:-

DEPTNO MAX(SAL)
---------- ----------
30 2850

SQL>select deptno,min(sal) from emp group by deptno having min(sal)>1000;

OUTPUT:-

DEPTNO MIN(SAL)
---------- ----------
10 1300

SQL> select ename,count(*) from emp group by deptno;

OUTPUT:-

DEPTNO COUNT(*)
---------- ----------
10 3
20 5
30 6
3 rows selected.
CONVERSION FUNCTIONS(TO_CHAR)

SQL>select to_char(65,'RN')from dual;


OUTPUT:LXV

SQL>select to_char(65,'rn')from dual;


OUTPUT:lxv

SQL>select to_char(58,'s9999')from dual;


OUTPUT:+58

SQL>select to_char(-100,'s9999')from dual;


OUTPUT:-100

SQL> select to_char(41,'XXXX')from dual;


OUTPUT:29

SQL> select to_char(10,'XXXX')from dual;


OUTPUT:A

SQL> select to_char(sysdate,'day')from dual;


OUTPUT:MONDAY

SQL> SELECT TO_CHAR(SYSDATE,'MONTH')FROM DUAL;


OUTPUT:JANUARY

SQL> SELECT TO_CHAR(SYSDATE,'YEAR')FROM DUAL;


OUTPUT:TWO THOUSAND NINE

SQL> select to_char(123456,'9g99g999')from dual;


OUTPUT:1,23,456

SQL> select to_char(1234,'l9999')from dual;


OUTPUT:$1234

SQL> select to_char(123456,'9g99g999d999')from dual;


OUTPUT:1,23,456.000

SELECT TO_CHAR(2234,'L9999','NLS_CURRENCY=RS')FROM DUAL;


OUTPUT:RS2234
STRING FUNCTIONS

SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;

OUTPUT:-ORACLECORPORATION

SQL>SELECT LPAD(‘ORACLE’,15,’*’)FROM DUAL;

OUTPUT:-*********ORACLE

SQL>SELECT RPAD(‘ORACLE’,15,’*’)FROM DUAL;

OUTPUT:-ORACLE*********

SQL>SELECT LTRIM(‘SSMITHSS’,’S’)FROM DUAL;

OUTPUT:-MITHSS

SQL>SELECT RTRIM(‘SSMITHSS’,’S’)FROM DUAL;

OUTPUT:-SSMITH

SQL>SELECT LOWER(‘DBMS’)FROM DUAL;

OUTPUT:-dbms

SQL>SELECT UPPER(‘dbms’)FROM DUAL;

OUTPUT:-DBMS

SQL>SELECT INITCAP(‘ORACLE’,’CORPORATION’)FROM DUAL;

OUTPUT:-Oracle Corporation

SQL>SELECT LENGTH(‘DATABASE’)FROM DUAL;

OUTPUT:-8

SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;


OUTPUT:-CDEF

SQL>SELECT INSTR('CORPORATE FLOOR','OR',3,2)FROM DUAL;

OUTPUT:-14
DATE FUNCTIONS

SQL>SELECT SYSDATE FROM DUAL;

OUTPUT:-29-DEC-08

SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;

OUTPUT:-05-JAN-09

SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;

OUTPUT:-28-FEB-09

SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;

OUTPUT:-31-DEC-08

SQL>SELECT MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP;

OUTPUT:-

SQL>SELECT LEAST('10-JAN-07','12-OCT-07')FROM DUAL;

OUTPUT:-10-JAN-07

SQL>SELECT GREATEST('10-JAN-07','12-OCT-07')FROM DUAL;

OUTPUT:-10-JAN-07
SQL>SELECT TRUNC(SYSDATE,'DAY')FROM DUAL;

OUTPUT:-28-DEC-08

SQL>SELECT TRUNC(SYSDATE,'MONTH')FROM DUAL;

OUTPUT:-01-DEC-08
SQL>SELECT TRUNC(SYSDATE,'YEAR')FROM DUAL;

OUTPUT:-01-JAN-08

SQL>SELECT ROUND(SYSDATE,'DAY')FROM DUAL;

OUTPUT:-28-DEC-08

SQL>SELECT ROUND(SYSDATE,'MONTH')FROM DUAL;

OUTPUT:-01-JAN-09

SQL>SELECT ROUND(SYSDATE,'YEAR')FROM DUAL;

OUTPUT:-01-JAN-09

NUMBER FUNCTIONS

SQL> select round(12.36), round(14.63) from dual;

OUTPUT:-

ROUND(12.36) ROUND(14.63)
------------ ------------
12 15

SQL> select floor(12.87), floor(11.23) from dual;

OUTPUT:-
FLOOR(12.87) FLOOR(11.23)
------------ ------------
12 11

SQL> select ceil(16.23), ceil(12.78) from dual;

OUTPUT:-
CEIL(16.23) CEIL(12.78)
----------- -----------
17 13

SQL> select trunc(56.63) from dual;

OUTPUT:-

TRUNC(56.63)
------------
56

SQL> select mod(11,4) from dual;

OUTPUT:-

MOD(11,4)
----------
3

SQL> select power(2,3) from dual;

OUTPUT:-

POWER(2,3)
----------
8

SQL> select sign(0),sign(34),sign(-56) from dual;

OUTPUT:-

SIGN(0) SIGN(34) SIGN(-56)


---------- ---------- ----------
0 1 -1
SQL> select abs(12),abs(-89) from dual;

OUTPUT:-

ABS(12) ABS(-89)
---------- ----------
12 89

SQL> select sqrt(25) from dual;

OUTPUT:-

SQRT(25)
--------

Experiment 19: To understand use and working with joins.

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.

Types of SQL Joins

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

Understanding Joins in SQL

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.

Types of SQL Joins

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:

Let's assume we have two tables:

 employees (Employee details)


 departments (Department details)

employees table:

employee_id name department_id


1 Alice 1
2 Bob 2
3 Charlie 1
4 David 3

departments table:
department_id department_name
1 Sales
2 HR
3 IT

INNER JOIN Query:

SELECT [Link], d.department_name


FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;

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

2. LEFT JOIN (LEFT OUTER JOIN)

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:

LEFT JOIN Query:

SELECT [Link], d.department_name


FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;

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:

employee_id name department_id


1 Alice 1
2 Bob 2
3 Charlie 1
4 David 3
5 Eve NULL

LEFT JOIN Output:

name department_name
Alice Sales
Bob HR
Charlie Sales
David IT
Eve NULL

3. RIGHT JOIN (RIGHT OUTER JOIN)

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:

RIGHT JOIN Query:

SELECT [Link], d.department_name


FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
Explanation:

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

4. FULL JOIN (FULL OUTER JOIN)

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:

FULL JOIN Query:

SELECT [Link], d.department_name


FROM employees e
FULL OUTER JOIN departments d ON e.department_id = d.department_id;

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:

CROSS JOIN Query:

SELECT [Link], d.department_name


FROM employees e
CROSS JOIN departments d;

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

Experiment 20: To understand use and working of sub-queries.


A subquery is a query nested inside another query (such as in a SELECT, INSERT, UPDATE,
or DELETE statement). Subqueries are used to retrieve data that will be used in the main query
for various purposes, like filtering results or computing values.
Subqueries are helpful when you need to perform operations that involve multiple steps or are
too complex to be achieved in a single query.

Create Database and Tables

sql
Copy code
CREATE DATABASE CompanyDB;

USE CompanyDB;

-- Create departments table


CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50),
location VARCHAR(50)
);

-- Create employees table


CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2),
department_id INT,
manager_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

2. Insert Sample Data

Here is some sample data for departments and employees:

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

Sample Queries with Subqueries and Expected Outputs

1. Subquery in SELECT Clause

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:

name salary avg_department_salary


Alice 60000.00 67500.00
Bob 75000.00 67500.00
Charlie 85000.00 67500.00
David 50000.00 65000.00
Eva 90000.00 67500.00
Frank 45000.00 60000.00

2. Subquery in WHERE Clause

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

3. Subquery with IN Operator


Query:
Find employees working in departments located in 'New York'.

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:

name salary department_id


Bob 75000.00 1
Charlie 85000.00 2
Eva 90000.00 3
5. Subquery in FROM Clause (Inline View)

Query:
Find the average salary of employees who earn more than 50,000 in each department.

sql

SELECT department_id, AVG(salary) AS avg_salary


FROM (SELECT department_id, salary FROM employees WHERE salary > 50000) AS
high_salary_employees
GROUP BY department_id;

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

6. Subquery with EXISTS

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

7. Subquery in UPDATE Statement

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

8. Subquery in DELETE Statement

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.

You might also like