It - (20) - 2-2 - Database Management Systems Laboratory Manual (2022-23)
It - (20) - 2-2 - Database Management Systems Laboratory Manual (2022-23)
LABORATORY MANUAL
B.TECH
(IIYEAR–IISEM)
(2022-23)
PREPARED BY
K.SHANTHI
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
1. Students are advised to come to the laboratory at least 5 minutes before (to the
startingtime), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to
thelabwith the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement,
Aim,Algorithm,Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments and other utensils (if
any)needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
systemallotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observationnote book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintainthe discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
whichshould be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode
during thelab sessions.Misuse of the equipment, misbehaviors with the staff and
systemsetc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ;
if anybody found loitering outside the lab / class without permission during
working hourswill be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she must
ensure the system /seat is kept properly.
4 Normalization 14-15
Querying
7 Queries using ANY, ALL, IN, INTERSECT, UNION 50-54
Querying
8 Using aggregate functions COUNT, SUM 55-59
using GROUPBY andHAVING.
9 TRIGGER 60-64
Procedures and Stored Procedures
10 Creation, Execution and Modification of stored 65-70
Procedure
12 CASESTUDY 1 73
13 CASESTUDY 2 74
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.
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
1
Retrieval of information stored in more than one table
An RDBMS product has to satisfy at least Seven of the 12 rules of Codd to beaccepted
as a full- fledged RDBMS.
Data is stored in tables. Tables have columns, rows and names. Tables can be related to
each other if each has a column with a common type of information. The most famous
RDBMS packages are Oracle, Sybase and Informix.
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)
2
The Degree of Relationship indicates the link between two entities for a specified occurrence of
each.One to One Relationship: (1:1)Student Has Roll No.
One student has only one Rollno. For one occurrence of the first entity, there can be, at themost one
related occurrence of the second entity, and vice-versa.
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
3
3. The View Updating Rule
All views that are theoretically updatable are also updatable by the system.
4. The Insert and Update Rule
This rule indicates that all the data manipulation commands must be operational on sets of rows
having a relation rather than on a single row.
The system must be access or manipulate the data that is distributed in other systems.
4
What is MYSQL
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.
5
Numeric Data 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.
6
Date and Time Types
The MySQL date and time datatypes are as follows −
DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
December 30th, 1973 would be stored as 1973-12-30.
DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-
01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30 th,
1973 would be stored as 1973-12-30 15:30:00.
TIMESTAMP − A timestamp between midnight, January 1 st, 1970 and sometime in 2037. This looks
like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the
afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
TIME − Stores the time in a HH:MM:SS format.
YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example
YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then
YEAR can be 1901 to 2155. The default length is 4.
String Types
Although the numeric and date types are fun, most data you'll store will be in a string format. This list
describes the common string datatypes in MySQL.
CHAR(M) − A fixed-length string between 1 and 255 characters in length (for example CHAR(5)),
right-padded with spaces to the specified length when stored. Defining a length is not required, but the
default is 1.
VARCHAR(M) − A variable-length string between 1 and 255 characters in length. For example,
VARCHAR(25). You must define a length when creating a VARCHAR field.
7
ROADWAY TRAVELS
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.
8
WEEK-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
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
BusN
Ticket
9
Passenger:
ContactNO
Age
Sex
PNRNO
Name
TicketNo
Passenger
Cancellation(Entity)
Journeydate SeatNo
ContactNo
PNRNO
Cancellation
10
WEEK- 2
11
WEEK: 3
Relational Model
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)
12
Ticket:
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
13
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 oflogical
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 Normalization is a process of converting a relation to be standard form by decomposition a larger
relation into smaller efficient relation that depicts a good database design.
• 1NF: A Relation scheme is said to be in 1NF if the attribute values in the relation are atomic.i.e.,
Mutli –valued attributes are not permitted.
• 2NF: A Relation scheme is said to be in 2NF,iff and every Non-key attribute is fully functionally
dependent on
primary Key.
• 3NF: A Relation scheme is said to be in 3NF,iff and does not have transitivity dependencies. A
Relation is said to be 3NF if every determinant is a key for each & every functional dependency.
• BCNF: A Relation scheme is said to be BCNF if the following statements are true for eg FD P->Q
in set F of FDs that holds for each FD. P->Q in set F of FD’s that holds over R. Here P is the subset
of attributes of R & Q is a single attribute of R represented by a single instance only.
14
mysql> Create table Reservation(PNRNO integer Primary key, JourneyDate DateTime,NoofSeats
int,Address varchar(20),Contact No Integer);
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
15
WEEK-5
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.
16
Step 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.
Step 4
17
Step 5
28
Step 6: To continue, click next
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
29
Step 9:The configuration wizard will allow you to configure the MySQL Server 5.0 server instance.To continue,
click next
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.
30
Step11
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.
31
Step13
Ready to execute? Clicks execute to continue.
Step14
Processing configuration in progress.
32
Step15
Configuration file created. Windows service MySQL5 installed. Press finish to close
thewizard.
34
5(b) :Installation of MangoDB
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.
35
Mongo DB Installation:
You can find the downloaded file in the downloads directory. You can follow the stepsmentioned
there and install the software.
36
On completing the installation successfully, you will find the software package in your Cdrive.
C:\Program Files\MongoDB\Server\4.4\bin.
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.
37
Execute the Mongo App:
After creating an environment path, you can open the command prompt and justtype in mongo and
press enter.
38
The mongo server is then generated and is up and running.
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.
39
PRACTICING DDL COMMANDS
Data Definition Language
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:
40
1. CREATION OF TABLES:
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;
41
Reservation Table:
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;
42
ALTER TABLE :
To ADD a column:
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;
43
TO ADD FOREIGN KEY TO THE EXISTING TABLE
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
44
RENAME table old tablename TO new tablename;
Example:
MYSQL>RENAME table passenger TO Passenger;
VIVA QUESTIONS
45
WEEK- 6
DML COMMANDS
SYNTAX:
INSERT INTO tablename values (columnname1, columnname2,….columnname n)
SYNTAX
UPDATE
46
WHERE somecolumn=somevalue;
DELETE
TEST OUTPUT:
SQL> select * from Passenger;
SYNTAX
Example:
TESTOUTPUT:
47
b. Elimination of duplicates from the select statement
EXAMPLE QUERY:
TEST OUTPUT:
TEST OUTPUT:
Example1:
Display Data From BUS Table
48
VIVA QUESTIONS
1. What are the DML commands?
2. How the data or values to be entered into a table?
3. What is the use of DELETE command?
4. How the data or values to be updated on a table?
5. List out the uses of SELECT command?
6. How the data or values are retrieved from a table?
7. Define DML? What are the DML commands?
49
WEEK -7
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
50
QUERIES
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');
51
TEST OUTPUT:
52
TEST OUTPUT:
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:
53
VIVA QUESTIONS
3) What happens if we eliminate HAVING clause in a query which is having both GROUP BY
and HAVING clauses.
54
WEEK 8 & 9
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
55
1. Write a Query to display the Information present in the Reservation and cancellation tables.
mysql>select * from Reservation
union
select * from Cancellation;
TEST OUTPUT:
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
56
5. Find the distinct PNR numbers that are present.
mysql>select distinct(PNR_NO) from Reservation;
TEST OUTPUT:
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
57
AIM : Implement Views:
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.
Empno=1122;
TEST OUTPUT:
58
mysql >Update EmpDept_Vw set salary=4300 where Empno=1125;
TEST OUTPUT:
DESTROYING A VIEW:
TEST OUTPUT:
VIVA QUESTIONS:
1. Define view.
59
WEEK 10
Triggers
In MySQL, a trigger is a set of SQL statements that is invoked automatically when a change is made tothe
data on the associated table. A trigger can be defined to be invoked either before or after the data ischanged
by INSERT, UPDATE or DELETE statement.
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 thatuses the
values of each row affected by the triggering statement.
60
2. Statement Triggers :A statement trigger is fired once on behalf of the triggering statement,
regardless of the number of rows in the table that the triggering statement affects (even if no rows are
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 isto
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;
61
FIRING A TRIGGER:
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:
62
mysql> update a row in the employees table:
UPDATE employeesSET
lastName = 'Phan'WHERE
employeeNumber = 1056;
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.
63
VIVA QUESTIONS:
64
WEEK 11 &12
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.
65
Executable_section It represents the code for the function execution.
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:
66
table rows. The following code creates a procedure named get_merit_students:
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 ;
67
In this procedure, we have used the IN parameter as 'var1' of integer type to accept a number from users.
Its body part fetches the records from the table using a SELECT statement
and returns only those rows that will be supplied by the user. It also returns the total number of rows of
the specified table. See the procedure code:
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 ;
68
mysql> CALL display_max_mark(@M);
mysql> SELECT @M;
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 ;
69
CREATE PROCEDURE my Proc() BEGIN
Procedures created
;
VIVA QUESTIONS:
70
WEEK: 13
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
71
mysql> select host, user from mysql.user;
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 & DCLcommands.
5. Who has the privilegeto access the DCLcommands.
72
CASE STUDY 1
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.
73
CASESTUDY 2
Normalization Exercise
UNF:
1NF:
2NF:
3NF:
same as 2NF
74