Вы находитесь на странице: 1из 54

Department of Computer Science & Engineering

DATABASE MANAGEMNT SYSTEMS

Y SUBBA RAYUDU
M. Tech

INDEX
SNO
1

NAME OF PROGRAM
Syllabus

Page No
4-14

2 Required Work
3 Program Education Objectives

15

4 Program out comes


5 Course Outcome PO mapping

17

6 Course Outcomes Lab experiments mapping

18

Y SUBBA RAYUDU

16
18

Page 1

E-R Model

19-21

Concept Design with E-R Model

22-24

Relational Model

25-26

10 Normalization
11 Installation of Mysql and practicing DDL commands

27-33

12 Practicing DML Commands


13 Querying

36-37

34-35
38-40

14 Querying (Continued)
15 Querying (Continued)

41

16 Triggers
17 Procedures

43

18 Cursers
19 Additional programs

45

20 Write a program to create trigger event


21 Write a program to create Procedure event

47

22 Write a program to create cursor event


23 Open Ended Lab Programs

49
50-51

24 Viva Questions

52-53

42
44
46
48

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD


II Year B.Tech. CSE -II Sem

L T/P/D C
-

(A40584) DATA BASE MANAGEMENT SYSTEMS LAB


Objectives:

Y SUBBA RAYUDU

Page 2

-/3/-

This lab enables the students to practice the concept learnt in the subject DBMS by
developing a database for an example company named "Roadway Travels" whose
description is as follows. The student is expected to practice the designing, developing
and querying a database in the context of example database "Roadway travels".
Students are expected to use "Mysql" database.

Roadway Travels
"Roadway Travels" is in business since 1997 with several buses connecting different places in
india. Its main office is located in Hydearabd.
The company wants to computerize its operations in the following areas:

Reservation and Ticketing

Cancellations

Reservation & Cancellation:


Reservations are directly handled by booking office. Reservations can be made 30 days in
advance and tickets issued to passenger. One Passenger/person can book many tickets (to
his/her family).
Cancellations are also directly handed at the bokking office.
In the process of computerization of Roadway Travels you have to design and develop a
Database which consists the data of Buses, Passengers, Tickets, and Reservation and
cancellation details. You should also develop query's usinf SQL to retrieve the data from
database.
The above process involves many steps like 1. Analyzing the problem and identifying the
Entities and Relationships, 2. E-R Model 3. Relational Model 4. Normalization 5. Creating
the database 6. Querying. Students are suppossed to work on these steps week wise and
finally create a complete "Database System" to Roadway Travels. Examples are given at
every experiment for guidance to students.

Experiment 1: E-R Model


Analyze the carefully and come up with the entities in it. Identitfy 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 others keys like candidate keys,
partial keys, if any.
Y SUBBA RAYUDU

Page 3

Example: Entities:
1. BUS
2. Ticket
3. Passenger
Relationships:
1. Reservation
2. Cancellation
PRIMARY KEY ATTRIBUTES:
1. Ticket ID (Ticket Entity)
2. Passport ID (Passenger Entity)
3. Bus_No (Bus Entity)
A part from the above mentioned entities you can identify more. The above mentioned are
few.
Note: The student is required to submit a document by writing the Entities and keys to the lab
teacher.

Experiment 2: Concept design with E-R Model

Relate the entities appropriately. Apply cardnalities for each relationship. Identify strong
entities and weak entities (if any). Indicate the type of relationships (total / partial). Try to
incorporate generalization, aggregation, specialization etc wherever required.
Example: E-R diagram for bus

Note: The student is required to submit a document by drawing the E-R Diagram to the lab
teacher.

Y SUBBA RAYUDU

Page 4

Experiment 3: Relational Model


Represent all the entities (Strong, Weak) in tabular fashion. Represent realtionships in a
tabular fashion. There are different ways of representing relationships as tables based on the
requirement. Different types of attributes (Composite, Multi-valued, and Derived) have
different way of representation.
Example: The passenger tables look as below. This is an example. You can add more
attributes based on E-R model. This is not a normalized table.

Passenger
Name

Age

Sex

Address

Ticket_id

Passport ID

NotEg: The student is required to submit a document by Represent relationships in a tabular


fashion to the lab teacher.

Experiment 4: Normalization
Database normalization is a technique for designing realtional database tables to minimize
duplication of information and, in so doing, to safegaurd the database against certain types of
logical or structural problems, namely data anormalies. 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 tha table is updated, leading to a loass 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.
For the above table in the First normalization we can remove the multiple valued attribute
Ticket_id and place it in another table along with the primary key of passenger.
First Normal Form: The above table can divided into two tables as shown below.

Y SUBBA RAYUDU

Page 5

Passenger

Name

Age

Passport ID

Sex

Address

Passport ID

Ticket_id

You can do the second and third normal forms if required. Anyhow Normalized tables are
given at the end.

Experiment 5: Installation of MySQL and practice DDL commands


Installation of MySQL. In this week you will learn Creating databases, How to create tables,
altering the database, droping tables and databases if not required. You will also try truncate,
rename commands etc.
Example for creation of a normalized "Passenger" table.
CREATE TABLE Passenger(
Passport_id INTEGER PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INTEGER NOT NULL,
Sex CHAR,
Address VARCHAR(50) NOT NULL
);
Similarly create all other tables. Note: Detailed creation of tables is given at the end.
Y SUBBA RAYUDU

Page 6

Experiment 6: Practicing DML commands


DML commandsare used for managing data within schema objects. Some examples:

SELECT - retrieve data from the database

INSERT - insert data into a table

UPDATE - updates exisitng data within a table

DELETE - deletes all records from a table, the space for the records remain

insert values into "Bus" table:


insert into Bus values (1234, 'hyderabad', 'tirupathi');
insert into Bus values(2345, 'hyderabad', 'banglore');
insert into Bus values(23, 'hyderabad', 'kolkata');
insert into Bus values(45, 'tirupathi', 'bangalore');
insert into Bus values(34, 'hyderabad', 'chennai');
insert values into "Passenger" table:
insert into Passenger values(1, 45, 'ramesh', 45, 'M', 'abc123');
insert into Passenger values(2, 78, 'geetha', 36, 'F', 'abc124');
insert into Passenger values(45, 90, 'ram', 30, 'M', 'abc12');
insert into Passenger values(67, 89, 'ravi', 50, 'M', 'abc14');
insert into Passenger values(56, 22, 'seetha', 32, 'F', 'abc55');
Few more Examples of DML commands:
SELECT * FROM Bus; (selects all the attributes and displays)
UPDATE Bus SET Bus_No = 1 WHERE Bus_No = 2;

Y SUBBA RAYUDU

Page 7

Experiment 7: Querying
In this week you are going to practice queries(along with sub queries) using ANY, ALL, IN,
EXISTS, NOT EXIST, UNION, INTERSECT, Constraints etc.
Practice the following Queries:
1. Dispaly unique PNR_No of all passengers.
2. Display all the names of male passengers.
3. Display the ticket numbers and names of all the passengers.
4. Find the ticket numbers of the passengers whose name start with 'r' and ends with 'h'.
5. Find the names of passengers whose age is between 30 and 45.
6. Display all the passengers names beginning with 'A'
7. Display the sorted list of passengers names.
Experiment 8 and Experiment 9: Querying (continued...)
You are going to practice queries using Aggregate functions (COUNT, SUM, AVG, MAX,and
MIN), GROUP BY, HAVING and Creation and droping of VIEWS.
1. Write a Query to display the information present in the Passenger and cancellation
tables. Hint: Use UNION Operator.
2. Display the number of days in a week on which the 9W01 bus is available.
3. Find number of tickets booked for each PNR_No using GROUP BY CLAUSE. Hint:
Use GROUP BY on PNR_No.
4. Find the distinct PNR numbers that are present.
5. Find the number of tickets booked by a passenger where the number of seats is greater
than 1. Hint: Use GROUP BY, WHERE and HAVING CLAUSES.
6. Find the total number of cancelled seats.
Experiment 10: Triggers
In this week you are going to work on Triggers. Creation of insert trigger, delete trigger,
update trigger. Practice triggers using the above database.
Y SUBBA RAYUDU

Page 8

E.g:
CREATE TRIGGER updatecheck BEFORE UPDATE ON passenger FOR EACH ROW
BEGIN
IF NEW.TickentNO > 60 THEN
SET New.TickentNO = TicketNo;
ELSE
SET New.TicketNo = 0;
END IF;
END

Experiment 11: Procedures


In this session you are going to learn Creation of stored procedure, Execution of procedure
and modification of procedure. Practice procedures using the database.
E.g:
CREATE PROCEDURE myproc()
BEGIN
SELECT
FROM
WHERE

COUNT(Tickets)
Ticket
age >= 40;

END;

Experiment 12: Cursors


In this week you need to do the following: Declare a cursor that defines a result set.
Open the cursor to establish the result set. Fetch the data into local variables as needed from
the cursor, one row at a time. Close the cursor when done
CREATE PROCEDURE myproc(in_customer_id INT)
BEGIN
DECLARE v_id INT;
DECLARE v_name VARCHAR(30);
Y SUBBA RAYUDU

Page 9

DECLARE c1 CURSOR FOR


SELECT stdid, stdFirstname FROM students WHERE stdid - in_customer_id;

OPEN c1;
FETCH c1 INTO v_id, v_name;
CLOSE c1;
END;

Tables:
BUS
Bus No: VARCAHR : PK(primary key)
Source: VARCHAR
Destination: VARCHAR
Passenger
PPNO: VARCHAR(15) : PK
Name: VARCHAR(15)
Age: INT(4)
Sex: CHAR(10) : Male/Female
Address: VARCHAR(20)
Passenger_Tickets
PPNO: VARCHAR(15) : PK
Ticket_No: NUMERIC(9)

Reservation
PNR_No: NUMERIC(9) : FK
Journey_date: DATETIME(8)
No_of_seats: INT(8)
Y SUBBA RAYUDU

Page 10

Address: VARCHRA(50)
Contact_No: NUMERIC(9) --> Should not less than 9 and Should not accept any other
character other than interger
STATUS: CHAR(2) : Yes/No
Cancellation
PNR_No: NUMERIC(9) : FK
Journey_date: DATETIME(8)
No_of_seats: INT(8)
Address: VARCHRA(50)
Contact_No: NUMERIC(9) --> Should not less than 9 and Should not accept any other
character other than interger STATUS: CHAR(2) : Yes/No
Ticket
Ticket_No: NUMERIC(9) : FK
Journey_date: DATETIME(8)
Age: INT(4)

Sex: CHAR(10) : Male/Female


Source: VARCHAR
Destination: VARCHAR
Dep_time: VARCHAR

Y SUBBA RAYUDU

Page 11

2. Required Work
There will be homework assignments of about 12 programmatic/project scripts/memos, most
of which will involve programming. Assignments are due at the beginning of its theoretic
class on the date specified. Late assignments will receive 75% of full credit if they are handed
in within one week of the specified due date. After one week, no credit will be given or else
losing of credits is made in practice. There is no specific attendance policy for the course,
although it is expected that absences will leave the student unprepared for tests and
assignments. Tests will not be rescheduled except in extreme circumstances. However, the
lowest quiz grade will be dropped. Grades will be determined as follows:
Day to- Day evaluation Marks

15 marks

Internal practical Examination

10 marks

Final Exam (University / External End Exam)

50 marks

At the minimum, traditional grading cutoffs will apply. That is, 90% is guaranteed an A, 87%
is guaranteed a B+, etc. Depending on class performance, some shifting of grades (in an
upward direction only) may occur as final letter grades are assigned.

Y SUBBA RAYUDU

Page 12

3. Program Educational Objectives (PEOs)


1. LEARN AND INTEGRATE
Graduates of the program will have through understanding of key principles and practices
of computing, engineering, mathematics and sciences required for identifying,
formulating and solving both hardware and software related problems, while engaging in
a successful career or higher studies or research.
2. THINK AND CREATE
Graduates of the program will be capable of analyzing real world problems and then,
design and develop solutions for the same, meeting the needs of the industry and society.
3. COMMUNICATE AND ORGANIZE
Graduates will have appropriate interpersonal and organizational skills, ethical values,
good communication skills and leadership skills.
4. Program Outcomes
a. an ability to apply knowledge of mathematics, science and engineering
b. an ability to design and conduct experiments, as well as to analyze and interpret data
c. an ability to design a system, component, or process to meet desired needs within
realistic constraints such as economic, environmental, social, political, ethical, health
and safety, manufacturability, and sustainability
d. an ability to function on multidisciplinary teams
e. an ability to identify, formulate, and solve engineering problems
f. an understanding of professional and ethical responsibility
g. an ability to communicate effectively (3g1 orally, 3g2 written)
h. the broad education necessary to understand the impact of engineering solutions in a
global, economic, environmental, and societal context
i. a recognition of the need for, and an ability to engage in life-long learning
j. a knowledge of contemporary issues
k. an ability to use the techniques, skills, and modern engineering tools necessary for
engineering practice.
l. An ability to succeed in competitive examinations like GATE, IES, GRE etc.

Y SUBBA RAYUDU

Page 13

Associated course: DataBase Management System


Course outcomes:
1. Demonstrate the basic elements of a relational database management system.
2. Ability to identify the data models for relevant problems.
3. Ability to design entity relationship and convert entity relationship diagrams into
RDBMS and formulate SQL queries on the respective data.
4. Apply normalization for the development of application softwares.

Y SUBBA RAYUDU

Page 14

5.Course Outcomes PO mapping


Outcomes
a

6. Course Outcomes Lab experiments mapping


Outcomes

Experiment numbers
1

Y SUBBA RAYUDU

Page 15

10

11

12

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.

1.
2.
3.
4.
5.

The entities for the above company named Roadway Travels are as follows
Bus
Ticket
Passenger
Reservation
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 as follows:

Dep_Time

Destination
Source

Bus_No
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:

Y SUBBA RAYUDU

Page 16

i.
i.
i.
v.
v.
i.

i.
i.
i.
v.
v.
i.

Age

Sex

Source
Destination

Journey_Date
Ticket_No

Dep_Time

TICKET

In the above figure Ticket_No is the Primary Key


3. PASSENGER Entity:
The attributes are:
PNR_No
Ticket_No
Name
Age
Sex
PPNo
The E-R Model is as follows:
Name

Age
Sex

Ticket_No
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:
PNR_NO
Journey_Date
No_Of_Seats
Address
Contact_No
Status
The E-R Model is as follow:

i.
i.
i.
v.
v.
i.

No_Of_Seats

Address
Contact_No

Journey_Date
PNR_No

Status
RESERVATION

In the above figure PNR_No is the Foreign Key


5. CANCELLATION Entity:
The attributes are:
PNR_No
Journey_Date
No_Of_Seats
Address
Contact_No
Status
The E-R Model is as follows:
No_Of_Seats

Address
Contact_No

Journey_Date
PNR_No

Status
CANCELLATION

In the above figure PNR_No is the Foreign Key

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.

Source

Destination

Bus_No

Dep_Time
BUS

Travels
in

PNR_No

PPNO
PASSENGER

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
Sex

Ticket_No
PNR_No

PPNo
PASSENGER

Takes

PNR_No
Status
RESERVATION
Journey_Date
Contact_No
No_Of_Seats

Address

The relationship between PASSENGER Entity and RESERVATION Entity is weakrelationship. Because the one
entity consists of primary key and another entity consists offoreign 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.

Name

Age
Sex

Ticket_No
PNR_No

PPNo
PASSENGER

Cancels

Status
PNR_No
CANCELLATION
Journey_Date

Contact_No
No_Of_Seats

Address

The relationship between PASSENGER Entity and CANCELLATION Entity is weakrelationship. Because the
one entity consists of primary key and another entity consists offoreign 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.

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,
Multivalued and Derived) have different way of representation.
The following are the tabular representations of the entities used in this company.
1. BUS Entity Table:
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

2. TICKET Entity Table:


Ticket_No Journey_Date

Age

Sex

Source

Destination

Dep_Time

2345

20-08-2010

25

Anantapur

Kurnool

10:30am

5678

25-08-2010

20

Hyderabad

Chennai

07:00pm

2457

30-08-2010

32

Bangalore

Hyderabad

12:30pm

4679

05-09-2010

28

Kadapa

Hyderabad

10:30pm

3. PASSENGER Entity Table:


PNR_No

Ticket_No

Name

Age

Sex

PPNo

2345

Varuni

25

9003345678

5678

Rahul

20

9247212345

2457

Ajay

32

9989892731

4679

Suni

28

9885252069

4. RESERVATION Entity Table:


PNR_No

Journey_Date

No_Of_Seats

Address

Contact_No

Status

20-08-2010

Anantapur

9003345678

Yes

30-08-2010

Bangalore

9989892731

No

25-08-2010

Hyderabad

9885252069

Yes

05-09-2010

Kadapa

9247212345

No

Address

Contact_No

Status

Bangalore

9989892731

No

5. CANCELLATION Entity Table:


PNR_No
3

Journey_Date No_Of_Seats
30-08-2010

BUS
1234

Anantapur

Kurnool

10:30am

4567

Kadapa

Hyderabad

10:30pm

1245

Hyderabad

Chennai

07:00pm

3467

Bangalore

Hyderabad

12:30pm

Ticket
2345 20-08-2010

25

Anantapur

Kurnool

10:30am

5678 25-08-2010

20

Hyderabad

Chennai

07:00pm

2457 30-08-2010

32

Bangalore

Hyderabad

12:30pm

4679 05-09-2010

28

Kadapa

Hyderabad

10:30pm

Passenger
1

2345

Varuni

25

9003345678

5678

Rahul

20

9247212345

2457

Ajay

32

9989892731

4679

Suni

28

9885252069

Reservation`
1

20-08-2010

Anantapur

9003345678

yes

30-08-2010

Bangalore

9989892731

no

25-08-2010

Hyderabad

9885252069

yes

05-09-2010

Kadapa

9247212345

no

Cancellation
3

30-08-2010

Bangalore

9989892731

no

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 ofinconsistency, 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

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_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_No

Journey_Date

Age

Sex

Source

Destination Dep_Time

2345

20-08-2010

25

Anantapur

Kurnool

10:30am

5678

25-08-2010

20

Hyderabad

Chennai

07:00pm

2457

30-08-2010

32

Bangalore

Hyderabad

12:30pm

4679

05-09-2010

28

Kadapa

Hyderabad

10:30pm

PNR_No

Ticket_No

Name

Age

Sex

PPNo

2345

Varuni

25

9003345678

5678

Rahul

20

9247212345

2457

Ajay

32

9989892731

4679

Suni

28

9885252069

PNR_No

Journey_Date

No_Of_Seats

Address

Contact_No

Status

20-08-2010

Anantapur

9003345678

Yes

30-08-2010

Bangalore

9989892731

No

25-08-2010

Hyderabad

9885252069

Yes

05-09-2010

Kadapa

9247212345

No

PNR_No
3

Journey_DateNo_Of_Seats
30-08-2010

AddressContact_No
Bangalore

9989892731

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

It is in the first normal form


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

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

Journey_Date

2345

20-08-2010

5678

25-08-2010

2457

30-08-2010

4679

05-09-2010

PASSENGER Table:
PNR_No

Name

Age

Sex

PPNo

Varuni

25

9003345678

Rahul

20

9247212345

Ajay

32

9989892731

Suni

28

9885252069

RESERVATION Entity Table:


PNR_No

Journey_Date No_Of_Seats

Address

Contact_No

Status

20-08-2010

Anantapur

9003345678

Yes

30-08-2010

Bangalore

9989892731

No

25-08-2010

Hyderabad

9885252069

Yes

05-09-2010

Kadapa

9247212345

No

Address

Contact_No

Status

Bangalore

9989892731

No

CANCELLATION Entity Table:


PNR_No

Journey_Date No_Of_Seats

30-08-2010

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

Journey_Date

2345

20-08-2010

5678

25-08-2010

2457

30-08-2010

4679

05-09-2010

PASSENGER Table:
PNR_No

Name

Age

Sex

PPNo

Varuni

25

9003345678

Rahul

20

9247212345

Ajay

32

9989892731

Suni

28

9885252069

RESERVATION TABLE:
PNR_No

Journey_Date

No_Of_Seats

Address

Contact_No

Status

20-08-2010

Anantapur

9003345678

Yes

30-08-2010

Bangalore

9989892731

No

25-08-2010

Hyderabad

9885252069

Yes

05-09-2010

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

20-08-2010

Yes

30-08-2010

No

25-08-2010

Yes

05-09-2010

No

2. Reservation details table


PNR_No

No_Of_Seats

Address

Contact_No

Anantapur

9003345678

Bangalore

9989892731

Hyderabad

9885252069

Kadapa

9247212345

CANCELLATION TABLE
PNR_No
3

Journey_Date No_Of_Seats
30-08-2010

Address

Contact_No

Status

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
3

Journey_Date
30-08-2010

Status
No

2. Cancellation details table


PNR_No
3

No_Of_Seats
1

Address

Contact_No

Bangalore

9989892731

WEEK 5: Installation of Mysql and practicing DDL commands


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
1. Creating the database table using CREATE TABLE Command:
The Create Table Command is used to create objects in the database. The syntax of this command is as
follows
SQL> CREATE TABLE <table name> (Attribute1 Data type,Attribute2 Data type,,Attributen Data
type, <Integrity-constraint t1>,.,<Integrity-constraint tn>);
Example:

SQL> CREATE TABLE bus (Bus_Novarchar(10) primary key, Source varchar(20), Destination
varchar(20), Dep_Timevarchar(10));
Table Created

SQL> CREATE TABLE ticket (Ticket_No number primary key, Journey_Date number, Age
number,
Sex
varchar(2),
Source
varchar(20),
Destination
varchar(20), Dep_Timevarchar (10) );

Table Created
SQL> CREATE TABLE passenger (PNR_No number(10) primary key, Ticket_No
number,
Name
varchar(10),
Age
number(3),
Sex
varchar(2),
PPNo number(10));
Table Created

SQL> CREATE TABLE reservation (PNR_No number references


Journey_Date
number,No_Of_Seats
number,Address

passenger,
varchar(10),

Contact_Nonumber(10), Status varchar(10)); Table


Created

SQL> CREATE TABLE cancellation (PNR_No number references passenger,


Journey_Date
date,
No_Of_Seats
number,
Address
varchar(10),
Contact_Nonumber(10), Status varchar(10));
Table Created

2. Altering the database tables using ALTER TABLE Command:


The ALTER TABLE command is used to alter the structure of the database. The syntax of the command is as
follows.
SQL>ALTER TABLE tablename ADD column_namecolumn_definition(datatype);
Example:

SQL> ALTER TABLE ticket ADD (Ticket_Cost number; Table Altered

3. Dropping the database tables using DROP TABLE Command:


The DROP TABLE command is used to delete objects from the database. The syntax of the command is as
follows.
SQL> DROP TABLE tablename;
Example:

SQL> DROP TABLE bus; Table Dropped.

4. TRUNCATE TABLE Command:


TRUNCATE TABLE Command is used to remove all records from a table, including all spaces allocated for
the records are removed. The syntax is as follows.
SQL> TRUNCATE TABLE tablename;
Example:

SQL> TRUNCATE TABLE passenger; Table Truncated

5. RENAME TABLE Command:


RENAME TABLE Command is used to rename the old table name to new table name. The syntax is as follows.
SQL> RENAME TABLE tablename TO newtablename;
Example:

SQL> RENAME TABLE reservation TO ticketreservation; Table renamed

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 Bus_No ,Dep_Time FROM bus WHERE Source=Kadapa;
Bus_No
4567

Dep_Time
10:30pm

1 row selected
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:
SQL> INSERT INTO passenger VALUES(0012345678,1234,Rahul,25,M,9902345178);
1 row created.

SQL> INSERT INTO passenger


VALUES(&PNR_No,&Ticket_No,&Name,&Age,&Sex,&PPNo);
SQL> INSERT INTO passenger
VALUES(&PNR_No,&Ticket_No,&Name,&Age,&Sex,&PPNo);
Enter value of PNR_No: 0014568972 Enter value of
Ticket_No: 3456 Enter value of Name: Varuni
Enter value of Age: 26 Enter value of Sex:
F
Enter value of PPNo: 9830527846 1 row created
SQL> /
And press enter. Then, again it inserts one more tuple.
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 SET No_Of_Seats=2 WHERE Journey_Date=30-08-2010; 1 row updated.
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=0012345678; 1 row deleted;

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;
Output:
Pnr_no
--------1
2
2. Display all the name of male passengers.
SQL>select name from Passenger where sex=M;
Output:
Name
-------Ramesh
3. Display the ticket numbers and names of all the passengers.
SQL>select ticket_no,name from passenger;
Output:
Ticket_no name
----------------------45

ramesh

78

geeta

4. Display the sorted list of passenger names.


SQL> select * from passenger order by name;
Ouput;
PNR_NO TICKET_NO NAME

AGE

SEX

PPNO

---------- ---------- --------------- ---------- ---------- -------------------------1

78

geetha

36

abc124

45

ramesh

45

abc123

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

SQL>select ticket_no from passenger where name like a%%h;


Output:
PNR_NO TICKET_NO NAME
AGE
SEX
PPNO
---------- ---------- --------------- ---------- ---------- -------------------------1
78
aramesh
36
F
abc124
2
45
anirudh
45
M
abc123
6. Find the names of passengers whose age between 30 and 45.
SQL>select name from passenger where age >=30 and age <=40;
Output:
Name
------Geeta
Or
SQL>select name from passenger where age between 30 and 40;
Output:
Name
------Geeta
7. Display the bus numbers that travel on Sunday and Monday.
SQL>select no from bus where days in(Sunday,wednesday);
Output:
No
---1234
1235
1237

8. Display the source and the destination having journey time more than than 10 hours.
SQL>select source,destination from bus where hours>=10;
Output:
Source
destination
----------------------------------Hyderabad
banglore
Kurnool
Chennai
Madras
manglore
9. Display the details of passengers who are travelling either in Ac or Non_Ac (using in
operator).
SQL> select * from passenger wherebusservice in(ac,non_ac);
Ouput;
PNR_NO TICKET_NO NAME AGE SEX PPNO BUSERVICE
--------------------------------------------------------------------------------------1

78

geetha

36

abc124

ac

45

ramesh

45

abc123

non_ac

10. Display all the passenger names beginning with A.


SQL>select name from passenger from name like a%;
Ouput;
NAME
---------ananth
arvind

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;
Output:
Pnr_no
---------1
2
2. Display the number of days ina week on which the 9wo1 bus is available.
SQL>select count(days) from bus where busno=9w01;
Output:
Days
-----4
3. Find the distincet numbers that are present.
SQL>select distinct pnr_no from passenger;
Output:
Pnr_no
---------1
2
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_tickets) nof_of_tickets from reservation group by pnr_no;
Output:
Pnr_nono_of_tickets
-----------------------------1
4

20
6

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_tickets) no_of_tickets from passenger where journey_date between '12-mar-09'and
sysdate having count(pnr_no)>=0;
Output:
NO_OF_TICKETS
----------------------------------8
6. Find the total no of cancellation seats.
SQL>select sum(no_of_cancelseats) total_no_of_cancelseats from cancellation;
Output:
Total_no_of_canceltickets
---------------------------------5
7. Find the number of tickets booked in each class where the number of seats is greater
than1(use GROUP BY ,WHERE and HAVING VLAUSES).
SQL> select pnr_no,name,sum(no_of_tickets) nof_of_tickets ,busservice from passenger where busservice
in('ac','nonac') group by name,pnr_no,busservice having sum(no_of_seats)>1;
Output:
PNR_NO NAME

(NO_OF_TICKETS

BUSSERVICE

---------------------------------------------- ----------------------------------------1

ramesh

geetha

3
17

ac
nonac

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.
SQL>edstrig
create or replace trigger strig before update on passenger for each row
declare
z number; begin
if :new.ticket_no>60 then z:=:new.ticket_no

:new.ticket_no:=:old.ticket_no;

dbms_output.put_line('old ticket_no ||:old.ticket_no|| is updated with new ticketno ||z); else


:new.ticket_no:=0;
dbms_output.put_line('old ticket_no ||:old.ticket_no|| is updated with new ticketno
||:new.ticket_no);
end if; end;
output:
SQL>@strig
Trigger created
SQL>Update passenger set ticket_no=68 where pnr_no=2;
The old ticketno 61 is updated with new ticketno 68;

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 creation of stored procedures ,exection of procedure and modification of


procedure.
SQL>edproc
create or replace procedure myproc(s out number) is
begin
select count(ticket_no) into s from ticket where age>=40; end;
/
Ouput:
@ proc; Procedure created;
SQL>Set serverouput on; >create a blind
variable;
SQL>varablenooftickets number;
SQL>execute(:nooftickets)
SQL>Procedure successfully completed;
SQL>Print :noofticket
Noofticket
--------------2

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.
SQL>edpsg;
create or replace procedure myproc(custid number) is
vid number(4); vname varchar2(10);
cursor c1 is select stdid,stdname from student where stdid=custid; begin
open c1;
fetch c1 into vid,vname; dbms_output.put_line(vid||
vname); close c1;
end;
/
Output:
--------SQL>@ psg;
Procedure created;
SQL>execute myproc(12);
Stidstdname
---------------12

aaa

Additional Programs

1.Write a program to create trigger event?


Create or replace trigger over_time
Before insert or delete or update on a
Declare
T number;
Begin
T:=to_char(sysdate,'hh24');
If t not between 10 and 18 then
Raise_application_error(-20007,'time already over.....transaction not allowed now');
End if;
End;
Output:
@ trigger.sql
Trigger created successfully
/

2.Write a program to create procedure event?


Declare
a number (10);
tkt varchar(10);
begin
select count(pid) into tkt from passenger
where age>=&a;
dbms_output.put_line(tkt);
end;
/
Output:
@d.sql
Enter the value of a:25
Old 5: select count(pid) into tkt from passengers where age>=&a;
New 5: select count(pid) into tkt from passengers where age>=25

50

3. Write a program to create Cursor event?


declare
cursor c1 is
select a1 from a;
t1 varchar(10);
begin
open c1;
loop
fetch c1 into t1;
exit when c1%notfound;
dbms_output.put_line(t1);
end loop;
close c1;
end;
Output:
@Cursor.sql
101
102
Procedure completed Successfully.

51

Open Ended Lab Programs

52

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?

53

Viva Questions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

What are super, primary, candidate and foreign keys?


What is the difference between primary key and unique constraints?
What are the differences between DDL, DML and DCL in SQL?
What is Join?
What is Identity?
What are the uses of view?
What is a stored procedure?
What is the difference between Trigger and Stored Procedure?
What are indexes?
What are clustered and non-clustered Indexes?
Define Fragmentation.
What do you mean by Index hunting?
Define Aggregate functions.
Why is group-clause used?
What are the various kinds of interactions catered by DBMS?
Define DDL Interpreter.
Define Entity.
What do you mean by Entity type extension?
Define Scalar functions.
Enlist the types of cursor.

54