You are on page 1of 57

DATABASE MANAGEMENT SYSTEM

LAB MANUAL
(R18 REGULATION)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VAAGDEVI COLLEGE OF ENGINEERING


BOLLIKUNTA, WARANGAL
INDEX
1. Syllabus…………………………………………………………….1
2. Introduction………………………………………………………..2
3. DDL commands……………………………………………………3
4. DML commands…………………………………………………...4
5. Data types…………………………………………………………..5
6. Experiments………………………………………………………...6
VAAGDEVI COLLEGE OF ENGINEERING
(AUTONOMOUS)

(B18CS07)DATABASE MANAGEMENT SYSTEMS LAB

II Year I Sem L/ T/ P / C

0/ 0/ 3 / 1.5

Objectives:

This lab enables the students to practice the concepts 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 Hyderabad.

The company wants to computerize its operations in the following areas:

• Reservations and Ticketing

• Cancellations

Reservations & 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 booking 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 using SQL to retrieve the data
from the 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 supposed 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.

WEEK 1: E-R Model

Analyze the carefully and come up with the entities in it. Identify what data has to be persisted in the
database. This contains the entities, candidate attributes etc.

Identify the primary keys for all the entities. Identify the other keys like keys, partial keys, if any.

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)

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

WEEK 2: Concept design with E-R Model

Relate the entities appropriately. Apply cardinalities 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.

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

WEEK 3: Relational Model

Represent all 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, 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

Note: The student is required to submit a document relationships in a tabular fashion to the lab teacher.

WEEK 4: Normalization

Database normalization is a technique for designing relational database tables to minimize duplication of
information and, in so 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.

For the above table in the First normalization we can remove the multi valued attribute Ticket_id and place
it in another table along with the primary key of passenger.

First Normal Form: The above table can be divided into two tables as shown below. Passenger

Name Age Sex Address Passport_ID

Passport_ID Ticket_id
You can do the second and third normal forms if re wired. Any ht)* given Normalized tables are at the end.

WEEK 5: Installation of Mysql and practicing DDL commands

Installation of MySql. In this week you will learn Creating databases, How to create tables, altering the
database, dropping 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.

WEEK 6: Practicing DML commands

DML commands are used to for managing data within schema objects. Some examples:

• SELECT - retrieve data from the a database

• INSERT - insert data into a table

• UPDATE - updates existing data within a table

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

Inserting values into "Bus" table:

Insert into Bus values (1234,'hyderabad', lirupathi');

Insert into Bus values (2345,1hyderabd,Banglore');

Insert into Bus values (23,'hyderabd','Kolkata');

Insert into Bus values (45,11rupathi,'Banglore');

Insert into Bus values (34,1h derab yc11,1Chennar);

Inserting 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',1abc12');

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

UPDATE BUS SET Bus No = 1 WHERE BUS NO=2;

WEEK 7: Querying

In this week you are going to practice queries ( along with subquries) Using queries ANY, ALL, IN, Exists,
NOT EXISTS, UNION, INTERSECT, Constraints etc.

Practice the following Queries:

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

WEEK 8 and WEEK 9: Querying (continued...)

You are going to practice queries using Aggregate functions (COUNT, Sum, AVG, and 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. 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.

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

Eg: CREATE TRIGGER updcheck BEFORE UPDATE ONpassenger FOR EACH ROW BEGIN IF
NEW.TickentNO > 60 THEN

SET New.Tickent no = Ticket no;

ELSE

SET New.Ticketno:at 0;

END IF;

END;

WEEK 11: Procedures

This session you are going to learn Creation of stored procedure, Execution of procedure and modification
of procedure. Practice procedures using the above database.

Eg: CREATE PROCEDURE myProc()

BEGIN

SELECT COUNT(Tickets) FROM Ticket WHERE age>=40;

End;

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

DECLARE c1 CURSOR FOR SELECT stdld,stdFirstname FROM students WHERE


stdId=in_customer_id;

OPEN c1;

FETCH cl into v_id, v_name;

Close c1;

END;

Tables

BUS

Bus No: Varchar: PK (public key)

Source : Varchar

Destination : Varchar

Passenger

PPNO: Varchar(15)) :

PK Name: Varchar(15)

Age int (4)

SexIChar(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)

Address : Varchar (50)


Contact_No: Numeric (9) --> Should not be less than 9 and Should not accept any other character other
than Integer

Status: Char (2) : Yes / No

Cancellation

PNR_No: Numeric(9) : FK

Journey_date : datetime(8)

No_of_seats : int (8)

Address : Varchar (50)

Contact_No: Numeric (9) --> Should not be less than 9 and Should not accept any other character other
than Integer

Status: Char (2) : Yes / No

Ticket

Ticket_No: Numeric (9): PK

Journey date : datetime(8)

Age : int (4)

Sex:Char(10) : Male / Female

Source : Varchar

Destination : Varchar

Dep_time : Varchar

COURSE OUTCOMES:
1. Design database schema for given Application.
2.Transform ER Model to Relational Model.
3.Apply the normalization techniques for development of application software to realistic problems.
4.Construct SQL queries to retrieve information from databases .

TEXT BOOKS:

1.Introduction to SQL, Rick F.Vander Lans, Pearson education.


2.Oracle PL/SQL, B.Rosenzweig and E.Silvestrova, Pearson education
3.Oracle PL/SQL Programming, Steven Feuerstein, SPD.

REFERENCE BOOKS:

1) SQL & PL/SQL for Oracle 10g, Black Book, Dr. P. S. Deshpande, Dream Tech.
2) Oracle Database 11g PL/SQL Programming, M. Mc Laughlin, TMH.
3) SQL Fundamentals, J.J. Patrick, Pearson Education.
Indroduction
Database management system:

Database is collection of data which is related by some aspect. Data is collection of facts and figures which
can be processed to produce information. Name of a student, age, class and her subjects can be counted as
data for recording purposes. Mostly data represents recordable facts. Data aids in producing information
which is based on facts. For example, if we have data about marks obtained by all students, we can then
conclude about toppers and average marks etc. A database management system stores data, in such a way
which is easier to retrieve, manipulate and helps to produce information.
DDL Introduction

DDL:

DDL statements or commands are used to define and modify the database
structure of your tables or schema. When you execute a DDL statement, it
takes effect immediately.

Some commands of DDL are:

• CREATE – to create table (objects) in the database


• ALTER – alters the structure of the database
• DROP – delete table from the database
• TRUNCATE – remove all records from a table, including all spaces
allocated for the records are removed
• COMMENT – add comments to the data dictionary
• RENAME – rename a table

CREATE :

The create table statement (query) to create a table is given below:

CREATE TABLE <table name> (

<attribute name 1> <data type 1>,

...

<attribute name n> <data type n>);


Example:
CREATE TABLE STUDENT ( StudID NUMBER, Name VARCHAR);
The data types that you will use most frequently are character strings, which
might be called VARCHAR or CHAR for variable or fixed length strings; numeric
types such as NUMBER or NTEGER, which will usually specify a precision; and
DATE or related types. Data types are differ according to the databases
software whatever you are using to your system.

ALTER :

The alter table statement to make modifications to the table structure such as
Key constraints, Column size, etc.

ALTER TABLE <table name> ADD CONSTRAINT <constraint name> PRIMARY


KEY(<attribute list>);
Example:

ALTER TABLE STUDENT ADD CONSTRAINT NOT NULL PRIMARY KEY (StudID);

DROP :

The drop table statement (query) to delete a table is given below:

DROP TABLE <table name>;

Example: DROP TABLE STUDENT;


DML Introduction
DML:
DML- Data Manipulation Language (DML) statements are used for managing
data within schema objects DML deals with data manipulation, and therefore
includes most common SQL statements such SELECT, INSERT, etc. DML allows
to add / modify / delete data itself.
DML is used to manipulate with the existing data in the database objects
(insert, select, update, delete).

DML Commands:
1.INSERT
2.SELECT
3.UPDATE
4.DELETE

*INSERT:
Syntax: INSERT INTO Table name values();

*SELECT:
Syntax: Select * from <table name>

*UPDATE:
Syntax: Update<table name> set to(calculation);

*DELETE:
Syntax: Delete form<table name>
Data Types
MySQL data types :
A database table contains multiple columns with specific data types such as numeric or
string. MySQL provides more data types other than just numeric or string. Each data
type in MySQL can be determined by the following characteristics:

• The kind of values it represents.


• The space that takes up and whether the values is a fixed-length or variable
length.
• The values of the data type can be indexed or not.
• How MySQL compares the values of a specific data type.

Numeric Data Types

You can find all SQL standard numeric types in MySQL including exact number data
type and approximate numeric data types including integer, fixed-point and floating
point. In addition, MySQL also supports BIT data type for storing bit field values.
Numeric types can be signed or unsigned except the BIT type. The following table
shows you the summary of numeric types in MySQL:

Numeric Types Description

TINYINT A very small integer

SMALLINT A small integer

MEDIUMINT A medium-sized integer

INT A standard integer


Numeric Types Description

BIGINT A large integer

DECIMAL A fixed-point number

FLOAT A single-precision floating point number

DOUBLE A double-precision floating point number

BIT A bit field

String Data Types:

In My SQL, a string can hold anything from plain text to binary data such as images and
files. The string can be compared and searched based on pattern matching by using
the LIKE operator or regular expression. The following table shows you the string data
types in MySQL:

String Types Description

CHAR A fixed-length non binary (character) string

VARCHAR A variable-length non-binary string

BINARY A fixed-length binary string


String Types Description

VARBINARY A variable-length binary string

TINYBLOB A very small BLOB (binary large object)

BLOB A small BLOB

MEDIUMBLOB A medium-sized BLOB

LONGBLOB A large BLOB

TINYTEXT A very small non-binary string

TEXT A small non-binary string

MEDIUMTEXT A medium-sized non-binary string

LONGTEXT A large non-binary string

ENUM An enumeration; each column value may be assigned one


enumeration member

SET A set; each column value may be assigned zero or more set
members
Date and Time Data Types:

MySQL provides types for date and time as well as a combination of date and time. In
addition, MySQL supports timestamp data type for tracking the changes of a row in a
table. If you just want to store the year without date and month, you can use YEAR data
type. The following table illustrates the MySQL date and time data types:

Date and Time Description


Types

DATE A date value in ‘YYYY-MM-DD’ format

TIME A time value in ‘hh:mm:ss’ format

DATETIME A date and time value in ‘YYYY-MM-DD hh:mm:ss’ format


Experiments
Exp No: 1

AIM: Analyze the problem and come with the entities in it. Identify what Data
has to be persisted in the databases.

The Following are the entities:


1 .Bus
2. Reservation
3. Ticket
4. Passenger
5. Cancellation

Cancellation (Entity)
Exp No: 2

AIM: Concept Design With E-R Model. Relate the entities appropriately. Apply
Cardinality for each relationship. Identfiy strong Entities and Weak entities.
Indicate the type of relationship(total/ partial)
Exp No: 3

AIM: Represent all entities in a tabular fashion. Represent all relationships in a


tabular fashion.
BUS

COLOUMN NAME DATA TYPE CONSTRAINT

Bus_No varchar(10) Primary Key

Source varchar(20)
Destination varchar(20)

Couch _Type varchar(20)

Reservation

COLOUMN NAME DATA TYPE CONSTRAINT

PNR_No number(9) Primary Key

Journey_date Date

No_of_seats integer(8)

Address varchar(50)

Contact_No Numeric(10) Should be equal to 10


numbers and not
allow other than
numeric
Bus_No varchar(10) Foreign key

Seat_no Int(4)

Ticket:

COLOUMN NAME DATA TYPE CONSTRAINT

Ticket_No numeric(9) Primary Key

Journey date Date


Age int(4)
Gender Char(1)
Source varchar(20)
Destination varchar(20)
Dep_time varchar(10)
Bus_No varchar(10)

Passenger:
COLOUMN NAME DATA TYPE CONSTRAINT

PNR_No Numeric(9) Primary Key

Ticket_No Numeric(9) Foreign key

Name varchar(15)
Age integer(4)
Gender char(1) (M/F)
Contact_no Numeric(10) Should be equal to 10 numbers
and not allow other than
numeric

Cancellation:
COLOUMN NAME DATA TYPE CONSTRAINT

PNR_No Numeric(9) PRIMARY KEY

Journey_date Date

Seat no Integer(9)
Contact_No Numeric(10) Should be equal to 10 numbers
and not allow other than
numeric

Exp No: 4
Normalization:

Normalization: Database Normalization is a technique to minimize the duplication


of information and in so 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 with in the
table is updated, leading to loss of data integrity. A table that is normalized
sufficiently is less vulnerable to problems of this kind, because its structure
reflects the basic assumption for when the multiple instances of the same
information should be represented by a single instance only.

Exp No: 5

Installation of MySQL

1.Steps for installing MySQL


Step1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi
file. Double click on the .msi file.

Step2
This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL
Server 5.0 release 5.0.45 on your computer. To continue, click next.
Step3 3
Choose the setup type that best suits your needs. For common program
features select Typical and it’s recommended for general use. To continue,
click next.

Step4 4
This wizard is ready to begin installation. Destination folder will be in
C:\Program Files\MySQL\MySQL Server 5.0\. To continue, click next.

Step5 5
The program features you selected are being installed. Please wait while the
setup wizard installs MySQL 5.0. This may take several minutes.

Step6 6
To continue, click next.
Step7 7
To continue, click next.

Step8 8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the
configure the MySQL server now to continue. Click Finish to exit the wizard
Step9

The configuration wizard will allow you to configure the MySQL Server 5.0
server instance.
To continue, click next.

Step10 10
Select a standardconfiguration and this will use a general purpose
configuration for the server that can be tuned manually. To continue, click
next.
Step11.Check on the install as windows service and include bin directory
in windows path. To continue, click next.

Step12 12
Please set the security options by entering the root password and confirm
retype the password. To continue, click next.
Step13 Ready to execute? Clicks execute to continue.

Step14 14
Processing configuration in progress.
Step15

Configuration file created. Windows service MySQL5 installed. Press finish to

close the wizard.


Exp No: 6 Practicing DDL and DML Commands

mysql> create table Bus(Bus_No varchar(10) ,source varchar(20), destination varchar(20),


Couch_Typevarchar(10), price numeric(8,2));

mysql>desc bus;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Bus_no | varchar(10) | NO | PRI | NULL | |
| Source | varchar(10) | YES | | NULL | |
| Destination | varchar(10) | YES | | NULL | |
| Couch_type | varchar(10) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+

mysql> create table Reservation(PNR_NO Numeric(9), No_of_seatsNumeric(8), Address


varchar(50), Contact_NoNumeric(10), Status char(3));
s
Table created.
mysql>desc Reservation
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| PNR_NO | decimal(9,0) | NO | PRI | NULL | |
| Journey_date | date | YES | | NULL | |
| No_of_seats |int(4) | YES | | NULL | |
| Address | varchar(100) | YES | | NULL | |
| contact_no | decimal(10,0) | YES | | NULL | |
| Bus_no | varchar(10) | YES | | NULL | |
| seat_no | int(3) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+

Cancellation Table:

MYSQL> create table Cancellation(PNR_NO Numeric(9), No_of_seats Numeric(8), Address


varchar(50), Contact_No Numeric(9), Status char(3));
Table created.
MYSQL>desc Cancellation
+-------------+--------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------------+--------------+------+-----+---------+-------+

| PNR_NO | decimal(9,0) | YES | | NULL | |

| No_of_seats | decimal(8,0) | YES | | NULL | |

| Address | varchar(50) | YES | | NULL | |

| Contact_No | decimal(9,0) | YES | | NULL | |

| Status | char(3) | YES | | NULL | |

+-------------+--------------+------+-----+---------+-------+

Ticket Table:

mysql> create table Ticket(Ticket_No Numeric(9) primary key, age numeric(3), gender char(1) Not
null, source varchar(2), destination varchar(20), dep_time varchar(4));
Table created.
mysql>desc Ticket
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| ticket_no | decimal(9,0) | NO | PRI | NULL | |
| journey_date | date | YES | | NULL | |
| age | int(4) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| source | varchar(20) | YES | | NULL | |
| Destination | varchar(20) | YES | | NULL | |
| Departure_time | time | YES | | NULL | |
| bus_no | varchar(10) | YES | | NULL | |
+----------------+--------------+------+-----+---------+-------+
ALTER TABLE Passenger ADD FOREIGN KEY (PNR_NO)
REFERENCES Reservation(PNR_NO);
Table altered. Query OK

mysql>ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO)


REFERENCES Reservation(PNR_NO);
Table altered. Query ok.

mysql>alter table Ticket modify tiketnonumeric(10);

mysql>Alter Table reservation drop column address;

Alter table passenger modify age number(3);


Exp No: 7
Applying DML commands on Road Way Travels Tables.
mysql>insert into BUS values(1234,’Hyderabad’,’Thirupathi’);

mysql>select * from BUS;

mysql> select bus_no, source from bus.

mysql>select * from Passenger;

mysql> select distinct PNR_NO from passenger;

mysql>select pnr_no, first_name, last_name, contact_no


From passenger where gender = ‘M’;

mysql> update Passenger set age='43' where PNR_NO='2’ and first_name = ‘Suresh’;
delete from Passenger
wherePNR_NO='4';
Query OK, 1 row affected (0.04 sec).

mysql>select * from Passenger;


mysql> drop table Cancellation;

mysql>create table passenger_copy as select * from passenger;

mysql>create table passenger_copy1


as select first_name, last_name, contact_no from passenger;
mysql>create table passenger_copy as select * from passenger where 1=2;
mysql>insert into passenger_copy1
select first_name, last_name, contact_no from passenger;
mysql> insert into passenger_cop1(first_name) (select first_name from passenger);

Exp No: 8

Practice Queries using ANY, ALL, IN, EXISTS, UNION

mysql>select order_no from order_master union select order_no


from order_detail;

mysql> select order_no from order_master


union all
select order_no from order_detail
mysql>select PNR_NO from Passenger;

mysql>select first_name from Passenger where gender = 'M';


select source, destination from Ticket
where (arrival_time – departure_time) > 10;
mysql> select Name from Passenger ORDER BY Name;
Exp No: 9 Practice Queries using Aggregate functions(COUNT,SUM, AVG, MAX, MIN),
Group By, Having Clause and Creation and Dropping of Views.
mysql> select avg(age) from passenger;

mysql>Select min(age) from passenger;

mysql>select max(age) from passenger;

mysql>Select sum(age) from passenger;

mysql>Select count(*) from passenger;

mysql> select count(comm) from emp_master;

mysql>Select count(distinct PNR_NO) from passenger;

mysql>select pnr_no, count(*) from passenger group by pnr_no;

mysql>select pnr_no,count(*) from passenger group by pnr_no having count(*) > 1;


mysql>select first_name, last_name from passenger order by first_name;
mysql>select first_name, last_name from passenger order by first_namedesc

1.Write a query to Display the information present in the Cancellation and Reservation Tables

mysql> select * from Reservation UNION select * from Cancellation;

2.Find the distinct PNR_NO that are present

mysql> SELECT PNR_NO, COUNT(*) AS NoOccurances FROM Passenger GROUP BY


PNR_NO HAVING COUNT(*) > 0;

3. Find the No of Seats booked for each PNR_NO using GROUP BY Clause.

mysql> select PNR_NO, sum(No_of_seats) from Reservation group by PNR_NO;


4. Find the number of seats booked in each class where the number of seats is greater than
1.

mysql> select class,sum(No_of_seats) from Reservation where class='a 'or class='b' or class= 'c'
group by class having sum(No_of_seats)>1;
5. Find the total number of cancelled seats.

mysql> select sum(No_of_seats) from Cancellation;

Exp No: 10
Views
mysql>Create View passenger_view As Select * from passenger;

Select columnname, columnname from <View_Name>;

mysql>Select ticket_no, first_name, last_name frompassenger_view where gender = ‘M’;

mysql>Create View passenger_view1 As Select first_name, last_name, gender from passenger;

mysql>Insert into passenger_view1 values(‘Saraswathi’, ‘K’);

mysql>update passenger_view
set last_name = 'Paul'
where first_name = 'Ramesh'
and last_name = 'P';
mysql>create view passenger_reserv_view as
select a.first_name,
a.last_name,
b.journey_date
from passenger a, reservation b
where a.pnr_no = b.pnr_no;
mysql>insert into passenger_reserv_view(first_name, last_name, journey_date)
values('John','Beverly', '2016-01-01');

MYSQL>Drop View passenger_view1

Exp No: 11
: Writing triggers
The Syntax:

CREATE TRIGGER trigger_nametrigger_timetrigger_event


ON table_name
FOR EACH ROW
BEGIN
...
END
Where

trigger_name is the name of the trigger. The programmer gives the name of the trigger.

trigger_time is the time at which the trigger should be executed. The values are ‘BEFORE’ or
‘AFTER’.

trigger_event is the name of the event on the database tables. The possible values are ‘INSERT’,
‘UPDATE’, ‘DELETE’.

4) Following tables are created


a) t1(x int)
b) t2(y int)
c) t3(z int not null)
d) t4(x int not null, y int default 0)
Write a trigger for the following scenario:

1) Whenever a record is inserted in table t1,


a. insert the same value into t2.
b. delete a record from t3 where z = new_value of t1
c. update t4 ; set y = y + 1 where x = new_value of t1.
Solution:

CREATE TABLE t1(x INT);


CREATE TABLE t2(y INT);
CREATE TABLE t3(z INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE t4( x INT NOT NULL AUTO_INCREMENT PRIMARY KEY, b4 INT
DEFAULT 0
);

delimiter $$

CREATE TRIGGER tst_trig BEFORE INSERT ON t1


FOR EACH ROW
BEGIN
INSERT INTO t2 VALUES(NEW.x);
DELETE FROM t3 WHERE z = NEW.x;
UPDATE test4 SET y = y + 1 WHERE x = NEW.x;
END;
$$

delimiter ;

Create of insert trigger, delete trigger and update trigger.


1.To write a TRIGGER to ensure that Bus table does not contain duplicate or null values in Bus_No
column.

b) Create Trigger updchek before update on Ticket


c) CREATE OR RELPLACE TRIGGER trig1 before insert on Passenger for each row
Exp No: 12:
Implement Procedures in mySQLSyntax:
CREATE
[DEFINER = { user | CURRENT_USER }]
PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ]param_name type
characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }

routine_body:
Valid SQL routine statement
mysql>CALL procedure_name(parameter_vlaues);
mysql> call example1(7)
Exp No: 13
: Implement Cursors:

Aim: To write a Cursor to display the list of Male and Female Passengers.

Solution:

CREATE TABLE MALE(Name VARCHAR(15));

CREATE TABLE FEMALE(Name VARCHAR(15));

delimiter $$
CREATE PROCEDURE list_M_F()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE x int;
DECLARE y, z numeric(5);
DECLARE Cur__passenger CURSOR FOR SELECT first_name, Gender FROM PASSENGER;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;


OPEN c1;

sssome_loop: LOOP
FETCH cur_passenger INTO v_name, v_gender;
IF done THEN
LEAVE some_loop;
END IF;
IF v_gender = ‘M’ THEN
INSERT INTO MALE VALUES (v_name);
ELSE
INSERT INTO FEMALE VALUES (v_name);
END IF;
END LOOP;

CLOSE c1;
SELECT * FROM MALE;
SELECT * FROM FEMALE;
END;
$$delimiter ;

Viva Questions

1. What is database?
A database is a logically coherent collection of data with some inherent
meaning, representing some aspect of real world and which is designed, built
and populated with data for a specific purpose.

2. What is DBMS?
It is a collection of programs that enables user to create and maintain a
database. In other words it is general-purpose software that provides the
users with the processes of defining, constructing and manipulating the
database for various applications.

3. What is a Database system?


The database and DBMS software together is called as Database system.

4. Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.

5. Disadvantage in File Processing System?


Data redundancy & inconsistency.
Difficult in accessing data.
Data isolation.
Data integrity.
Concurrent access is not possible.
Security Problems.

6. Describe the three levels of data abstraction?


Three levels of abstraction:
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are
stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire
database.
7. Define the "integrity rules"
There are two Integrity rules.
Entity Integrity: States that Primary key cannot have NULL value
Referential Integrity: States that Foreign Key can be either a NULL value or
should be Primary Key value of other relation.

8. What is extension and intension?


Extension -It is the number of tuples present in a table at any instance. This
is time dependent.
Intension -It is a constant value that gives the name, structure of table and
the constraints laid on it.

9. What is System R? What are its two major subsystems?


System R was designed and developed over a period of 1974-79 at IBM San
Jose Research Center. It is a prototype and its purpose was to demonstrate
that it is possible to build a Relational System that can be used in a real life
environment to solve real life problems, with performance at least comparable
to that of existing system.
Its two subsystems are
Research Storage
System Relational Data System.

10. How is the data structure of System R different from the relational
structure?
Unlike Relational systems in System R
Domains are not supported
Enforcement of candidate key uniqueness is optional
Enforcement of entity integrity is optional
Referential integrity is not enforced

11. What is Data Independence?


Data independence means that “The application is independent of the storage
structure and access strategy of data”. In other words, the ability to modify
the schema definition in one level should not affect the schema definition in
the next higher level.
Two types of Data Independence:
Physical Data Independence: Modification in physical level should not affect
the logical level.
Logical Data Independence: Modification in logical level should affect the
view level.
NOTE: Logical Data Independence is more difficult to achieve

12. What is a view? How it is related to data independence?


A view may be thought of as a virtual table, that is, a table that does not really
exist in its own right but is instead derived from one or more underlying base
table. In other words, there is no stored file that direct represents the view
instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the
view can insulate users from the effects of restructuring and growth in the
database. Hence accounts for logical data independence.

13. What is Data Model?


A collection of conceptual tools for describing data, data relationships data
semantics and constraints.

14. What is E-R model?


This data model is based on real world that consists of basic objects called
entities and of relationship among these objects. Entities are described in a
database by a set of attributes.

15. What is Object Oriented model?


This model is based on collection of objects. An object contains values stored
in instance variables with in the object. An object also contains bodies of code
that operate on the object. These bodies of code are called methods. Objects
that contain same types of values and the same methods are grouped together
into classes.

16. What is an Entity?


It is a 'thing' in the real world with an independent existence.

17. What is an Entity type?


It is a collection (set) of entities that have same attributes.

18. What is an Entity set?


It is a collection of all entities of particular entity type in the database.

19. What is an Extension of entity type?


The collections of entities of a particular entity type are grouped together into
an entity set.

20. What is Weak Entity set?


An entity set may not have sufficient attributes to form a primary key, and its
primary key compromises of its partial key and primary key of its parent entity,
then it is said to be Weak Entity set.

21. What is an attribute?


It is a particular property, which describes the entity.

22. What is a Relation Schema and a Relation?


A relation Schema denoted by R (A1, A2,…?, An) is made up of the relation
name R and the list of attributes Ai that it contains. A relation is defined as a
set of tuples. Let r be the relation which contains set tuples (t1, t2, t3... tn).
Each tuple is an ordered list of n-values t= (v1, v2... vn).

23. What is degree of a Relation?


It is the number of attribute of its relation schema.

24. What is Relationship?


It is an association among two or more entities.

25. What is Relationship set?


The collection (or set) of similar relationships.

26. What is Relationship type?


Relationship type defines a set of associations or a relationship set among a
given set of entity types.

27. What is degree of Relationship type?


It is the number of entity type participating.

25. What is DDL (Data Definition Language)?


A data base schema is specifies by a set of definitions expressed by a special
language called DDL.

26. What is VDL (View Definition Language)?


It specifies user views and their mappings to the conceptual schema.
27. What is SDL (Storage Definition Language)?
This language is to specify the internal schema. This language may specify the
mapping between two schemas.
28. What is Data Storage - Definition Language?
The storage structures and access methods used by database system are
specified by a set of definition in a special type of DDL called data storage-
definition language.

29. What is DML (Data Manipulation Language)?

This language that enable user to access or manipulate data as organized by


appropriate data model.
Procedural DML or Low level: DML requires a user to specify what data are
needed and how to get those data.
Non-Procedural DML or High level: DML requires a user to specify what
data are needed without specifying how to get those data.

31. What is DML Compiler?


It translates DML statements in a query language into low-level instruction
that the query evaluation engine can understand.

32. What is Query evaluation engine?


It executes low-level instruction generated by compiler.

33. What is DDL Interpreter?


It interprets DDL statements and records them in tables containing metadata.

34. What is Record-at-a-time?


The Low level or Procedural DML can specify and retrieve each record from a
set of records. This retrieve of a record is said to be Record-at-a-time.

35. What is Set-at-a-time or Set-oriented?


The High level or Non-procedural DML can specify and retrieve many records
in a single DML statement. This retrieve of a record is said to be Set-at-a-time
or Set-oriented.

36. What is Relational Algebra?


It is procedural query language. It consists of a set of operations that take one
or two relations as input and produce a new relation.

37. What is Relational Calculus?


It is an applied predicate calculus specifically tailored for relational databases
proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL.
38. How does Tuple-oriented relational calculus differ from domain-
oriented relational calculus?
The tuple-oriented calculus uses a tuple variables i.e., variable whose only
permitted values are tuples of that relation. E.g. QUEL The domain-oriented
calculus has domain variables i.e., variables that range over the underlying
domains instead of over relation. E.g. ILL, DEDUCE.

39. What is normalization?


It is a process of analysing the given relation schemas based on their
Functional Dependencies (FDs) and primary key to achieve the properties
Minimizing redundancy
Minimizing insertion, deletion and update anomalies.

40. What is Functional Dependency?


A Functional dependency is denoted by X Y between two sets of attributes X
and Y that are subsets of R specifies a constraint on the possible tuple that
can form a relation state r of R. The constraint is for any two tuples t1 and t2
in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X
component of a tuple uniquely determines the value of component Y.

41. When is a functional dependency F said to be minimal?


Every dependency in F has a single attribute for its right hand side.
We cannot replace any dependency X A in F with a dependency Y A where
Y is a proper subset of X and still have a set of dependency that is equivalent
to F.
We cannot remove any dependency from F and still have set of dependency
that is equivalent to F.

42. What is multivalued dependency?


Multivalued dependency denoted by X Y specified on relation schema R, where
X and Y are both subsets of R, specifies the following constraint on any relation
r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4
should also exist in r with the following properties
t3[x] = t4[X] = t1[X] = t2[X]
t3[Y] = t1[Y] and t4[Y] = t2[Y]
t3 [Z] = t2[Z] and t4[Z] = t1[Z]
Where [Z = (R-(X U Y)) ]

43. What is Lossless join property?


It guarantees that the spurious tuples generation does not occur with respect
to relation schemas after decomposition.
44. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values.

45. What is Fully Functional dependency?


It is based on concept of full functional dependency. A functional dependency
X Y is full functional dependency if removal of any attribute A from X means
that the dependency does not hold any more.
46. What is 2NF?
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in
R is fully functionally dependent on primary key.

47. What is 3NF?


A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the
following is true
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on
primary key.

48. What is BCNF (Boyce-Codd Normal Form)?


A relation schema R is in BCNF if it is in 3NF and satisfies an additional
constraint that for every FD X A, X must be a candidate key.

49. What is 4NF?


A relation schema R is said to be in 4NF if for every multivalued dependency
X Y that holds over R, one of following is true
X is subset or equal to (or) XY = R.
X is a super key.

50. What is 5NF?


A Relation schema R is said to be 5NF if for every join dependency {R1, R2...
Rn} that holds R, one the following is true
i) Ri = R for some i.
ii) The join dependency is implied by the set of FD, over R in which the left
side is key of R.

51. What is Domain-Key Normal Form?


A relation is said to be in DKNF if all constraints and dependencies that should
hold on the constraint can be enforced by simply enforcing the domain
constraint and key constraint on the relation.

52. What are partial, alternate, artificial, compound and natural 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.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key, either stand-alone or compound is available, then the last
resort is to simply create a key, by assigning a unique number to each record
or occurrence. Then this is known as developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct,
then combining multiple elements to create a unique identifier for the
construct is known as creating a compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the
primary key, then it is called the natural key.

53. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing

54. What is system catalog or catalog relation? How is better known


as?
A RDBMS maintains a description of all the data that it contains, information
about every relation and index that it contains. This information is stored in a
collection of relations maintained by the system called metadata. It is also
called data dictionary.

55. What is meant by query optimization?


The phase that identifies an efficient execution plan for evaluating a query that
has the least estimated cost is referred to as query optimization.

56. What is join dependency and inclusion dependency?

Join Dependency:
A Join dependency is generalization of multivalued dependency. A JD {R1, R2,
..., Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join
decomposition of R . There is no set of sound and complete inference rules for
JD.

Inclusion Dependency:
An Inclusion Dependency is a statement of the form that some columns of a
relation are contained in other columns. A foreign key constraint is an example
of inclusion dependency.
57. What is durability in DBMS?
Once the DBMS informs the user that a transaction has successfully
completed, its effects should persist even if the system crashes before all its
changes are reflected on disk. This property is called durability.

58. What do you mean by atomicity and aggregation?

Atomicity:
Either all actions are carried out or none are. Users should not have to worry
about the effect of incomplete transactions. DBMS ensures this by undoing the
actions of incomplete transactions.
Aggregation:
A concept which is used to model a relationship between a collection of entities
and relationships. It is used when we need to express a relationship among
relationships.

59. What is a Phantom Deadlock?


In distributed deadlock detection, the delay in propagating local information
might cause the deadlock detection algorithms to identify deadlocks that do
not really exist. Such situations are called phantom deadlocks and they lead
to unnecessary aborts.

60. What is a checkpoint and when does it occur?


A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the
DBMS can reduce the amount of work to be done during restart in the event
of subsequent crashes.
61. What are the different phases of ARIES Algorithm transaction?
Different phases are
Analysis phase
Redo Phase
Undo phase

62. What do you mean by flat file database?


It is a database in which there are no programs or user access languages. It
has no cross-file capabilities but is user-friendly and provides user-interface
management.

63. What is "transparent DBMS"?


It is one, which keeps its Physical Structure hidden from user.

64. Brief theory of Network, Hierarchical schemas and their properties


.
Network schema uses a graph data structure to organize record; example for
such a database management system is CTCG while a hierarchical schema
uses a tree data structure; example for such a system is IMS.

65. What is a query?


A query with respect to DBMS relates to user commands that are used to
interact with a data base. The query language can be classified into data
definition language and data manipulation language.

66. What do you mean by Correlated sub query?

Sub queries, or nested queries, are used to bring back a set of rows to be used
by the parent query. Depending on how the sub query is written, it can be
executed once for the parent query or it can be executed once for each row
returned by the parent query. If the sub query is executed for each row of the
parent, this is called a correlated sub query.
A correlated sub query can be easily identified if it contains any references to
the parent sub query columns in its WHERE clause. Columns from the sub
query cannot be referenced anywhere else in the parent query. The following
example demonstrates a non-correlated sub query.
E.g.
SELECT *
FROM CUST
WHERE '10/03/1990' IN (
SELECT ODATE
FROM ORDER
WHERE CUST.CNUM = ORDER.CNUM);
67. What are the primitive operations common to all record
management systems?
Addition
Deletion and
Modification.

68. Name the buffer in which all the commands that are typed in are
stored
Edit Buffer

69. What are the unary operations in Relational Algebra?


PROJECTION and SELECTION.

70. Are the resulting relations of PRODUCT and JOIN operation the
same?
No.
PRODUCT: Concatenation of every row in one relation with every row in
another.
JOIN: Concatenation of rows from one relation and related rows from another.
71. What is RDBMS KERNEL?

Two important pieces of RDBMS architecture are the kernel, which is the
software, and the data dictionary, which consists of the system-level data
structures used by the kernel to manage the database
You might think of an RDBMS as an operating system (or set of subsystems),
designed specifically for controlling data access;
Its primary functions are storing, retrieving, and securing data. An RDBMS
maintains its own list of authorized users and their associated privileges;
Manages memory caches and paging;
Controls locking for concurrent resource usage;
Dispatches and schedules user requests; and
Manages space usage within its table-space structures.

72. Name the sub-systems of a RDBMS.


I/O, Security, Language Processing, Process Control, Storage Management,
Logging and Recovery, Distribution Control, Transaction Control, Memory
Management, Lock Management

73. Which part of the RDBMS takes care of the data dictionary? How?
Data dictionary is a set of tables and database objects that is stored in a special
area of the database and maintained exclusively by the kernel.
74. What is the job of the information stored in data-dictionary?
The information in the data dictionary validates the existence of the objects,
provides access to them, and maps the actual physical storage location.

75. Not only RDBMS takes care of locating data it also determines an
optimal access path to store or retrieve the data.
YES

76. How do you communicate with an RDBMS?


You communicate with an RDBMS using Structured Query Language (SQL)

77. Define SQL and state the differences between SQL and other
conventional programming Languages
SQL is a nonprocedural language that is designed specifically for data access
operations on normalized relational database structures. The primary
difference between SQL and other conventional programming languages is
that SQL statements specify what data operations should be performed rather
than how to perform them.

78. Name the three major set of files on disk that compose a database
in Oracle
There are three major sets of files on disk that compose a database. All the
files are binary. These are
Database files
Control files
Redo logs

The most important of these are the database files where the actual data
resides. The control files and the redo logs support the functioning of the
architecture itself.
All three sets of files must be present, open, and available to Oracle for any
data on the database to be useable. Without these files, you cannot access the
database, and the database administrator might have to recover some or the
entire database using a backup, if there is one.

79. Spurious tuples may occur due to


i. Bad normalization
ii. Theta joins
iii. Updating tables from join
a) i & ii b) ii & iii c) i & iii

80. Tables derived from the ERD


a) Are totally UN normalized
b) Are always in 1NF
c) Can be further denormalized
d) May have multi-valued attributes

81. What are database files, control files and log files? How many of
these files should a database have at least? Why?

Database Files:
The database files hold the actual data and are typically the largest in size.
Depending on their sizes, the tables (and other objects) for all the user
accounts can go in one database file? But that's not an ideal situation because
it does not make the database structure very flexible for controlling access to
storage for different users, putting the database on different disk drives, or
backing up and restoring just part of the database.
You must have at least one database file but usually, more than one file are
used. In terms of accessing and using the data in the tables and other objects,
the number (or location) of the files is immaterial.
The database files are fixed in size and never grow bigger than the size at
which they were created
Control Files:
The control files and redo logs support the rest of the architecture. Any
database must have at least one control file, although you typically have more
than one to guard against loss. The control file records the name of the
database, the date and time it was created, the location of the database and
redoes logs, and the synchronization information to ensure that all three sets
of files are always in step. Every time you add a new database or redo log file
to the database, the information is recorded in the control files.
Redo Logs:
Any database must have at least two redo logs. These are the journals for the
database; the redo logs record all changes to the user objects or system
objects. If any type of failure occurs, the changes recorded in the redo logs
can be used to bring the database to a consistent state without losing any
committed transactions. In the case of non-data loss failure, Oracle can apply
the information in the redo logs automatically without intervention from the
DBA.
The redo log files are fixed in size and never grow dynamically from the size
at which they were created.

82. What is ROWID?


The ROWID is a unique database-wide physical address for every row on
every table. Once assigned (when the row is first inserted into the
database), it never changes until the row is deleted or the table is dropped.
The ROWID consists of the following three components, the combination of
which uniquely identifies the physical storage location of the row.
Oracle database file number, which contains the block with the rows
Oracle block address, which contains the row
The row within the block (because each block can hold many rows)
The ROWID is used internally in indexes as a quick means of retrieving
rows with a particular key value. Application developers also use it in SQL
statements as a quick way to access a row once they know the ROWID

84. What is database Trigger?


A database trigger is a PL/SQL block that can defined to automatically
execute for insert, update, and delete statements against a table. The
trigger can be defined to execute once for the entire statement or once for
every row that is inserted, updated, or deleted. For any one table, there
are twelve events for which you can define database triggers. A database
trigger can call database procedures that are also written in PL/SQL.

85. Name two utilities that Oracle provides, which are use for backup
and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use
to back up and restore the database. These utilities are Export and Import.
The Export utility dumps the definitions and data for the specified part of the
database to an operating system binary file. The Import utility reads the file
produced by an export, recreates the definitions of objects, and inserts the
data
If Export and Import are used as a means of backing up and recovering the
database, all the changes made to the database cannot be recovered since the
export was performed. The best you can do is recovering the database to the
time when the export was last performed.

86. What are stored-procedures? What are the advantages of using


them?
Stored procedures are database objects that perform a user defined
operation. A stored procedure can have a set of compound SQL statements.
A stored procedure executes the SQL commands and returns the result to
the client. Stored procedures are used to reduce network traffic.

You might also like