You are on page 1of 37

DATABASE MANAGEMENT SYSTEMS LAB

Course Objectives:
Introduce ER data model, database design and normalization Learn SQL basics
for data definition and data manipulation
Course Outcomes:
Design database schema for a given application and apply normalization
Acquire skills in using SQL commands for data definition and data
manipulation.
Develop solutions for database applications using procedures, cursors and
triggers

LIST OF EXPERIMENTS:
1. Concept design with E-R Model
2. Relational Model
3. Normalization
4. Practicing DDL commands
5. Practicing DML commands
6. Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION,
INTERSECT,
Constraints etc.)
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation
and dropping of Views.
8. Triggers (Creation of insert trigger, delete trigger, update trigger)
9. Procedures
10. Usage of Cursors

1
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 1: E-R Model

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 an independent existence. (or)
A real word object that can be distinguished from other objects is called an entity.
There are two types of entities:
1) Strong Entity
2) Weak Entity

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 entity set)

2. Ellipse (Attributes)

3.Rhombus (Relationship set)

4. Double Rectangle (Weak Entity set)

5. Undirected Line(Flow of Relationship)

6. Directed Line (Flow of Relationship)


2
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

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_Id is 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
Primary Key.

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.

3
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

1. BUS Entity:

The attributes are:

i. Bus_No
ii. Source
iii. Destination
iv. Dep_Time

The E-R Model is as follows:

Dep_Tim Destination
e
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

4
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

Age Sourc
e
Journey_Dat Destinatio
e n
Ticket_No Dep_Tim
e
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:

Nam Age
e
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_Sea Addres
5
ts s
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

Journey_Dat Contact_N
e o

Status
PNR_No
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_Sea Addres
ts s
Journey_Dat Contact_N
e o
Status
PNR_No
CANCELLATION

In the above figure PNR_No is the Foreign Key

6
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 2: Concept Design with E-R Model

Relate the entities appropriately. Apply cardinalities for each relationship. Identify the strong entities and
weak entities (if any). Indicate the type of relationships (total/partial). Try to incorporate generalization,
aggregation, specialization etc… wherever required.

Relationship between BUS Entity and PASSENGER Entity:

The following diagram depicts the relationship exists between BUS Entity and PASSENGER Entity.

Dep_Tim Destination
e
Bus_No Source

BUS

Travel
in

PASSENGER
PNR_No PPNo

Ticket_No Sex

Nam Age
e

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

7
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

RESERVATION Entity.

Nam Age
e
Ticket_No Sex

PNR_No PPNo
PASSENGER

Takes

RESERVATION

PNR_No Statu
s

Journey_Date Contact_N
o
No_Of_Seat Addres
s s

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:

8
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

The following diagram depicts the relationship exists between PASSENGER Entity and

CANCELLATION Entity.

Nam Age
e
Ticket_No Sex

PNR_No PPNo
PASSENGER

Cancel
s

CANCELLATION

PNR_No Status

Journey_Date Contact_N
o
No_Of_Seat Addres
s s

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

9
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

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.

WEEK 3: Relational Model

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 Entity Table:


SQL> CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar (15), Destination varchar
(15), Weekday varchar (10));

SQL> insert into Bus values('AP01','Hyderabad','Karimnagar',’Sunday’);

SQL> insert into Bus values('AP02','Delhi','Mumbai',’Monday’);


10
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

SQL> insert into Bus values('AP03','Chennai','Srinagar',’Wednesday’);

SQL> insert into Bus values('AP04','Bangalore','Hyderabad',’Sunday’);

SQL> insert into Bus values('AP05','Karimnagar','Warangal',’Friday’);

SQL> Select * from Bus;

2.TICKET 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));

SQL> insert into Ticket values(1,’01-jan-2010’,35,'F','Hyderabad',9,'Karimnagar',23);

SQL> insert into Ticket values(2,’02-jan-2010’,30,'F','Delhi',5,'Mumbai',18);

SQL> insert into Ticket values(3,’03-jan-2010’,22,'F','Chennai',6,'Srinagar',16);

SQL> insert into Ticket values(4,’04-jan-2010’,25,'M','Bangalore',8,'Hyderabad',14);

SQL> insert into Ticket values(5,’05-jan-2010’,28,'M','Karimnagar',5,'Warangal',13);


SQL> Select * from Ticket;

3. PASSENGER Entity Table:

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),Cate-
gory varchar (8));
SQL> insert into Passenger values(1000,01,'Anitha',35,'F',10,’A/C’);

SQL> insert into Passenger values(2000,02,'Haritha',30,'F',20,’NONA/C’) ;

SQL> insert into Passenger values(3000,03,'Srilatha',22,'F',30, ’A/C’) ;

SQL> insert into Passenger values(4000,04,'Chaitanya',25,'M',40, ’A/C’) ;

SQL> insert into Passenger values(5000,05,'Saketh',28,'M',50, ’NONA/C’) ;

SQL> insert into Passenger values(6000,06,'Anirudh',27,'M',60, ’NONA/C’);

11
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

SQl> Select * from Passenger;

4. RESERVATION Entity Table:

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

SQL> insert into reserve values(1000,'1-feb-2010’,5,'Ramanthpur',0123456789,'Y');

SQL> insert into reserve values(2000,’2-feb-2010’,2,'KPHB',1234567890,'Y');

SQL> insert into reserve values(3000,’3-feb-2010’,3,'Dilsukhnagar',1234567809,'Y');

SQL> insert into reserve values(4000,’4-feb-2010’,4,'Tarnaka',1234123412,'Y');

SQL> insert into reserve values(5000,’5-feb-2010’,5,'DDCOLONY',1234512345,'Y');

SQL> Select * from Reserve;

4. CANCELLATION Entity Table:

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


key(PNR_NO) references passenger(PNR_NO),Journey_date date,No_of_seats
NUMERIC(8), Address Varchar(40),Contact_No NUMERIC(10),Status char(2));

SQL> insert into cancellation values(1000,'1-Jan-


2010',5,'Ramanthpur',0123456789,'N');

SQL> insert into cancellation values(2000,'2-feb-2010',5,'KPHB',1234567890,'N');

SQL> insert into cancellation values(3000,'3-feb- 2010',4,'Dil-


sukhnagar',1234567809,'N');

SQL> insert into cancellation values(4000,'4-Apr-2010',2,'tarnaka',1234123412,'N');

SQL> insert into cancellation values(5000,'5-May-


2010',6,'DDCOLONY',1234512345,'N');

SQL> Select * from Cancellation;

12
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 4: NORMALIZATION

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

13
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

TICKET
Ticket_No Journey_Date Age Sex Source Destination Dep_Time
2345 20-08-2016 25 F Anantapur Kurnool 10:30am
5678 25-08-2016 20 M Hyderabad Chennai 07:00pm
2457 30-08-2016 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2016 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-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No

CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 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-2016 25 F Anantapur Kurnool 10:30am
5678 25-08-2016 20 M Hyderabad Chennai 07:00pm
2457 30-08-2016 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2016 28 F Kadapa Hyderabad 10:30pm
14
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

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-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No

CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 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 normal form
2. No partial dependency exists between non-key attributes and key attributes.

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_No is the key attribute for Bus


 Ticket_No is the key attribute for Ticket
 PNR_No is the key attribute for passenger
 Other attributes like name, age, sex, Journey_Dateetc are non-key attributes

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

15
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

 Source, Destination and Dep_Time depends only on Bus_No


 Journey_Date depends only on Ticket_No
 Ticket_No, Name, Age, Sex, PPNo depends on PNR_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-2016
5678 25-08-2016
2457 30-08-2016
4679 05-09-2016

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-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No

CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 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 in 2NF
2. No transitive dependency exists between non-key attributes and key attributes.

BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
16
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

4567 Kadapa Hyderabad 10:30pm


1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm

TICKET
Ticket_No Journey_Date
2345 20-08-2016
5678 25-08-2016
2457 30-08-2016
4679 05-09-2016

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-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 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 normal form.

1.Reservation status table

PNR_No Journey_Date Status


1 20-08-2016 Yes
3 30-08-2016 No
2 25-08-2016 Yes
4 05-09-2016 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-2016 1 Bangalore 9989892731 No

17
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

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-2016 No

2.Cancellation details table

PNR_No No_of_seats Address Contact_No


3 1 Bangalore 9989892731

WEEK 5: Installation of MySQL and practicing DDL commands

18
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

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 database objects
C). DQL command: - To retrieve the data from a database.
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 and size.
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 created table.
a) add new columns
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 a table:


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


particular field
Syntax: Alter table <tablename> modify <col> <newdatatype>(<newsize>);
Ex: alter table emp modify ename varchar(15);
5. Renaming the tables: It is used to change the table name which was already created.
Syntax: Rename <oldtable> to <new table>;

Ex: rename emp to emp1;


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

19
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

7. Destroying tables. Drop command is used to destroy the existing table (or) a view.
Syntax: Drop table <tablename>;
Ex: drop table emp;
BUS:
SQL> CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar (15),
Destination varchar (15));

SQL> desc Bus;


SQL> Alter table Bus add (Weekday varchar (10));
SQL> desc Bus;
SQL> Alter table Bus modify (BusNo varchar(10));
SQL> Alter table Bus drop column BusNo;

SQL> desc Bus;

SQL> Drop table bus;

SQL> Rename Bus to Bus1;

SQL> desc Bus1;

SQL> Truncate table bus;

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

SQL> desc Passenger;


SQL> Alter table Passenger add (Category varchar (8));
SQL> desc Passenger;
SQL> Alter table Passenger modify (PNR_No number(9));

CANCELLATION:

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


references passenger(PNR_NO),Journey_date date,No_of_seats NUMERIC(8), Address
Varchar(40),Contact_No NUMERIC(10));
SQL> desc Cancellation;

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

SQL> desc Cancellation;

20
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

SQL> Alter table Cancellation modify (PNR_No number(9));

SQL> Alter table Cancellation drop column PNR_No;

SQL> desc Cancellation;

SQL> Drop table Cancellation;

SQL> Rename Cancellation to Cancellation1;

SQL> desc Cancellation1;

SQL> Truncate table Cancellation1;

21
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 6: Practicing DML Commands

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. SELECT Command:

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 * FROM Bus;

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

SQL> INSERT INTO tablenameVALUES(value list);

 To insert the multiple values into the table the following syntax is used.
SQL> INSERT INTO tablenameVALUES(&value1,&value2,………,valueN);

Example:

22
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

 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

3. 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’ WHERE PNR_No=1;

4. 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 WHERE PNR_No=1;

23
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 7: Querying

In this week you are going to practice queries (along with sub queries) using ANY, ALL,

IN, EXISTS, NOT EXISTS, UNION, INTERSECT, Constraints etc…

Practice the following Queries:

1. Display unique PNR_no of all passengers.

SQL>SELECT PNR_No FROM Passenger;

2. Display all the name of male passengers.

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

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

SQL>SELECT Ticket_No, Name FROM Passenger;

4. Display the sorted list of passenger names.

SQL> SELECT * FROM Passenger ORDER BY NAME;

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

‘A’.

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

6. Find the names of passengers whose age between 30 and 45.

24
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

SQL>SELECT Name FROM Passenger WHERE Age >=30 and Age <=50;

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

SQL>SELECT Bus_No FROM Bus WHERE Days IN (‘Tuesday’);

8. Display the source and the destination having journey time more than 10 hours.

SQL>SELECT Source, Destination FROM Bus WHERE Hours>=8;

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

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

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

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

WEEK 8 and WEEK 9: Querying (Continued…)

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

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

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

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

3. Find the distincet numbers that are present.

SQL>SELECT DISTINT PNR_No FROM Passenger;

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

GROUP BY on pnr_no).

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


PNR_No;

5. Write a query to count the number of tickets for the buses , which travelled after the

date 14/13/2009(use HAVING CLAUSES).

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;

25
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

6. Find the total no of cancellation seats.

SQL>SELECT sum(No_of_seats) No_of_seats FROM Cancellation;

7. Find the number of tickets booked in each class where the number of seats is greater

than 1 (use GROUP BY ,WHERE and HAVING VLAUSES).

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;

WEEK 10: TRIGGERS

In this week you are going to work on Triggers. Creation of Insert Trigger, Delete Trigger,

Update Trigger. Practice Triggers using above database.

DELIMITER //
CREATE TRIGGER insert_trig BEFORE INSERT ON Passenger
FOR EACH ROW
BEGIN
IF NEW.Age<0 THEN
SET NEW.Age=0;
END IF;
END //
DELIMITER ;

NOTE: Triggers can be used on only existing tables.

26
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

WEEK 11: Procedures

In this session you are going to learn Creation of stored procedure, execution of procedure and
modification of procedure. Practice procedures using above database.

Write a program to create stored procedures, execution of procedure and modification


of procedure.

DELIMITER / /
CREATE PROCEDURE p1 ()
BEGIN
SELECT Ticket_No, Name, Ph_no FROM Passenger WHERE No_of_seats>2;
END //
DELIMITER ;

DELIMITER //
CREATE PROCEDURE p2 (IN n varchar (20))
BEGIN
SELECT Ticket_No, PNR_No, Age, Ph_no FROM Passenger WHERE Name=n;
END //
DELIMITER ;

27
B.TECH :III / I
DATABASE MANAGEMENT SYSTEMS LAB

28
B.TECH :III / I
WEEK 12: Cursors

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 time.Close the
cursor when
done.

DELIMITER //
CREATE PROCEDURE not_reserved ()
BEGIN
DECLARE pnr, seats, pno numeric;
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 ;
Additional Programs
19.1 IMPLEMENTATION OF DATA AND BUILT IN FUNCTIONS IN SQL

CHARACTER/STRING FUNCTION:

SQL> select upper('welcome') from dual;

SQL> select upper('hai') from dual;

SQL> select lower('HAI') from dual;

SQL> select initcap(‘hello world') from dual;

SQL> select ltrim(' hai') from dual;

SQL> select rtrim('hai ')from dual;

SQL> select rtrim(' hai ')from dual;

SQL> select concat('JNTU',' university')from dual;

SQL> select length('JNTU’)from dual;

SQL> select replace('JNTU university', 'JNTU','SPEC')from dual;

SQL> select substr('JNTU', 7,6)from dual;

SQL> select rpad('hai',3,'*')from dual;

SQL> select lpad('hai',3,'*')from dual;

SQL> select replace('Dany','y','ie')from dual;

SQL> select translate('cold','ld','ol')from dual;


19.2 NUMERIC FUNCTION

SQL> select round(15.6789)from dual;

SQL> select ceil(23.20)from dual;

SQL> select floor(34.56)from dual;

SQL> select trunc(15.56743)from dual;

SQL> select sign(-345)from dual;

SQL> select abs(-70)from dual;


19.3 MATH FUNCTION:

SQL> select abs(45) from dual; ABS(45)

SQL> select power(10,12) from dual; POWER(10,12)

SQL> select mod(11,5) from dual; MOD(11,5)

SQL> select exp(10) from dual; EXP(10)

SQL> select sqrt(225) from dual; SQRT(225)


Open Ended Programs
1. Write a function to accept the empno and return exp with minimum 3 decimal?
2. Write a function to accept a grade and return the number of emps belongs to that grade?
3. Write a function to accept a character string and print it in case?
Viva Questions
1. Difference between file systems and database management systems?
2. What is the difference between update and insert command?
3. What is the entity relationship model?
4. What are super, primary, candidate and foreign keys?
5. What is the difference between primary key and unique constraints?
6. What are the differences between DDL, DML and DCL in SQL?
7. What is Join?
8. What is Identity?
9. What are the uses of view?
10. What is a stored procedure?
11. What is the difference between Trigger and Stored Procedure?
12. What are indexes?
13. What is the use of normalization?
14. What are clustered and non-clustered Indexes?
15. Define Fragmentation.
16. What do you mean by Index hunting?
17. Define Aggregate functions.
18. Why is group-clause used?
19. What are the various kinds of interactions catered by DBMS?
20. Define DDL Interpreter.
21. Define Entity.
22. What do you mean by Entity type extension?
23. Define Scalar functions.
24. Enlist the types of cursor.
25. What is the use of groupby command in dbms?

You might also like