0% found this document useful (0 votes)
5 views

8.lab manual dbms

r22 lab manual

Uploaded by

Nikhil Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

8.lab manual dbms

r22 lab manual

Uploaded by

Nikhil Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

GURU NANAK INSTITUTIONS TECHNICAL CAMPUS

(AUTONOMOUS)
Special Batch - Emerging Technologies

Database Management Systems


Master Lab Manual
Common to AIML / IT / DS

For the Academic year 2023-24

II B. Tech II Semester

Guru Nanak Institutions Technical Campus (Autonomous)


Ibrahimpatnam, R.R District – 501506 (T. S.)
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS
(AUTONOMOUS)
Special Batch - Emerging Technologies

LAB MANUAL FOR THE ACADEMIC YEAR 2023-24

Lab Database Management Systems Lab


Semester : II-II
Stream : AIML / DS / IT
Prepared :
Programmer :
Venue :
Block : GNU

HOD-IT

Dr.
Thariq Hussan
S.No. Contents
1 Lab Objectives
2 Lab Outcomes
3 List of Experiments

4 List of Additional Experiments


HOD
5 Text Books / Reference Books

INDEX
LAB OBJECTIVES
 Introduce ER data model, database design and normalization
 Learn SQL basics for data definition and data manipulation

LAB OUTCOMES
CO1: Design database schema for a given application and apply normalization.
CO2: Acquire skills in using SQL commands for data definition and data manipulation.
CO3: Develop solutions for database applications using procedures, cursors and triggers.

LIST OF EXPERIMENTS
1. Concept design with E-R Model
2. Relational Model
3. Normalization
4. Practicing DDL commands
5. Practicing DML commands
6. A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
B. Nested, Correlated subqueries
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and dropping
of Views.
8. Triggers (Creation of insert trigger, delete trigger, update trigger)
9. Procedures
10. Usage of Cursors
LIST OF ADDITIONAL EXPERIMENTS
1. Student Information System
2. Library Management System

TEXT BOOKS
1. Database Management Systems, Raghurama Krishnan, Johannes Gehrke, Tata Mc Graw
Hill, 3rd Edition
2. Database System Concepts, Silberschatz, Korth, McGraw Hill, V edition.

REFERENCE BOOKS
1. Database Systems design, Implementation, and Management, Peter Rob & Carlos
Coronel 7th Edition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student
Edition.

Week 1: Entity Relationship (E-R Model)

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

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know the entities and attributes and representation of diagrams.

The following are the entities:


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

Attributes of the following entities:


Bus
- BusNo
- Source
- Destination
- CoachType
Passenger
- PassportID
- Name
- Age
- Sex
- Address

Ticket
- TicketNo
- DOJ
- Age
- Sex
- Source
- Destination
- BusNo

Reservation
- PNRNo
- DOJ
- ContactNo
- No_of_seats
- BusNo
- Address

Cancellation
- PNRNo
- DOJ
- No_of_seats
- Status
The schemes for the following entities are:
1. Bus (BusNo String, Source String, Destination String, Coach_Type String);
2. Passenger (PassportID String, Name String, Age integer, Sex character, Address
String);
3. Ticket (TicketNo Integer, DOJ date, Age integer, Dept_time Timestamp, Source
String, Destination String, BusNo String);
4. Reservation (PNRNo String, DOJ Date, ContactNo integer, No_of_Seats integer,
BusNo String, Address String);
5. Cancellation (PNRNo String, DOJ Date, SeatNo integer, ContactNo integer, Status
String);

Conclusion: The student is able to identify the Entities and Attributes of the Roadway
Travels.
Week 2: Concept design with E-R Model

Aim: To relate the entities appropriately. Apply cardinalities for each relationship. Identify
strong and weak entities. Indicate the type of relationships (total/partial). Incorporate
generalization, aggregation and specialization etc wherever required.

Recommended Hardware / Software Requirements:


 Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
 MySQL 5.6.1

Prerequisites: Student must know the entities and attributes and relationship among entities.
 Conceptual data models provide concepts that are close to the way many users
perceive data.
 Before implementation, a rough model of database is created.
 This model is never implemented but is used for designing purpose.
 This model use concepts such as entities, attributes and relationships.
o Example: E-R Model

The E-R data model employs three basic notions:


 Entity
 Attributes
 Relationship

Entity: It is an object with a physical existence. For example, each person in an enterprise,
car, house, a company, student.

Entity Type & Entity Sets


• Entity Type
– Collection of entities that have the same attributes.
Ex: STUDENT
• Entity Set
– The collection of all entities of a particular entity type.
Ex: Set of all rows, 10 rows of STUDENT

General Representation of Entity type:

Attributes: Attributes are the particular properties that describe an entity.

Ex: A STUDENT entity may be described by student’s name, student’s roll_number.


Relationship

• Relates two or more distinct entities with a specific meaning.

Draw an E-R Diagram for an employee works in one department. The department contains
phone, the employee also has phone. Assume that an employee works in maximum 2
departments or minimum one department. Each department must have maximum 3 phones or
minimum zero phone. Design an E-R diagram for the above.
Construct an E-R diagram for a car-insurance company whose customers own one or more
cars each. Each car has associated with it zero to any number of recorded accidents.

Construct an E-R diagram for a hospital with a set of patients and a set of medical doctors.
Associate with each patient a log of the various tests and examinations conducted.
Week 3: Relational Model

Aim: To represent all the entities (Strong, Weak) in tabular fashion. Represent relationships
in a tabular fashion.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the Relational Model

Bus:

ColumnName Datatype Constraints Type of Attributes


BusNo Varchar(10) Primary Key Single-valued
Source Varchar(20) Single-valued
Destination Varchar(20) Simple
CouchType Varchar(10) Simple

Ticket:

ColumnName Datatype Constraints Type of Attributes


TicketNo Integer Primary Key Single-valued
DOJ Date Single-valued
Address Varchar(20) Composite
ContactNo Integer Multi-valued
BusNo Varchar(10) Foreign Key Single-valued
SeatNo Integer Simple
Source Varchar(10) Simple
Destination Varchar(10) Simple
Passenger:

ColumnName Datatype Constraints Type of Attributes


PassportID Varchar(15) Primary Key Single-valued
TicketNo Integer Foreign Key Single-valued
Name Varchar(20) Composite
ContactNo Integer Multi-valued
Age Integer Single-valued
Sex Varchar Simple
Address Varchar(20) Composite

Reservation:

ColumnName Datatype Constraints Type of Attributes


PNRNo Interger Primary Key Single-valued
DOJ date Single-valued
No_of_Seats Integer Simple
Address Varchar(20) Composite
ContactNo Integer Multi-valued
BusNo Varchar(10) Foreign Key Single-valued
SeatNo Integer Simple

Cancellation:

ColumnName Datatype Constraints Type of Attributes


PNRNo Interger Primary Key Single-valued
DOJ date Single-valued
SeatNo Integer Simple
ContactNo Varchar(10) Multi-valued
Status Varchar(10) Simple
Conclusion: The student is able to draw the tabular representation of the relations of
Roadway travels.

Viva-Voce

1. What is Relational Model?

2. What are the different types of attribute can be there in any relation?

3. Is this mandatory to have key attributes in every relation?


Week 4: Normalization

Aim: Apply the database normalization techniques for designing relational database tables to
minimize duplication of information like 1NF, 2NF, 3NF, BCNF.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the relational database (SQL)

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., Multivalve attributes are not permitted.

2NF: A relation scheme is said to be in 2NF, if and every non-key attribute is fully
functionally dependent on primary key.

3NF: A relation scheme is said to be in 3NF, and does not have transitivity dependencies. A
relation is said to be 3NF if every determinant is a key for each and every functional
dependency.

BCNF: A Relation scheme is said to be BCNF if the following statements are true for each
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.
i) The given FD is a trival
ii) P is a super key.

1. Create table Bus (BusNo varchar(10) NOT NULL,


Source varchar(20),
Destination varchar(20),
CoachType varchar(10),
PRIMARY KEY(BusNo));

2. Create table Passenger (PassportID varchar(15) NOT NULL,


Name varchar(20),
Age integer,
Sex varchar,
Address varchar(20),
ContactNo Varchar(12),
PRIMARY KEY(PassportID));

3. Create table Ticket (TicketNo integer(10), NOT NULL,


DOJ date, Age integer(2), Sex Varchar,
Source varchar(20), Destination varchar(20),
Dept_Time varchar(10),
PRIMARY KEY(TicketNo));
4. Create table Passenger_Ticket(PassportID varchar(15) NOT NULL,
TicketNo integer(10) NOT NULL,
PRIMARY KEY(PassportID,TicketNo),
FOREIGN KEY(PassportID) REFERENCES Passenger(PassportID),
FOREIGN KEY(TicketNo) REFERENCES Ticket(TicketNo));

5. Create table Reservation(PNR_No integer(10) NOT NULL,


DOJ date,
No_of_seats int(2),
Address varchar(20),
ContactNo Varchar(10),
Status varchar(10),
PRIMARY KEY(PNR_NO));

6. Create table Cancellation(PNR_No integer(10),


DOJ Date,
No_of_Seats integer(2),
Address varchar(20),
ContactNo integer(12),
Status varchar(10),
FOREIGN KEY(PNR_No) REFERENCES Reservation(PNR_No));

Conclusion: The student is able to normalize the tables applying 3NF.

Viva-Voce

1. Define Normalization.

2. What is 1 NF (Normal Form)?

3. What is Fully Functional dependency?

4. What is 2NF?

5. What is 3NF?

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


Week 5: Installation of MySQL and Practicing DDL Commands

Aim: Installation of MySQL. Creating database tables, altering the database, dropping tables
and truncate commands

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the MySQL

Steps for Installation of 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: 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: 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: The program features you selected are being installed. Please wait while the setup wizard
installs MySQL 5.0. This may take several minutes.

Step6: To continue, click next.

Step7: To continue, click next.

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

Step9: The configuration wizard will allow configuring the MySQL Server 5.0 server instance. To
continue, click next.

Step10: Select a standard configuration 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: 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: Processing configuration in progress

Step15: Configuration file created. Windows service MySQL5 installed. Press finish to close the
wizard.
Creating Tables and altering the Tables

1. Mysql>Create table Bus(BusNo varchar(10) NOT NULL, Source varchar(20),


Destination varchar(20), coachType varchar(10), PRIMARY KEY(BusNo));

Table Created

2. Mysql>Create table Passenger(PassportID varchar(15) NOT NULL, Name


varchar(20), Age integer, Sex varchar, Address varchar(20),
ContactNo Varchar(12), PRIMARY KEY(PassportID));

Table Created

3. Mysql>Create table Ticket(TicketNo integer(10), NOT NULL, DOJ


date, Age integer(2), Sex Varchar, Source varchar(20), Destination varchar(20),
Dept_Time varchar(10), PRIMARY KEY(TicketNo));

Table Created

4. Mysql>Create table Passenger_Ticket(PassportID varchar(15) NOT NULL, TicketNo


integer(10) NOT NULL, PRIMARY KEY(PassportID,TicketNo),
FOREIGN KEY(PassportID) REFERENCES Passenger(PassportID),
FOREIGN KEY(TicketNo) REFERENCES Ticket(TicketNo));

Table Created

5. MySql>Create table Reservation(PNR_No integer(10) NOT NULL, DOJ


date,No_of_seats int(2), Address varchar(20), ContactNo Varchar(10), Status
varchar(10), PRIMARY KEY(PNR_NO));

Table Created
6. Mysql>Create table Cancellation(PNR_No integer(10), DOJ Date, No_of_Seats
integer(2), Address varchar(20), ContactNo integer(12), Status varchar(10),
FOREIGN KEY(PNR_No) REFERENCES Reservation(PNR_No));

Table Created

ADD COLUMN CAPACITY to BUS Table

MySql> ALTER TABLE BUS ADD CAPACITY Integer(2);


Mysql> desc bus;

Field Datatype
BusNo varchar(10),
Source varchar(20),
Destination varchar(20),
CoachType varchar(10),
Capacity integer(2)

Conclusion: The student is able to install the MySQL and create database, create tables and
alter tables.

Viva Voce

1. What is DDL?
2. Which command is used to create a table or a database?
3. What are the various commands used for DDL Languages?
Week 6: Practicing DML Commands

Aim: Practicing DML Commands.


DML commands are used to manage data within the scheme objects.
SELECT - Retrieve data from the database.
INSERT - Insert data into a table.
UPDATE - Updates existing data within a table.
DELETE - Delete all records from a table.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the RDBMS SQL.

DML Commands
Mysql>Insert into Bus values(‘AP123’,’Hyderabad’,’Banglore’,’Volvo’);

MySql>Insert into Bus values(‘AP234’,’Mumbai’,’Hyderabad’,’Semi-sleeper’);

Insert 5 or more records like-wise

Mysql> Select * from Bus;

BusNo Source Destination CoachType


AP123 Hyderabad Bangalore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper

Mysql>Insert into Passenger values (82302,’Smith’,23,’M’,’Hyderabad’, ‘9982682829’);

Insert 5 or more records like-wise


Mysql> Select * from Passenger;

PassPortID Name Age Sex Address ContactNo


8939034 Smith 23 M Hyderabad 9443502918
9820023 John 24 M Mumbai 9838930933
8738939 Kavitha 22 F Hyderabad 9983836732

Mysql>Insert into Passenger_Ticket values(‘AP123’,82302);

Insert 5 or more records like-wise

Mysql>Select * from Passenger_Ticket;

PassportID TicketNo
8738939 453
5443243 332

Mysql> Insert into Ticket values(29823,’AP123’,82302,’21-03-2014’,’4:00PM’,


‘9820203033’);

Insert 5 or more records like-wise

TicketNo BusNo PassportID DOJ Dept_time ContactNo


29823 AP123 82302 21-03-2014 4 pm 9832434354
34353 AP234 32243 12-04-2014 5 pm 9855645433

Mysql>Insert into Reservation values(‘783-93930’,’21-03-


2014’,04,’Hyderabad’,’8972389289’,’Confirm’);

Insert 5 or more records like-wise

Mysql> Select * from Reservation;

PNRNo DOJ No_of_seats Address ContactNo


837-99203 21-03-2014 02 Hyderabad 9837383393
938-89894 23-03-2014 04 Hyderabad 9389939202

Mysql>Insert into Cancellation values(‘783-93930’,’21-03-2014’,02,’Confirm’);

Insert 5 or more records like-wise

Mysql>Select * from Cancellation;

PNRNo DOJ No_of_seats Address Status


837-99203 21-03-2014 02 Hyderabad Confirm
938-89894 23-03-2014 04 Hyderabad Confirm
Mysql>Update BUS set BusNo=’AP3456’ where BusNo=’AP123’;

Mysql>Delete from BUS where BusNo=’AP345’;

Conclusion: The student is able to perform DML Commands like Insert, Update, Delete and
Select.

Viva-Voce
1. What are DML commands?
2. Write the syntax for insert command.
3. What is the syntax for update command?
4. Write the syntax for delete command.
5. Write the syntax for select command.
6. Differentiate DCL and TCL.
Week 7: Queries using ANY, All, IN, Exists, Not Exists, Union, Intersect, Constraints

Aim: 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 ‘r’ and ends with ‘h’.
5. Find the names of Passengers whose age is between 30 and 45.
6. Display all the passengers’ names beginning with ‘A’.
7. Display the sorted list of Passengers names.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 64MB RAM and 100 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the RDBMS.

1. Display unique PNR_NO of all reservation


Mysql>Select DISTINCT PNR_NO from Reservation;

PNR_No
783-32923
928-38983

2. Display all the names of male passengers.

Mysql> Select Name from Passenger where Sex=’M’;

Name
Smith
John
3. Display the ticket numbers and names of all the passengers.
MySQL>Select TicketNo,Name from Ticket, Passenger;

name ticketno
Sai 1500
Raju 1502
Ramu 1503

4. Find the ticket numbers of the passengers whose name start with ‘r’ and ends with ‘h’.
MySQL> Select Name from Passenger where name LIKE ‘R%’ AND name LIKE ‘%H’;

Name
Rajesh
Ramesh
5. Find the names of Passengers whose age is between 30 and 45.
MySQL> Select Name from Passenger where age BETWEEN 30 AND 45;

Name
Neha
Ramu

6. Display all the passengers names beginning with ‘A’.


MySQL> Select * from Passenger where NAME LIKE ‘A%’;

Name
Akash
Avinash
Arivind
7. Display the sorted list of Passengers names
MySQL> Select Name from Passenger order by NAME;
Name
Akash
Aravind
Avinash
Neha
Ramu
smith

Conclusion: The student is able to execute the Queries from above database.
Viva-Voce:

1. What is the result of String functions?

2. What is the result of Date functions?

3. What is the result of conversion function?

4. What is Concatenation?

5. What is the difference between LTRIM and RTRIM?


Week 8: Querying

Aim: To practice Queries using Aggregate functions for the following:


 Write a query to display the information present in the passenger and
cancellation tables
 Display the number of days in a week on which the AP123 bus is available
 Find number of tickets booked for each PNR_No using GROUP BY clause
 Find the distinct PNR Numbers that are present

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the RDBMS-SQL

1. Write a Query to display the information present in the passenger and


cancellation tables
MySQL> SELECT * FROM RESERVATION
UNION
SELECT * FROM CANCELLATION;
PNR_NO DOJ No_of_SEATS Address ContactNo Status
78393445 2003-03-04 5 Hyderabad 9440121444 cnfirm
78393930 2003-03-04 4 Hyderabad 9440121232 Cnfirm
78393445 2003-03-04 2 Hyderabad 938837383 Cnfirm
78393445 2003-03-04 4 Hyderabad 938837383 cnfirm

2. Display the Minimum age of the Passenger


MySQL> SELECT MIN(AGE) as MINAGE FROM PASSENGER;
MIN(AGE)
23
3. Find number of tickets booked for each PNR_No using GROUP BY CLAUSE
MySQL> SELECT PNR_NO,SUM(No_of_SEATS) AS SUM_OF_SEATS FROM
RESERVATION GROUP BY PNR_NO;

PNR_NO SUM_OF_SEATS
78393445
78393930

4. Find the distinct PNR Numbers that are present.


MySQL> SELECT DISTINCT PNR_NO FROM RESERVATION;
PNR_NO
78393445
78393930
5.Mysql> select sum(No_of_seats) from Cancellation;

SUM(NO_OF_SEATS)
----------------
6

Viva-Voce
1. What is the difference between SUM and COUNT?
2. What is the purpose of MIN?
3. What is the use of MAX?
4. Define VIEW. What is the use of VIEW?
5. What is difference between DROP table and DELETE?
6. What is the use of AVG?
Week 9: Querying

Aim: To practice Queries using Aggregate functions for following:


 Find the number of tickets booked by a passenger where the number of seats is
greater than 1.
 Find the total number of cancelled seats.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 1GB RAM and 500 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the RDBMS-SQL


Find the number of tickets booked by a passenger where the number of seats is greater
than 1.
MySQL> select * from reservation where NO_of_seats >1;

Find the total number of cancelled seats.


MySQL> SELECT SUM(NO_OF_SEATS) AS CANCELED_SEATS FROM
CANCELLATION;

CANCELLED_SEATS
03

Conclusion: The student is able to execute the Queries using SQL Clauses.
Week 10:Triggers

Aim: Creation of insert trigger, delete trigger and update trigger.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 64MB RAM and 100 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the Relational Database SQL-Triggers.

MySQL>CREATE TABLE BUS(BUSNO VARCHAR(10) NOT NULL, SOURCE VARCHAR(10),


DESTINATION VARCHAR(10), CAPACITY INT(2), PRIMARY KEY(BUSNO));
MySQL>INSERT INTO BUS VALUES('AP123','HYD','CHENNAI','40');

CREATE TABLE BUS_AUDIT1(ID INT NOT NULL AUTO_INCREMENT, SOURCE


VARCHAR(10) NOT NULL, CHANGEDON DATETIME DEFAULT NULL, ACTION
VARCHAR(10) DEFAULT NULL, PRIMARY KEY(ID));
DELIMITER $$
CREATE TRIGGER BEFORE_BUS_UPDATE
BEFORE UPDATE ON BUS
FOR EACH ROW
BEGIN
INSERT INTO BUS_AUDIT1
SET action='update',
source=OLD.source,
changedon=NOW();
END$$

UPDATE
MySQL>UPDATE BUS SET SOURCE='KERALA' WHERE BUSNO='AP123'$$

S.No Source Changedon Action


1 Bangalore 2014:03:23 12:51:00 Insert
2 Kerala 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete
INSERT
CREATE TRIGGER BEFORE_BUS_INSERT
BEFORE INSERT ON BUS
FOR EACH ROW
BEGIN
INSERT INTO BUS_AUDIT1
SET action='Insert',
source=NEW.source,
changedon=NOW();
END$$
INSERT INTO BUS VALUES('AP789','VIZAG','HYDERABAD',30)$$

S.No Source Changedon Action


1 Bangalore 2014:03:23 12:51:00 Insert
2 Kerala 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete

CREATE TRIGGER BEFORE_BUS_DELETE


BEFORE DELETE ON BUS
FOR EACH ROW
BEGIN
DELETE FROM BUS_AUDIT1
SET action='Insert',
source=NEW.source,
changedon=NOW();
END$$
DELETE FROM BUS WHERE SOURCE=’HYDERABAD’$$
S.No Source Changedon Action
1 Bangalore 2014:03:23 12:51:00 Insert
2 Kerala 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete
Conclusion: The student is able to work on Triggers and create active database.

Viva-Voce

1. What is TRIGGER?

2. What is BEFORE Trigger?

3. What is AFTER Trigger?

4. What is the difference between BEFORE and AFTER?

5. What are ROW and Statement Triggers?

6. What is INSTEAD Triggers?

7. What are the types on Triggers?

8. It is possible to create Trigger on Views?


Week 11: Procedures

Aim: Creation of stored procedures and execution of procedures and modification of


procedures.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 64MB RAM and 100 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the Relational Database SQL-Procedures

CREATE PROCEDURE BUS_PROC1()


BEGIN
SELECT * FROM BUS;
END$$
CALL BUS_PROC1()$$

BusNo Source Destination CoachType


AP123 Hyderabad Bangalore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper

CREATE PROCEDURE SAMPLE2()


BEGIN
DECLARE X INT(3);
SET X=10;
SELECT X;
END$$

CALL SAMPLE2()$$
BusNo Source Destination CoachType
AP123 Hyderabad Bangalore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper
CREATE PROCEDURE SIMPLE_PROC(OUT PARAM1 INT)
BEGIN
SELECT COUNT(*) INTO PARAM1 FROM BUS;
END$$
CALL SIMPLE_PROC(@a)$$
PARAM1
4

Conclusion: The Student is able to work on Stored Procedures.

Viva Voce

1. What is a stored procedure?


2. When would you use stored procedure or functions?
3. What are external procedures?
4. What is input parameter?
5. How to use stored procedures?
Week 12: Cursors

Aim: 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.

Recommended Hardware / Software Requirements:


● Hardware Requirements: Intel Based desktop PC with minimum of 166 MHZ or
faster processor with at least 64MB RAM and 100 MB free disk space.
● MySQL 5.6.1

Prerequisites: Student must know about the Relational SQL-Cursors

Cursors
In MySQL, a cursor allows row-by-row processing of the result sets. A cursor is used for the
result set and returned from a query. By using a cursor, you can iterate, or by step through the
results of a query and perform certain operations on each row. The cursor allows you to
iterate through the result set and then perform the additional processing only on the rows that
require it.

In a cursor contains the data in a loop. Cursors may be different from SQL commands that
operate on all the rows in the returned by a query at one time.

There are some steps we have to follow, given below:

● Declare a cursor

● Open a cursor statement

● Fetch the cursor

● Close the cursor

1. Declaration of Cursor: To declare a cursor you must use the DECLARE statement. With
the help of the variables, conditions and handlers we need to declare a cursor before we can
use it. first of all we will give the cursor a name, this is how we will refer to it later in the
procedure. We can have more than one cursor in a single procedure so its necessary to give it
a name that will in some way tell us what its doing. We then need to specify the select
statement we want to associate with the cursor. The SQL statement can be any valid SQL
statement and it is possible to use a dynamic where clause using variable or parameters as we
have seen previously.

Syntax: DECLARE cursor_name CURSOR FOR select_statement;

2. Open a cursor statement: For open a cursor we must use the open statement. If we want
to fetch rows from it you must open the cursor.

Syntax: OPEN cursor_name;

3. Cursor fetch statement: When we have to retrieve the next row from the cursor and move
the cursor to next row then you need to fetch the cursor.
Syntax: FETCH cursor_name INTO var_name;

If any row exists, then the above statement fetches the next row and cursor pointer moves
ahead to the next row.

4. Cursor close statement: By this statement closed the open cursor.

Syntax: CLOSE_name;

By this statement we can close the previously opened cursor. If it is not closed explicitly then
a cursor is closed at the end of compound statement in which that was declared.

Example: In the following example first of all we have to declare the Cursor and select the all
records from Company table. And after opened the cursor we fetch the record one by one
from cursor. And then insert these records in Products table.

delimiter $$
CREATE PROCEDURE DemoCurs()
BEGIN
DECLARE d INT DEFAULT 0;
DECLARE c_id INT;
DECLARE c_name,c_address VARCHAR(20);
DECLARE cur CURSOR FOR SELECT * FROM company;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET d=1;
DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET d=1;
OPEN cur;
lbl: LOOP
IF d=1 THEN
LEAVE lbl;
END IF;
IF NOT d=1 THEN
FETCH cur INTO c_id,c_name,c_address;
INSERT INTO products VALUES(c_id,c_name,c_address);
END IF;
END LOOP;
CLOSE cur;
END$$
mysql> delimiter;
mysql> CALL DemoCurs();
Query OK, 1 row affected (0.12 sec)

mysql> SELECT * FROM Products;

C_id C_Name Address


12303 IBM Bangalore
83893 Infosys Hyderabad

Conclusion: The student is able to work on Cursors.

Viva Voce
1. What is a cursor?
2. What are the types of cursor?
3. What is the use of parameterized cursor?
4. What is the use of cursor variable?
5. What is a normal cursor?
6. What are explicit cursors attributes?

You might also like