r18dbms Lab Manual
r18dbms Lab Manual
LAB MANUAL
(R18 REGULATION)
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.
• 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.
2. E-R Model
3. Relational Model
4. Normalization
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.
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
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.
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.
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
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
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.
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.
Sex Char,
DML commands are used to for managing data within schema objects. Some examples:
• DELETE - deletes all records from a table, the space for the records remain
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.
4. Find the ticket numbers of the passengers whose name start with and ends with 'h'.
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.
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
ELSE
SET New.Ticketno:at 0;
END IF;
END;
This session you are going to learn Creation of stored procedure, Execution of procedure and modification
of procedure. Practice procedures using the above database.
BEGIN
End;
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
BEGIN
OPEN c1;
Close c1;
END;
Tables
BUS
Source : Varchar
Destination : Varchar
Passenger
PPNO: Varchar(15)) :
PK Name: Varchar(15)
Address: VarChar(20)
Passenger_Tickets
PPNO: Varchar(15)) :
Reservation
PNR_No: Numeric(9) :
FK Journey_date : datetime(8)
Cancellation
PNR_No: Numeric(9) : FK
Journey_date : datetime(8)
Contact_No: Numeric (9) --> Should not be less than 9 and Should not accept any other character other
than Integer
Ticket
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:
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.
CREATE :
...
ALTER :
The alter table statement to make modifications to the table structure such as
Key constraints, Column size, etc.
ALTER TABLE STUDENT ADD CONSTRAINT NOT NULL PRIMARY KEY (StudID);
DROP :
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:
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:
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:
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:
AIM: Analyze the problem and come with the entities in it. Identify what Data
has to be persisted in the databases.
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
Source varchar(20)
Destination varchar(20)
Reservation
Journey_date Date
No_of_seats integer(8)
Address varchar(50)
Seat_no Int(4)
Ticket:
Passenger:
COLOUMN NAME DATA TYPE CONSTRAINT
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
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:
Exp No: 5
Installation of MySQL
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
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 | |
+-------------+-------------+------+-----+---------+-------+
Cancellation Table:
+-------------+--------------+------+-----+---------+-------+
+-------------+--------------+------+-----+---------+-------+
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> 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).
Exp No: 8
1.Write a query to Display the information present in the Cancellation and Reservation Tables
3. Find the No of Seats booked for each PNR_NO using GROUP BY Clause.
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.
Exp No: 10
Views
mysql>Create View passenger_view As Select * from passenger;
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');
Exp No: 11
: Writing triggers
The Syntax:
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’.
delimiter $$
delimiter ;
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:
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;
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.
4. Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
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
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
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.
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.
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
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.
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
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.
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.
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.