Database Management Systems Laboratory Manual & Record
Database Management Systems Laboratory Manual & Record
B.TECH
(IIYEAR–IISEM)
(2021-22)
Vision
➢ To achieve high quality in technical education that provides the skills and
attitude to adapt to the global needs of the Information Technology sector,
Mission
➢ To equip the students with the cognizance for problem solving and to
improve the teaching learning pedagogy by using innovative techniques.
➢ To strengthen the knowledge base of the faculty and students with motivation
towards possession of effective academic skills and relevant research experience.
➢ To promote the necessary moral and ethical values among the engineers, for the
betterment of the society.
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)
PEO1 : PROFESSIONALISM & CITIZENSHIP
4 Normalization 14-15
9 TRIGGER 49-53
Procedures and Stored Procedures
10 Creation, Execution and Modification of stored 54-59
Procedure
12 CASESTUDY 1 62
13 CASESTUDY 2 63
INTRODUCTION
Types of database models:
Hierarchical Model
This model is like a hierarchical tree structure, used to construct a hierarchy of
records in the form of nodes and branches. The data elements present in the structure have
together as a logical unit. A parent unit may have many child units, but a child is restricted
• It cannot demonstrate the overall data model for the enterprise because of the
non-availability of actual data at the time of designing the data model.
• It cannot represent the Many-to-Many relationship.
Network Model
• It supports the One-To-One and One-To-Many types only. The basic objects in
this model are Data Items, Data Aggregates, Records and Sets.
Relational Model
• An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to beaccepted
as a full- fledged RDBMS.
1 Rahul Satelite
2 Sachin Ambawadi
3 Saurav Naranpura
1 78 89 94
2 54 65 77
3 23 78 46
Here, both tables arebased on students details. Common field in both tables is Rollno.
So wecan say both tables are related with each other through Rollno column.
Degree of Relationship
One to One (1:1)
One to Many or Many to One (1:M / M: 1)
Many to Many (M: M)
1 :M
Course Contains Students
As per the Institutions Norm, One student can enroll in one course at a time however, in one course,
there can be more than one student.
For one occurrence of the first entity there can exist many related occurrences of the second entity
and for every occurrence of the second entity there exists only one associated occurrence of the
first.
Oracle has introduced added functionality to this by incorporated object-oriented capabilities. Now
it is known is as Object Relational Database Management System (ORDBMS). Object- oriented
concept is added in Oracle8.
Some basic rules have to be followed for a DBMS to be relational. They are known as Codd’s rules,
designed in such a way that when the database is ready for use it encapsulates the relational theory
to its full potential. These twelve rules are as follows.
E. F. Codd Rules
The system must be access or manipulate the data that is distributed in other systems.
MySQL is a relational database management system based on the Structured Query Language, which is
the popular language for accessing and managing the records in the database. MySQL is open-source and
free software under the GNU license. It is supported by Oracle Company.
MySQL is a Relational Database Management System (RDBMS) software that provides many things,
which are as follows:
It defines the database relationship in the form of tables (collection of rows and columns), also known as
relations.
It uses many SQL queries and combines useful information from multiple tables for the end-users
MySQL is named after the daughter of co-founder Michael Widenius whose name is "My".
MySQL uses many different data types broken into three categories −
• Numeric
• Date and Time
• String Types.
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to MySQL from a
different database system, these definitions will look familiar to you.
The following list shows the common numeric data types and their descriptions −
INT − A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -
2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can
specify a width of up to 11 digits.
TINYINT − A very small integer that can be signed or unsigned. If signed, the allowable range is
from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to
4 digits.
SMALLINT − A small integer that can be signed or unsigned. If signed, the allowable range is from
-32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up
to 5 digits.
MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed, the allowable
range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can
specify a width of up to 9 digits.
BIGINT − A large integer that can be signed or unsigned. If signed, the allowable range is from -
9223372036854775808 to9223372036854775807. If unsigned, the allowable range is from 0 to
18446744073709551615. You can specify a width of up to 20 digits.
• FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define the display length
(M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the
number of decimals and 10 is the total number of digits (including decimals). Decimal precision can
go to 24 places for a FLOAT.
• DOUBLE(M,D) − A double precision floating-point number that cannot be unsigned. You can
define the display length (M) and the number of decimals (D). This is not required and will default
to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE.
REAL is a synonym for DOUBLE.
• DECIMAL(M,D) − An unpacked floating-point number that cannot be unsigned. In the unpacked
decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of
decimals (D) is required. NUMERIC is a synonym for DECIMAL.
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.
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
TheattributesintheEntities:B
us:(Entity)
Destination
Source
CouchType
BusNo
Bus
Reservation(Entity)
ContactNo BusNo
No-of-Seats
Journeydate
Address
PNRNO
Reservation
Ticket:(Entity)
Dep-Time
Source
Age
Sex
Journeydate
Destination
TicketNo
BusNo
Ticket
ContactNO
Age
Sex
PNRNO
Name
TicketNo
Passenger
Cancellation(Entity)
Journeydate SeatNo
ContactNo
PNRNO
Cancellation
The following are tabular representation of the above entities and relationships
BUS:
COLUMNNAME DATATYPE CONSTRAINT
Source varchar2(20)
Destination varchar2(20)
CoachType varchar2(20)
Reservation:
COLUMNNAME DATATYPE CONSTRAINT
Journeydate Date
No-of-seats integer(8)
Address varchar2(50)
Passenger
Name varchar2(15)
Age integer(4)
Sex char(10) (Male/Female)
Contactno Number(9) Should be equal to 10numbers
And not allow other than
numeric
Cancellation:
Journey-date Date
Seatno Integer(9)
Contact_No Number(9) Should be equal to 10numbers
And not allow other than
numeric
mysql> Create table Ticket(TicketNo Integer Primary key,JourneyDate DateTime, Age Int(4),Sex
char(2),Source varchar(20),Destination varchar(20),DeptTime varchar(2));
VIVA QUESTIONS
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.
Step 4
Step 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
Step 10 :Select a standard configuration and this will use a general purpose configuration for the server
that can be tuned manually. To continue, click next
d.
Step:11 Check on the install as windows service and include bin directory in windows path.
Tocontinue,clicknext.
Step12: Please set the security options by entering the root password and confirm retype the
password.continue, click next.
Step14
Processing configuration in progress.
thewizard.
At the time of writing, the latest version is 4.4.5. Ensure that the platform is Windows, and the
packageis MSI. Go ahead and click on download.
You can find the downloaded file in the downloads directory. You can follow the stepsmentioned
there and install the software.
You can see that there are mongo and mongod executable files. The mongod file is the daemonprocess
that does the background jobs like accessing, retrieving, and updating the database.
It’s best practice to create an environment variable for the executable file so that youdon’t have to
change the directory structure every time you want to execute the file.
After creating an environment path, you can open the command prompt and justtype in mongo and
press enter.
To verify if it did the setup correctly, type in the command show DBS.
With that, you have successfully installed and set up MongoDB on your Windows system.
The data definition language is used to create an object, alter the structure of an object and also drop already
created object. The Data Definition Languages used for table definition can be classified into following:
CREATE TABLE:
Table is a primary object of database, used to store data in form of rows and columns. It is created
using following command:
CREATING TABLES:
Example:
mysql> create table Bus (Bus_No varchar(5), source varchar(20), destination varchar(20), daysperweek int);
Table Created.
Above definition will create simple table. Still there are more additional option related with create
table for the object-relation feature we will discuss it afterwards.
Desc command:
Describe command is external command of Oracle. The describe command is used to view thestructure
of table as follows.
Desc <table name>
mysql> desc Bus;
Mysql>desc passenger;
mysql > create table Reservation (PNR_NO integer(9), No_of_seats integer(8), Address varchar(50),
Contact_No Bigint(12), Status varchar(10));
desc Reservation;
Cancellation Table:
mysql > create table Cancellation (PNR_NO integer (9), No_of_seats integer (8), Address varchar (50),
Contact_No integer (12), Status char (3));
Table created.
Ticket Table:
mysql >create table Ticket(Ticket_No integer(9) primary key, age int, sex char(4) Not null, source
varchar(2), destination varchar(20), dep_time varchar(4));
Table created;
Example:
To DROP a column:
SYNTAX: ALTER TABLE <TABLE NAME>DROP COLUMN <COLUMN NAME>;
Example:
To MODIFY a column:
SYNTAX: ALTER TABLE <TABLE NAME>MODIFY COLUMN <COLUMN NAME>
<NEW DATATYPE>(<NEW SIZE>);
Example:
mysql >alter table Reservation modify column status varchar(10);
mysql >desc Reservation;
mysql > ALTER TABLE passenger ADD FOREIGN KEY (pnrno) REFERENCES Reservation (PNR_NO);
Table altered.
desc passenger;
mysql > ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO) REFERENCES
Reservation (PNR_NO);
Table altered.
TRUNCATE TABLE:
If there is no further use of records stored in a table and the structure is required then only data can be
deleted using truncate command. Truncate command will delete all the records permanently of specified
table as follows.
RENAME A TABLE
Example:
MYSQL>RENAME table passenger TO Passenger;
VIVA QUESTIONS
DML COMMANDS
SYNTAX:
INSERT INTO tablename values (columnname1, columnname2,….columnname n)
SYNTAX
UPDATE
DELETE
TEST OUTPUT:
SQL> select * from Passenger;
SYNTAX
Example:
TESTOUTPUT:
EXAMPLE QUERY:
TEST OUTPUT:
TEST OUTPUT:
Example1:
Display Data From BUS Table
UNION
Union is used to combine the results of two queries into a single result set of all matching rows. Both the
queries must result in the same number of columns and compatible data types in order to unite. All
duplicate records are removed automatically unless UNION ALL is used.
INTERSECT
It is used to take the result of two queries and returns the only those rows which are common in both
result sets. It removes duplicate records from the final result set.
EXCEPT
It is used to take the distinct records of two one query and returns the only those rows which do not
appear in the second result set.
EXAMPLES:
Let us create tables for sailors, Reserves and Boats
1. Find all sailor id’s of sailors who have a rating of at least 8 or reserved boat 103.
2. Find all sailor id’s of sailors who have a rating of at least 8 and reserved boat 103.
3. Find the names of sailors who have reserved boat number 103.
mysql >(select s.sname from sailors s where s.sid in (select r.sid from reserves r where r.bid=103);
TEST OUTPUT:
4. Find the names of sailors who have never reserved boat number 103.
mysql >(select s.sname from sailors s where s.sid not in (select r.sid from reserves r where r.bid=103);
TEST OUTPUT:
5. Find sailors whose rating is better than some sailor called Horatio
mysql >(select s.sid from sailors s where s.rating > any(select s2.rating from sailors s2 where
s2.sname='Horatio');
4. Find the ticket numbers of the passengers whose name start with 'r' and ends with 'h'.
Mysql>select ticketno from Passenger where Name like'r%h';
TEST OUTPUT:
TEST OUTPUT:
TEST OUTPUT:
3) What happens if we eliminate HAVING clause in a query which is having both GROUP BY
and HAVING clauses.
Querying Using Aggregate functions (COUNT, SUM, AVERAGE using GROUPBY and
HAVING) Creation and dropping of Views.
Aggregate operators: In addition to simply retrieving data, we often want to perform some computation
or summarization. SQL allows the use of arithmetic expressions.
1. COUNT:
SYNTAX:
Select count ([<distinct>/<ALL]<expr>)
2. SUM:
SYNTAX:
Select SUM ([<distinct>/<ALL]<column name>)
3. AVG:
SYNTAX:
Select AVG ([<distinct>/<ALL]<column name>)
4. MINIMUM(MIN):
SYNTAX:
Select MIN ([<distinct>/<ALL]<expr>)
5. MAXIMUM(MAX):
SYNTAX:
Select MAX ([<distinct>/<ALL]<expr>)
SYNTAX
2. Display the number of days in a week on which the 9W01 bus is available.
TEST OUTPUT:
3. Find number of tickets booked for each PNR_no using GROUP BY CLAUSE
mysql>select count(No_of_seats),PNR_NO from Reservation group by PNR_NO;
TEST OUTPUT:
4. Find the number of tickets booked by a passenger where the number of seats is greater than 1
VIEWS
After a table is created and populated with data, it may become necessary to prevent all users from accessing
all columns of a table, for data security reasons. This would mean creating several tables having the
appropriate number of columns and assigning specific users to each table as required. This will achieve the
security requirements but will rise to a great deal of redundant data being resident in tables, in the database.
To reduce redundant data to the minimum possible, oracle allows the creation ofan object called a view.
A view is a virtual table or logical representation of another table or combination of tables. A view
consists of rows and columns just like a table. The difference between a view and a table is that views
are definitions built on top of other tables (or views), and do not hold data themselves. If data is
changing in the underlying table, the same change is reflected in the view. A view can be built on top of
a single table or multiple tables. It can also be built on top of another view. A view derives its data from
the tables on which it is based. These tables are called base tables. Base tables might in turn be actual
tables or might be views themselves. All operations performed on a view actually affect the base table
of the view. We can use views in almost the same way as tables. Also can query, update, insert into and
delete from views, just as in standard tables
View created.
Example:
SQL>Select Empno,Ename,Salary from EmpView where salary in (10000,20000);
TEST OUTPUT:
UPDATABLE VIEWS:
Syntax for creating an Updatable View:
Create View Emp_vw As
Select Empno,Ename,Deptno from Employee;
View created.
SQL>Insert into Emp_vw values(1126,’Brijesh’,20);
SQL>Update Emp_vw set Deptno=30 where
Empno=1125;
1 row updated.
Empno=1122;
TEST OUTPUT:
TEST OUTPUT:
DESTROYING A VIEW:
TEST OUTPUT:
VIVA QUESTIONS:
1. Define view.
A database trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database. The trigger is mostly used for maintaining the integrity of the
information on the database.
Types of Triggers:-
1. Row Triggers :-A row trigger is fired each time the table is affected by the triggering statement. For
example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each
row affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is not
executed at all.
Row triggers are useful if the code in the trigger action depends on data provided by the triggering
statement or rows that are affected. For example, Figure 15 - 3 illustrates a row trigger that uses the
values of each row affected by the triggering statement.
affected). For example, if a DELETE statement deletes several rows from a table, a statement-level
DELETE trigger is fired only once, regardless of how many rows are deleted from the table.
Statement triggers are useful if the code in the trigger action does not depend on the data provided
by the triggering statement or the rows affected. For example, if a trigger makes a complex security
check on the current time or user, or if a trigger generates a single audit record based on the type of
triggering statement, a statement trigger is used.
When defining a trigger, specify the trigger timing. That is, specify whether the trigger action is to
be executed before or after the triggering statement. BEFORE and AFTER apply to both statement and
row triggers
Example:
trigger_time=before/after
trigger_event=insert/delete/update
Example:
CREATE TRIGGER sal_sum after insert ON emp
FOR EACH ROW SET @sal = @sal + NEW.sal;
First, create a new table named employees_audit to keep the changes to the employees table:
create a BEFORE UPDATE trigger that is invoked before a change is made to the employees table.
Inside the body of the trigger, we used the OLD keyword to access values of the columns
employeeNumber
and lastname of the row affected by the trigger.
show all triggers in the current database by using the SHOW TRIGGERS statement:
query the employees_audit table to check if the trigger was fired by the UPDATE statement:
create another table called reminders that stores reminder messages to members.
PROCEDURES
Procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored inside
the database. It is a subroutine or a subprogram in the regular computing language. A procedure always
contains a name, parameter lists, and SQL statements. We can invoke the procedures by using triggers,
other procedures and applications such as Java
, Python
, PHP, etc.
It was first introduced in MySQL version 5. Presently, it can be supported by almost all relational
database systems.
Creating a procedure:
The following syntax is used for creating a stored procedure in MySQL. It can return one or more value
through parameters or sometimes may not return at all. By default, a procedure is associated with our
current database. But we can also create it into another database from the current database by specifying
the name as database_name.procedure_name.
DELIMITER &&
CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [, parameter
datatype]) ]
BEGIN
Declaration_section
Executable_section
END &&
DELIMITER ;
Parameter Explanations
parameter It represents the number of parameters. It can be one or more than one.
IN parameter
It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the calling
program has to pass an argument to the stored procedure. This parameter's value is always protected.
OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the
changed (new) value is passed back to the calling program. It is noted that a procedure cannot access the
OUT parameter's initial value when it starts.
INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the argument, and
the procedure can modify the INOUT parameter, and then passes the new value back to the calling
program.
Suppose this database has a table named student_info that contains the following data:
DELIMITER &&
CREATE PROCEDURE get_merit_student ()
BEGIN
SELECT * FROM student_info WHERE marks > 70;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END &&
DELIMITER ;
DELIMITER &&
CREATE PROCEDURE get_student (IN var1 INT)
BEGIN
SELECT * FROM student_info LIMIT var1;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END &&
DELIMITER ;
DELIMITER &&
CREATE PROCEDURE display_max_mark (OUT highestmark INT)
BEGIN
SELECT MAX(marks) INTO highestmark FROM student_info;
END &&
DELIMITER ;
In this procedure, we have used the INOUT parameter as 'var1' of integer type. Its body part first fetches
the marks from the table with the specified id and then stores it into the same variable var1. The var1
first acts as the IN parameter and then OUT parameter. Therefore, we can call it the INOUT parameter
mode. See the procedure code:
DELIMITER &&
CREATE PROCEDURE display_marks (INOUT var1 INT)
BEGIN
SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
END &&
DELIMITER ;
Procedures created
;
VIVA QUESTIONS:
DCL (DATA CONTROL LANGUAGE): Data Control Language statements are used to create roles,
permissions, and referential integrity as well it is used to control access to database by securing it. DCL
Commands are Grant and Revoke
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
TEST OUTPUT
TEST OUTPUT
*To Check what are the GRANTS having for created user
mysql> show grants for mrcet_IT;
TEST OUTPUT
TEST OUTPUT
TEST OUTPUT
VIVA QUESTIONS
1. What are DCL commands?
2. List out the uses of various DCL commands?
3. What are the different types of Commands in SQL.
4. What is the difference between TCL & DCL commands.
5. Who has the privilegeto access the DCL commands.
Note that the Employees relation describes pilots and other kinds of employees as well; every pilot is
certified for some aircraft (otherwise, he or she would not qualify as a pilot), and only pilots are certified to
fly.
Write the following queries in relational algebra, tuple relational calculus, and domain relational
calculus.
3. Find the aids of all aircraft that can be used on non-stop flights from Bonn to Madras.
4. Identify the flights that can be piloted by every pilot whose salary is more than $100,000.
(Hint: The pilot must be certified for at least one plane with a sufficiently large cruising
range.)
5. Find the names of pilots who can operate some plane with a range greater than 3,000
7. Find the eids of employees who make the second highest salary.
8. Find the eids of pilots who are certified for the largest number of aircraft.
9. Find the eids of employees who are certified for exactly three aircraft.
5 1NF:
6
7 Pet [ pet_id, pet_name, pet_type, pet_age, owner ]
8 Pet_Visit [ pet_id, visitdate, procedure_no, procedure_name ]
9
0
1
2 2NF:
3
4 Pet [ pet_id, pet_name, pet_type, pet_age, owner ] Pet_Visit [
5 pet_id, visitdate, procedure_no ] Procedure [
6 procedure_no, procedure_name ]
7
8
9 3NF:
0
1 same as 2NF
2