0% found this document useful (0 votes)
7 views58 pages

DBMS Lab Manual

The document is a DBMS lab manual for B.Tech II Year students, outlining a series of experiments including E-R model design, relational model representation, normalization techniques, and practicing DDL and DML commands. Each section includes aims, prerequisites, and conclusions to help students understand database concepts and SQL commands. The manual also contains viva-voce questions to assess students' knowledge on the topics covered.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views58 pages

DBMS Lab Manual

The document is a DBMS lab manual for B.Tech II Year students, outlining a series of experiments including E-R model design, relational model representation, normalization techniques, and practicing DDL and DML commands. Each section includes aims, prerequisites, and conclusions to help students understand database concepts and SQL commands. The manual also contains viva-voce questions to assess students' knowledge on the topics covered.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

DBMS

Lab Manual
B.Tech II Year - IISemester
(A.Y. 2021-22)
DBMS LAB MANUAL

List of Experiments as per the university curriculum

S.No. Name of the Experiment

1 Concept design with E-R Model

2 Relational Model

3 Normalization

4 Practicing DDL Commands

5 Practicing DML Commands

6 Querying using ANY,ALL,IN, EXISTS,NOT


EXISTS,UNION,INSERSECT,CONSTRAINTS ETC
7 Querying 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
1. Concept design with E-R Model

Aim: Analyze the problem and come with the entities in it. Identify what Data has to be
Persisted in the databases. 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.

Prerequisites: Student must know the entities and attributes and representation of diagrams/
Student must know the entities and attributes and relationship among entities

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
- Destination
- BusNo

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

Cancellation
- PNRNo
- DOJ
- No_of_seats
- Status
- The attributes in the Entities:
Bus:( Entity)
Destination
Source

Couch Type
Bus No

Bus

- Reservation (Entity)

Contact No
Bus No

No-of-Seats
Journey date
Address

PNR NO

Reservation

- Ticket :(Entity)
Dep- Time
Source
Age

Sex
Journey date
Destination

Ticket No
Bus No
Ticket
Passenger:

Contact NO
Age

Sex
PNR NO
Name

Ticket No

Passenger

Cancellation (Entity)

Seat No
Journey date

Contact No
PNR NO

Cancellation
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

Viva-Voce:
1. What is SQL?
2. Is it Case Sensitive or non Case Snsitive?
3. What is DBMS?
4. What is a Database system?
5. Advantages of DBMS?
6.How many types of database languages are available?

Conclusion: The Student is able design the concept design of Road-way Travels

Viva-Vice:

1. Describe the three levels of data abstraction?

2. Define the "integrity rules"

3. What are the usage of SQL?

4. What is the use of SELECT?

5. What is the difference between UNION and INTERSECT?

6. Does SQL support programming?


2. Relational Model

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

Prerequisites: Student must know about the Relational Model

Bus:

ColumnName Datatype Constraints Type of Attributes


BusNo Varchar(10) Primary Single-valued
Key
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 Single-valued
Key
DOJ date Single-valued
No_of_Seats Integer Simple
Address Varchar(20) Composite
ContactNo Integer Multi-valued
BusNo Varchar(10) Foreign Single-valued
Key
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 draw the tabular representation of the relations of
Roadway travels.

Viva-Voce:

1. What is the difference between SUM and COUNT ?

2. What will you get when you use MIN ?

3. What will you get when you use MAX ?

4. What is VIEW ? and What will you get when you use VIEW

5. What is difference between TRUNCATE and DELETE?


3.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., 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 eacg
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)?


4. Practicing DML COMMANDS

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

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

3. 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));

4. 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));

5. 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));

ADD COLUMN CAPACITY to BUS Table

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

ALTER Table

ALTER TABLE Reservation ADD FOREIGN KEY


(PNR_NO) REFERENCES Passenger (PNR_NO);

Result: query ok, 0 rows affected

ALTER TABLE Cancellation ADD FOREIGN KEY


(PNR_NO) REFERENCES Passenger (PNR_NO);

Result: query ok, 0 rows affected

Alter table Ticket add constraint check_age check


(age>18);

Result: query ok, 0 rows affected

Mysql> desc bus;

Field Datatype
BusNo varchar(10),
Source varchar(20),
Destination varchar(20),
CoachType varchar(10),
Capacity integer(2)
Mysql> TRUNCATE TABLE BUS;

Deletes all the fields of the table

Conclusion: The Student is able Install the MySQL and Create database, Create
tables and Alter tables.

Viva Voce:

1. What is DDL (Data Definition Language)?


2. What is VDL (View Definition Language)?
3. What is SDL (Storage Definition Language)?
4. What is DML (Data Manipulation Language)?
5. What is DML Compiler?
6. What is PL/SQL?
5. Practicing DML Commands

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

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 Banglore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper
sql>Insert into Passenger values(82302,’Smith’,23,’M’,’Hyderabad’,’9982682829’);

Insert 5 or more records like-wise

Mysql> Select * from Passenger;

PassPortID Name Age Se Address ContactNo


x
8939034 Smith 23 M Hyderab 983893023
ad
9820023 John 24 M Mumbai 983893093
30
8738939 Kavitha 22 F Hyderab 998383673
ad 23

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’,

‘98202030334’);

Insert 5 or more records like-wise

TicketNo BusNo PassportI DOJ Dept_time ContaactNO


D
29823 AP123 82302 21-03- 4 pm 9832434354
2014

34353 AP234 32243 12-04- 5pm 9855645433


2014

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- 21-03- 02 Hyderabad 9837383393
99203 2014
938- 23-03- 04 Hyderbad 9389939202
89894 2014

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- 02 Hyderabad Confirm
2014
938-89894 23-03- 04 Hyderbad Confirm
2014

Mysql>UPDATE BUS set BusNo=’AP3456’ where BusNo=’AP123’;


Mysql> DELETE FROM BUS WHERE BusNo=’AP345’;

Conclusion: The Student is able 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. Difference between DCL and TCL

Querying

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.
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 execute the Queries from above database.

Viva-Vice:
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?


6. Practice Queries using ANY, ALL, IN, EXISTS, UNION, INTERSECT Set Operators

Set Operators
Set operators combine the results of two queries into a single one. The following set
operators are availablein SQL.
Union
Union All
Intersect
Minus
7. Queries using Aggregate functions, Group By, Having Clause and Order
Clause creation and dropping of views.

Aim: To Practice Queries using Aggregate functions for the following

1. Write a Query to display the information present in the passenger and cancellation
tables
2. Display the number of days in a week on which the AP123 bus is available
3. Find number of tickets booked for each PNR_No using GROUP BY CLAUSE
4. Find the distinct PNR Numbers that are present.

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 AND

SELECT * FROM CANCELLATION;


PNR_N DOJ No_of_S Addre ContactNo Status
O EATS ss
7839344 2003-03- 5 Hyder 9440121444 cnfirm
5 04 abad
7839393 2003-03- 4 Hyder 9440121232 Cnfirm
0 04 abad
7839344 2003-03- 2 Hyder 938837383 Cnfirm
5 04 abad
7839344 2003-03- 4 Hyder 938837383 cnfirm
5 04 abad

2. Display the Minimum age of the Passenger

MySQL> SELECT MIN(AGE) FROM PASSENGER;

MINAGE
23
3. Find number of tickets booked for each PNR_No using GROUP BY CLAUSE

MySQL> SELECT PNR_NO,NO(SUM_of_SEATS) AS NO_OF_SEATS FROM


RESERVATION GROUP BY PNR_NO;

PNR_NO SUM_OF_SEATS

78393445 5

78393930 4
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
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.

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 selected seats.

MySQL> SELECT SUM(NO_OF_SEATS) AS SELECTED_SEATS FROM

CANCELLATION;
CANCELLED_SEATS
03
Find the No of Seats booked for each PNR_NO using GROUP BY Clause.

Select PNR_NO, sum (No_of_seats) from Reservation group by


PNR_NO;

REASON: because all pnr_no are foreign keys, so all are unique.

4. Find the number of seats booked by a


passenger where the number of seats is
greater than 1.

Select p.name , r.No_of_seats from= Reservation r , passenger p where p.pnr_no =r.pnr_no


group by r.pnr_no having r.No_of_seats > 1;

5. Find the total number of cancelled seats.

Select sum (No_of_seats) from Cancellation;

Display the number of days in a week on which the 9W01 bus


is available.

Creating and dropping Views

a) CREATE VIEW

Create view male_passengers as select PNR_NO,age from Passenger where sex='m';


Select * from male_passenger;

b) Create a view from two tables with all columns.

Create view pass_reserve as select * from Passenger full natural join Reservation;

c) INSERT

Insert into male_passengers values (20, 40);

d) DROP VIEW

Drop view male_pass;


8.Triggers

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

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

i) 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$$
i)UPDATE :

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

SNo Source Changedon Action


1 Banglore 2014:03:23 12:51:00 Insert
2 Kerela 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete
ii) 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)$$

SNo Source Changedon Action


1 Banglore 2014:03:23 12:51:00 Insert
2 Kerela 2014:03:25:12:56:00 Update
3 Mumbai 2014:04:26:12:59:02 Delete
iii)

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’$$

SNo Source Changedon Action


1 Banglore 2014:03:23 12:51:00 Insert
2 Kerela 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-Vice:

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 is 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?


9.Procedures

Aim: Creation of stored Procedures and Execution of Procedures and Modification of


Procedures.

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

Ex1:

CREATE PROCEDURE BUS_PROC1()

BEGIN

SELECT * FROM BUS;

END$$

CALL BUS_PROC1()$$

BusNo Source Destination CoachType


AP123 Hyderabad Banglore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper
Ex2:

CREATE PROCEDURE SAMPLE2()

BEGIN

DECLARE X INT(3);

SET X=10;

SELECT X;

END$$

CALL SAMPLE2()$$

BusNo Source Destination CoachType


AP123 Hyderabad Banglore Volvo
AP234 Mumbai Hyderabad Semi-Sleeper
Ex3: 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.
10.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.

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.
Synatx : 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 record 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 cursor attributes?
Additional Experiments:

1.Create and manipulate various DB objects for a table.

 CREATION OF DATABASE OBJECTS


 ALTERATION OF DATABASE OBJECTS
 DROPPING DATABASE OBJECTS

A) AIM: To create the following relations using appropriate SQL statements:

Create table for various relation

DEPT (DEPTNO: NUMBER(2), DNAME: VARCHAR2(10), LOC: VARCHAR2(8))


EMP(EMPNO:NUMBER(4), ENAME: VARCHAR2(9),JOB:
VARCHAR2(9),MGR:NUMBER(4),
HIREDATE:DATE,SAL:NUMBER(7,2),COMM.:NUMBER(7,2),DEPTNO:NUMBER(2))
SALGRADE (GRADE:NUMBER(1),LOSAL:NUMBER(4),HISAL:NUMBER(4))
 Define a constraint on EMP relation that will ensure that every employee earns atmost Rs.10000/-
 Define constraint on EMP relation such that deptno will be foreign key to DEPT relation
 Define dept’s relation so that every department is guaranteed to have some name.

SQL>CREATE TABLE DEPT (DEPTNO NUMBER (2) PRIMARY KEY, DNAME VARCHAR2 (10) NOT
NULL, LOC VARCHAR2 (8));
Table created.
SQL>CREATE TABLE EMP(EMPNO NUMBER(4) PRIMARY KEY,ENAME VARCHAR2(9),JOB
VARCHAR2(9),MGR NUMBER(4),HIREDATE DATE,SAL NUMBER(7,2) CHECK(SAL<=10000),COMM
NUMBER(7,2),DEPTNO NUMBER(2) ,FOREIGN KEY(DEPTNO) REFERENCES DEPT);
Table created
SQL>CREATE TABLE SALGRADE (GRADE NUMBER (1), LOSAL NUMBER (4), HISAL NUMBER (4));
Table created.
To insert the following data into appropriate relations:

MULTI ROW INSERTIONS


1) SQL> INSERT INTO DEPT (DEPTNO, DNAME, LOC) VALUES(&DEPTNO,'&DNAME','&LOC');
Enter value for deptno: 10
Enter value for dname: ACCOUNTING
Enter value for loc: NEWYORK
old 1: INSERT INTO DEPT VALUES(&DEPTNO,'&DNAME','&LOC')
new 1: INSERT INTO DEPT VALUES(10,'ACCOUNTING','NEWYORK')
1 row created.
2) SQL> INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)

VALUES(&EMPNO,’&ENAME’,’&JOB’,&MGR,’&HIREDATE’,&SAL,&COMM,&DEPTNO);
Enter value for empno: 7499
Enter value for ename: ALLEN
Enter value for job: SALESMAN
Enter value for mgr: 7698
Enter value for hiredate: 20-FEB-81
Enter value for sal: 1600
Enter value for comm: 300
Enter value for deptno: 30
old 1: INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
new 1: INSERT INTO EMP(7499,’ALLEN’,’SALESMAN’,7698,’20-FEB-
81’,1600,300,30) 1 row created.
3) SQL> INSERT INTO SALGRADE (GRADE,LOSAL,HISAL)
VALUES(&GRADE,&LOSAL,&HISAL);
Enter value for grade: 5
Enter value for losal: 3001
Enter value for hisal: 9999
old 1: INSERT INTO SALGRADE (GRADE,LOSAL,HISAL)
VALUES(&GRADE,&LOSAL,&HISAL)
new 1: INSERT INTO SALGRADE (GRADE,LOSAL,HISAL)
VALUES(5,3001,9999)
1 row created.
SINGLE ROW INSERTIONS
SQL> INSERT INTO DEPT(DEPTNO,DNAME,LOC) VALUES(20,'RESEARCH','DALLAS')
1 row created.
SQL> INSERT INTO EMP(EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO)
VALUES(7521,’WARD’,’SALESMAN’,7698,’22-FEB-81’,1250,500,30);
1 row created.
SQL> INSERT INTO SALGRADE (GRADE,LOSAL,HISAL) VALUES(4,2001,3000);
1 row created.
b) AIM: To Alter the tables using appropriate SQL statements:
1) Alter the size of dname of DEPT table
SQL> ALTER TABLE DEPT MODIFY (DNAME VARCHAR2 (20));
Table altered.
2) Alter the SALGRADE table by adding constraint unique to the field grade
SQL> ALTER TABLE SALGRADE ADD CONSTRAINT CONS_GRADE UNIQUE (GRADE);
Table altered.
3) Alter the SALGRADE table by dropping constraint unique to the field grade
SQL> ALTER TABLE SALGRADE DROP CONSTRAINT CONS_GRADE;
Table altered.
c)AIM: Dropping the tables using appropriate SQL statements
1) Drop the EMP table
SQL> DROP TABLE EMP;
Table dropped.
2) Drop the DEPT table
SQL> DROP TABLE DEPT;
Table dropped.
2)Execute a single line and group functions for a table.

 AGGREGATE FUNCTIONS
 STRING FUNCTIONS
 NUMBER FUNCTIONS
 DATE FUNCTIONS
 CONVERSION FUNCTIONS

a)AIM: Queries using aggregate functions(COUNT,SUM,AVG,MIN,MAX) GROUP


BY,HAVING .
1) Find the number of rows in the EMP table.
SQL> SELECT COUNT(*) FROM EMP;
COUNT(*)
----------
14
2) List the numbers of jobs.
SQL> SELECT COUNT(DISTINCT(JOB)) AS TOTALJOBS FROM EMP;
TOTALJOBS
----------
5
3) Find total salary of the EMP table
SQL> SELECT SUM(SAL) AS TOTALSALARY FROM EMP;
TOTALSALARY
-----------
29025
4) List maximum sal, minimum sal, average sal of EMP table
SQL> SELECT MAX(SAL),MIN(SAL),AVG(SAL) FROM EMP;
MAX(SAL) MIN(SAL) AVG(SAL)
---------- ---------- ----------------------
5000 800 2073.21429
5) List the numbers of people and average salary in deptno 30.
SQL> select count(*),avg(sal) from emp where deptno=30;
COUNT(*) AVG(SAL)
-------------- -------------
6 1666.66667
6) List maximum sal and minimum sal in the designations SALESMAN and CLERK.
SQL> SELECT COUNT(*),MAX(SAL),MIN(SAL),AVG(SAL) FROM EMP WHERE JOB
IN('SALESMAN','CLERK');
COUNT(*) MAX(SAL) MIN(SAL) AVG(SAL)
---------- ---------- ---------- ----------------------------
8 1600 800 1218.75
7) ) Calculate total salary bill for each department.
SQL>SELECT DEPTNO,SUM(SAL) AS TOTALSAL FROM EMP GROUP BY DEPTNO;
DEPTNO TOTALSAL
------------------- ----------
10 8750
20 10875
30 9400
8) List max sal, min sal and average sal of depts. 10,30.
SQL> SELECT DEPTNO,MIN(SAL),MAX(SAL),AVG(SAL) FROM EMP WHERE DEPTNO IN(10,30) GROUP
BY DEPTNO;
DEPTNO MIN(SAL) MAX(SAL) AVG(SAL)
------- ---------- ---------- ---------------------------
10 1300 5000 2916.66667
30 950 2850 1566.66667
9) Find all departments which having more than 3 employees.
SQL> SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO HAVING COUNT(*)>3;
DEPTNO COUNT(*)
---------- ----------
20 5
30 6
10) Display the jobs where the minimum salary is greater than or equal to 3000.
SQL> SELECT JOB,MIN(SAL) FROM EMP GROUP BY JOB HAVING MIN(SAL)>=3000;
JOB MIN(SAL)
--------- ----------
ANALYST 3000
PRESIDENT 5000

b) AIM: Queries using string functions


(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and instr)
1) Display the output for all departments in the following manner:
Department number 10 with name Accounting is situated in New York.
SQL> SELECT 'Department number '||DEPTNO||' with name '||INITCAP(DNAME)||' is situated in
'||INITCAP(LOC) AS CONCATENATEDSTRING FROM DEPT;
CONCATENATEDSTRING
-----------------------------------------------------------------------------------------------
Department number 10 with name Accounting is situated in New York
Department number 20 with name Research is situated in Dallas
Department number 30 with name Sales is situated in Chicago
Department number 40 with name Operations is situated in Boston

2) Display ‘*”s before the employee name.


SELECT LPAD (ENAME, 9,’*’) FROM EMP;
LPAD (ENAM
---------
****SMITH
****ALLEN
*****WARD
****JONES
14 rows selected.

3) Display ‘*”s after the employee name.


SELECT RPAD (ENAME, 9,’*’) FROM EMP;
RPAD (ENAM
---------
SMITH****
ALLEN****
FORD*****
MILLER***
14 rows selected.

4) Left trim of character ‘s’ from employee names of department number 20.
SQL> SELECT LTRIM(ENAME,'S') FROM EMP WHERE DEPTNO=20;
LTRIM(ENAM
------------------
MITH
JONES

5) Righttrim of character ‘s’ from employee names of department number 20.


SQL> SELECT RTRIM(ENAME,'S') FROM EMP WHERE DEPTNO=20;
RTRIM(ENAM
----------
SMITH
JONE
SCOTT
ADAM

6) List employee names with all capital letters, with all small letters and with first letter
only as capital of department number 10.
SQL>SELECT ENAME,UPPER(ENAME),LOWER(ENAME),INITCAP(ENAME) FROM
EMP WHERE DEPTNO=10;
ENAME UPPER(ENAM) LOWER(ENAM INITCAP(EN
---------- ---------- ---------- ------------------ --------------------
CLARK CLARK clark Clark
KING KING king King
MILLER MILLER miller Miller

7) List employee names with length of the name sorted on length for department number
30.
SQL>SELECT ENAME, LENGTH (ENAME) FROM EMP WHERE DEPTNO=30 ORDER BY
LENGTH(ENAME);
ENAME LENGTH(ENAME)
---------- -------------------------
WARD 4
ALLEN 5
BLAKE 5
JAMES 5
MARTIN 6
TURNER 6
6 rows selected.

8) Display the first 4 letters of job of EMP table.


SQL> SELECT DISTINCT(SUBSTR(JOB,1,4)) AS JOB FROM EMP;
JOB
----
CLER
SALE
MANA
ANAL
PRES
5 rows selected.

9) Display ename and return the position of character ‘S’ in ename.


SQL>SELECT ENAME,INSTR(ENAME,'S') FROM EMP WHERE DEPTNO=20;
ENAME INSTR(ENAME,'S')
---------- ----------------
SMITH 1
JONES 5
SCOTT 1

C) AIM: Queries using string functions


(To_number, LEAST, GREATEST, TRUNC)
1) Find the least value of the following series:
9,3,56,89,23,1,0,-2,12,34,9,22
SQL> SELECT LEAST(9,3,56,89,23,1,0,-2,12,34,9,22) AS LOWEST FROM DUAL;
LOWEST
----------
-2
2) Find the greatest value of the following series:
9,3,56,89,23,1,0,-2,12,34,9,22
SQL> SELECT GREATEST(9,3,56,89,23,1,0,-2,12,34,9,22) AS HIGHEST FROM DUAL;
HIGHEST
------------
89
3)Trunk of the number 567.231656 by 3.
SQL> SELECT TRUNC(567.231656,3) FROM DUAL;
TRUNC(567.231656,3)

4)Add ‘100.00’ to the salary of every employee in EMP table


SQL>SELECT ENAME,SAL+TO_NUMBER('100.00') AS SALARY FROM EMP;
ENAME SALARY
---------- ----------
SMITH 900
ALLEN 1700
WARD 1350

d) AIM: Queries using date functions


(Sysdate,next_day,add_months,last_day,months_between,
least,greatest,trunk,round,to_char,to_date)
1)List employee names having an experience more than 24 years.
SQL> SELECT ENAME,ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12) EXP FROM EMP
WHERE ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12)>24;
ENAME EXP
---------- ----------
SMITH 28
ALLEN 28
WARD 28

2)Find the first ‘SUN’day of employees after join in the organization of EMP table.
SQL>SELECT NEXT_DAY (HIREDATE,'SUN') AS HOLIDAY FROM EMP;
HIREDATE HOLIDAY
-------------- ---------------
17-DEC-80 21-DEC-80
20-FEB-81 22-FEB-81
22-FEB-81 01-MAR-81
02-APR-81 05-APR-81

3)Display hiredate and reviewdate from EMP table, consider reviewdate


As 1year from the hiredate for the deptno ‘20’.
SQL> SELECT HIREDATE,ADD_MONTHS(HIREDATE,12) AS REVIEWDATE FROM EMP WHERE
DEPTNO=20;
HIREDATE REVIEWDAT
------------- ---------------
17-DEC-80 17-DEC-81
02-APR-81 02-APR-82

4)Display last day of joining month of employees of deptno ‘10’ from EMP table.
SQL> SELECT HIREDATE,LAST_DAY(HIREDATE) AS LASTDAY FROM EMP WHERE DEPTNO=10;
HIREDATE LASTDAY
------------- -------------
09-JUN-81 30-JUN-81
17-NOV-81 30-NOV-81
23-JAN-82 31-JAN-82

e) AIM: Queries using conversion functions (to_char,to_number,to_date)


1) Display the names and hire dates of the employees of deptno 20. Format hire date as
‘12/03/84’.
SQL>SELECT ENAME, TO_CHAR (HIREDATE,’DD/MM/YY’) AS HIREDATE FROM EMP WHERE
DEPTNO=20;
ENAME HIREDATE
----------------------------
SMITH 17/12/80
JONES 02/04/81
SCOTT 19/04/87
ADAMS 23/05/87
FORD 03/12/81

2) Display empno, employee name, job, salary of the employees. Show the salary with
thousand separators.
SQL>SELECT EMPNO, ENAME,JOB,TO_CHAR(SAL,’$9,999’)AS SALARY FROM EMP;
EMPNO ENAME JOB SALARY
---------- ---------- --------- ----------------
7369 SMITH CLERK $800
7499 ALLEN SALESMAN $1,600

3) List number of employees joined year wise.

SQL> SELECT TO_CHAR(HIREDATE,'YY')AS YY,COUNT(*) FROM EMP GROUP BY


TO_CHAR(HIREDATE,'YY');
YY COUNT(*)
-- ----------------
80 1
81 10
82 1
87 2

4) List employees who joined between Apr 81 and Apr 82.


SQL> SELECT ENAME,TO_CHAR(HIREDATE,'MON YY') AS HIREDATE FROM EMP WHERE
TO_DATE(HIREDATE) BETWEEN TO_DATE('01-APR-81') AND
TO_DATE('30-APR-82');

ENAME HIREDATE
---------- ----------------
JONES APR 81
MARTIN SEP 81
3. Create views, partitions and locks for a particular DB.

 Creating views
 Dropping views

1) Create a view that will store employee number ,names, job, salary and department
number of all employees.

CREATE OR REPLACE VIEW EMP1


AS
SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
FROM EMP;
View created.

2) Create a view that will store the information of all employees who are working Dallas.

CREATE OR REPLACE VIEW EMP_DALLAS


AS
SELECT * FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM DEPARTMENTS WHERE LOC = ‘DALLAS’);
View created.

3)Drop the view EMP1 that is created from the EMP table.

SQL> DROP VIEW EMP1;


View dropped.

Creating a list partition and range partition

Creating list partition for employees:

SQL>CREATE TABLE EMPLOYEES (ID NUMBER (10),FIRSTNAME VARCHAR2(20),LASTNAME


VARCHAR2(20),COUNTRY VARCHAR2(30))
PARTITION BY LIST (COUNTRY)
(PARTITION EUROPE VALUES (‘ENGLAND’,’FRANCE’,’ITALY’),
PARTITION AMERICA VALUES (‘AMERICA’),
PARTITION UNKNOWN VALUES (NULL));

Table created.

INSERTING DATA:-

SQL>INSERT INTO EMPLOYEES (ID,FIRSTNAME,LASTNAME,COUNTRY) VALUES


(10,’ANU’,’SREE’,’ENGLAND’);

One row inserted.

SQL>INSERT INTO EMPLOYEES (ID,FIRSTNAME,LASTNAME,COUNTRY) VALUES


(20,’RAJ’,’SMITH’,’FRANCE’);

One row inserted.


SQL>INSERT INTO EMPLOYEES (ID,FIRSTNAME,LASTNAME,COUNTRY) VALUES
(30,’JAMES’,’WARD’,’AMERICA’);

One row inserted.

SQL>INSERT INTO EMPLOYEES (ID,FIRSTNAME,LASTNAME,COUNTRY) VALUES


(40,’BLAKE’,’SCOTT’,’ENGLAND’);

One row inserted.

SQL>SELECT * FROM EMPLOYEES;

ID FIRSTNAME LASTNAME COUNTRY


---------- -------------------- ------------------ ---------------
10 ANU SREE ENGLAND
20 RAJ SMITH FRANCE
30 JAMES WARD AMERICA
40 BLAKE SCOTT ENGLAND

4 rows selected.

Sql>select * from employees partition(‘America’);

ID FIRSTNAME LASTNAME COUNTRY


---------- -------------------- ------------------ ---------------
30 JAMES WARD AMERICA

1 row selected.

Altering the partition:

SQL>ALTER TABLE EMPLOYEES ADD PARTITION SCOTTLAND VALUES(‘ATLANTA’,’CALIFONIA’);

TABLE ALTERED.

DROPPING THE PARTITION:

SQL>ALTER TABLE EMPLOYEES DROP PARTITION EUROPE;

TABLE ALTERED

7.Text Books / Reference Books


1. Introduction to SQl, Rick F.Vander Lans,Pearson Education
2. Oracle PL/SQL, B Rosenzweig and E.Silvestrova, Pearson Education
3. SQL & PL/SQL for Oracle 10g, Black Book, Dr P.S.Deshpande,Dream Tech.
4. Oracle Database 11g PL/SQL Programming,M,Mc.Laughlin,TMH
5. SQL Fundamentals,JJ.Patrick,Pearson Education

You might also like