ex4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

DBMS LAB MANUAL

II Year CSE- Semester II


DEPARTMENT OF INFORMATION TECHNOLOGY
ACADEMIC YEAR 2022-23
DEPARTMENT OF
INFORMATION TECHNOLOGY
LAB MANUAL

Branch:CSE Class: B.Tech- II Year-I sem


Subject: Database Management SystemS Lab Code: R20CSE22L2
Academic Year: 2022-23 Regulation: R20
Core/Elective/H&S: Core Credits:1.5

Prepared By
Name:

Verified By
Head of the Department:
DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL- INDEX


S. No Contents
1 Vision, Mission, PEOs, POs, PSOs & COs
2 Syllabus
3 Institution Academic Calendar
4 Lab Structure
5 Time Table
6 Index
7 Programs
8 Viva Questions
9 Additional Programs
SRI INDU COLLEGE OF ENGINEERING & TECHNOLOGY
B. TECH –INFORMATION TECHNOLOGY

INSTITUTION VISION
To be a premier Institution in Engineering & Technology and Management with competency,
values and social consciousness.

INSTITUTION MISSION

IM1 Provide high quality academic programs, training activities and research facilities.

IM2 Promote Continuous Industry-Institute Interaction for Employability, Entrepreneurship,


Leadership and Research aptitude among stakeholders.

IM3 Contribute to the Economical and technological development of the region, state and nation.

DEPARTMENT VISION
To be a recognized knowledge center in the field of Information Technology with self -
motivated, employable engineers to society.

DEPARTMENT MISSION
The Department has following Missions:
DM1 To offer high quality student centric education in Information Technology.

DM2 To provide a conductive environment towards innovation and skills.


DM3 To involve in activities that provide social and professional solutions.
DM4 To impart training on emerging technologies namely cloud computing and IOT with involvement
of stake holders.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


PEO 1: Higher Studies: Graduates with an ability to apply knowledge of Basic sciences and
programming skills in their career and higher education.
PEO 2: Lifelong Learning: Graduates with an ability to adopt new technologies for ever changing
IT industry needs through Self-Study, Critical thinking and Problem solving skills.
PEO 3: Professional skills: Graduates will be ready to work in projects related to complex
problems involving multi-disciplinary projects with effective analytical skills.
PEO 4: Engineering Citizenship: Graduates with an ability to communicate well and exhibit
social, technical and ethical responsibility in process or product.
PROGRAM OUTCOMES (POs) & PROGRAM SPECIFIC OUTCOMES (PSOs)

PO Description

PO 1 Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
Problem Analysis: Identify, formulate, review research literature, and analyze complex engineering
PO 2
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
Design / development of Solutions: Design solutions for complex engineering problems and design system
PO 3 components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and research methods including
PO 4 design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering and IT
PO 5
tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
The engineer and Society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
PO 6 legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO 7
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development.

PO 8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice
PO 9 Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
PO 10 community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering and
PO 11 management principles and apply these to one’s own work, as a member and leader in a team, to manage projects
and in multidisciplinary environments.
PO 12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological Change.
Program Specific Outcomes

Software Development: To apply the knowledge of Software Engineering, Data Communication, Web Technology
PSO 1
and Operating Systems for building IOT and Cloud Computing applications.
PSO 2 Industrial Skills Ability: Design, develop and test software systems for world-wide network of computers to
provide solutions to real world problems.
PSO 3 Project implementation: Analyze and recommend the appropriate IT Infrastructure required for the implementation
of a project.
DEPARTMENT OF INFORMATION TECHNOLOGY

COURSE OUTCOMES (CO’S)

COURSE NAME: Database Management System

Course Name Course outcomes

C22L2.1 Design database schema for a given application and apply normalization.
C22L2.2 1. Acquires skills in using SQL commands for data definition and data
manipulation.
C22L2.3 Develop solutions for database applications using procedures, cursors and
triggers.

COURSE ARTICULATION MATRIX

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3

C22L2.1 3 3 3 2 - 2 - - 2 - - 2 2 3 -

C22L2..2 3 2 2 - - - - - - - - 2 2 2 -

C22L2.3 3 3 2 2 - - - - - - - 2 2 2 1

C22L2 3 2.6 2.3 2 - 0.6 - - 0.6 - - 2 2 2.3 0.3


Database Management Systems
Experiment 5: Practicing DML commands
DML commands are used for managing data within schema objects. Some examples:

 SELECT-retrieve data from the database


 INSERT-insert data in to a table
 UPDATE-updates existing data within a table
 DELETE-deletes all records from a table, the space for the records remain

Insert values into "Bus" table:

insert into Bus values (1234, 'hyderabad', 'tirupathi');insert into Bus values(2345, 'hyderabad', 'banglore');insert into

Bus values(23, 'hyderabad','kolkata');insert into Bus values(45, 'tirupathi','bangalore');

insert values into "Passenger" table:


Insert into Passenger values (1,45,'ramesh',45,'M','abc123');

insert into Passenger values(2, 78, 'geetha', 36, 'F', 'abc124');

insert into Passenger values(45, 90,'ram', 30,'M', 'abc12');

insert into Passenger values(67,89,'ravi',50,'M','abc14');

insert into Passenger values(56,22,'seetha',32,'F','abc55');

Few more Examples of DML commands:


SELECT*FROM Bus; (selects all the attributes and displays) UPDATE Bus SET
Bus_No=1WHEREBus_No= 2;

Experiment 6: Querying (using ANY, ALL, IN, EXISTS, NOTEXIST, UNION, INTERSECT, Constraints etc.
In this week you are going to practice queries (along with sub queries) using ANY, ALL, IN, EXISTS,
NOTEXIST, UNION, INTERSECT, Constraints etc.
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. Findthenamesofpassengerswhoseageisbetween30 and 45.
6. Display all the passengers names beginning with 'A'
7. Display the sorted list of passenger’s names
Experiment 10: Usage of Cursors

In this week you need to do the following: Declare a cursor that defines a result set.
Open the cursor to establish the result set. Fetch the data into local variables as needed from the cursor, one
row at a time. Close the cursor when done
CREATE PROCEDURE myproc(in_customer_idINT) BEGIN
DECLARE v_id INT;
DECLARE v_name VARCHAR(30);
DECLARE c1 CURSOR FOR
SELECT stdid, stdFirstname FROM students WHERE stdid-in_customer_id;
OPENc1;
FETCHc1INTOv_id,v_name; CLOSE c1;
END;

Tables:
BUS
BusNo: VARCAHR : PK (primarykey)
Source: VARCHAR
Destination: VARCHAR
Passenger
PPNO: VARCHAR(15) : PK Name:
VARCHAR(15)
Age: INT(4)
Sex:CHAR(10) : Male/Female
Address: VARCHAR(20)
Passenger_Tickets
PPNO:VARCHAR(15): PK
Ticket_No:NUMERIC(9)
Reservation
PNR_No: NUMERIC(9) : FK
Journey_date: DATETIME(8)
No_of_seats: INT(8) Address:
VARCHRA(50)
Contact_No: NUMERIC(9)-->Should not less than 9 and Should not accept any other character other than
interger
STATUS:CHAR(2): Yes/No
Cancellation
PNR_No: NUMERIC(9):FK
Journey_date: DATETIME(8)
No_of_seats : INT(8) Address:
VARCHRA(50)
Contact_No:NUMERIC(9)-->Should not less than 9 and Should not accept any other character other than interger
STATUS:CHAR(2):Yes/No
Lab Structure
1.DIMENSIONS OF THE LAB
Area of the lab in Sqmts : Sqm
2. CAPACITY OF THE LAB :
3. EQUIPMENTS
Computer Systems (Clients) :
CPU :
Monitors :
Key Board :
Mouse :
4. SYSTEM CONFIGURATION : DELLE1916HV
Speed : 3.10 GHz, 2GB RAM
Hard Disk : 500 GB
HCL LED Monitor Size : 18.5
5. SOFTWARE : Turbo C++, MYSQL, Eclipse, Windows
OS,Open Office
6. AMBIENCE
Printers : 00
Projector : 01
Computer Tables :
Student Chairs :
Charts :
Photo Frames :
Switch/Hub :
White Boards :
A/C s :
Power Backup : UPS
TIME TABLE

Sri Indu College of Engineering &Technology


(An Autonomous Institution under UGC)
Sheriguda (V), Ibrahimpatnam (M), Ranga Reddy (Dist) – 501 510

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB Time - Table


Class: II-II SEM w.e.f:

12:40
Time 9:40-10:40 10:40-11:40 11:40-12:40
To
1:20-2:15 2:15-3:10 3:10-4:00

1 2 3 1:20 4 5 6
Days
Monday L
Tuesday U
Wednesday N
Thursday C
Friday H
Saturday
GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), thosewho come after 5 minutes will not be allowed into the lab.

2. Plan your task properly much before to the commencement, come prepared to the lab with 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 system
allotted toyou by the faculty.

5. Execute your task in the laboratory, and record the results / output in the lab
observation notebook, and get certified by the concerned faculty.

6. All the students should be polite and cooperative with the laboratory staff, must
maintain thediscipline and decency in the laboratory.

7. Computer labs are established with sophisticated and high end branded systems, which
should beutilized properly.

8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., 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 hours will 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.

Head of the Department Principal


INDEX
Pageno No. of proposed co
S.no Topic sections date of
handling
1-5 3 2
1. Concept Design with E-R Model
6-10 3 2
2. Relational Model
11-12 3 1
3. Normalization
13-15 3 2
4. Practicing DDL Commands
16-21 3 2
5. Practicing DML Commands
22-31 3 2
Querying using ANY, ALL, IN, EXISTS,
6. UNION, INTERSECT,CONSTRAINS etc.
32-36 3 2
7. Querying using Aggregate functions, GROUP
BY & HAVING and Creation and Dropping of
Views.
37-41 3 3
8. TRIGGERS USING Insert, Delete & Update.
42-43 3 3
9. Procedures.
44-46 3 3
10. Usage Cursors

11. Additional Programs 47-56 3


EXPERIMENT- 1
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.

E-R Model

Bus
 BusNo
 Source
 Destination
 CoachType

SCHEMA

Bus: Bus(BusNo :String ,Source : String, Destination: String, Coach Type: String)

Ticket
 TicketNo
 DOJ
 Address
 ContactNo
 BusNo

[1]
 SeatNo
 Source
 Destination

SCHEMA

Ticket (TicketNo: string, DOJ: date, Address: string, ContactNo : string, BusNo:String
SeatNo : Integer, Source: String, Destination: String)

Passenger
 PassportID
 TicketNo
 Name
 ContactNo
 Age
 Sex
 Address

SCHEMA

Passenger (PassportID: String, TicketNo :string, Name: String, ContactNo: string, Age:
integer, Sex: character, Address: String)
[2]
Reservation
 PNRNo
 DOJ
 No_of_seats
 Address
 ContactNo
 BusNo
 SeatNo

SCHEMA
Reservation(PNRNo: String, DOJ: Date, NoofSeats: integer , Address: String ,ContactNo: String, ,
BusNo: String,SeatNo:Integer)

[3]
Cancellation
 PNRNo
 DOJ
 SeatNo
 ContactNo
 Status

SCHEMA

Cancellation (PNRNo: String, DOJ: Date, SeatNo: integer, ContactNo: String, Status:
String)

[4]
CONCEPT DESIGN WITH E-R MODEL

[5]
Viva Questions:

1.Define DBMS?
2. Define the terms i) Entity ii) Entity set iii) weak entity set iv) strong entity set?
3.What is ER-diagram?
4.What are the different types of entities?
5. List various types of attributes?

[6]
EXPERIMENT – 2
RELATIONAL MODEL

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

1. Bus: Bus(BusNo: String, Source: String, Destination: String, CoachType: String)

ColumnName Datatype Constraints Type of Attributes

BusNo Varchar(10) Primary Single-value


key
Source Varchar(20) Single-value
Destination Varchar(20) Simple
CoachType Varchar(10) Simple

Mysql>create table Bus(BusNo varchar(10),source varchar(20),Destination varchar(20),coachType


varchar(10),primary key(BusNo));

Mysql>desc Bus;

Ticket:

Ticket(TicketNo: string, DOJ: date, Address:string,ContactNo: string, BusNo:String, SeatNo :Integer, Source: String,
Destination: String)

[7]
ColumnName Datatype Constraints Type of Attributes
TicketNo Varchar(20) 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

Mysql> create table ticket(ticketno varchar(20), doj date,address varchar(20),contactno int, busno
varchar(20),seatno int,source varchar(10),destination varchar(10),primary key(ticketno,busno) foreign key(busno)
references bus(busno);

Mysql>desc Ticket;

Passenger:

Passenger(PassportID: String, TicketNo:string,Name: String, ContactNo:string,Age: integer, Sex: character,


Address: String);

Type of
ColumnName Datatype Constraints
Attributes
PassportID Varchar(15) Primary Key Single-valued
TicketNo Varchar(20) Foreign Key Single-valued
[8]
Name Varchar(20) Composite
ContactNo Varchar(20) Multi-valued
Age Integer Single-valued
Sex character Simple
Address Varchar(20) Composite

Mysql> Create table passenger(passportID varchar(15) ,TicketNo varchar(15),Name varchar(15),ContactNo


varchar(20),Age integer, sex char(2),address varchar(20), primary key(passportID,TicketNo),foreign
key(TicketNo) references Ticket(TicketNo));

Mysql> desc passenger;

Reservation:

Reservation(PNRNo: String, DOJ: Date, NoofSeats: integer , Address: String ,ContactNo:


String, , BusNo: String,SeatNo:Integer)

ColumnName Datatype Constraints Type of Attributes


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

[9]
BusNo Varchar(10) Foreign Single-valued
Key
SeatNo Integer Simple
Mysql> Create table Resevation(PNRNo varchar(20),DOJ date,NoofSeates integer,Address varchar(20),ContactNo
varchar(20),BusNo varchar(20),SeatNo integer, primary key(PNRNo,BusNo),foreign key(BusNo) references
Bus(BusNo));

Mysql> desc reservation;

Cancellation:

Cancellation (PNRNo: String,DOJ: Date, SeatNo: integer,ContactNo: String,Status:


String)

ColumnName Datatype Constraints Type of Attributes


PNRNo Varchar(10) Primary Key Single-valued
DOJ date Single-valued
SeatNo Integer Simple
ContactNo Varchar(15) Multi-valued
Status Varchar(10) Simple

Mysql> create table cancellation(PNRNo varchar(10),DOJ date,SeatNo integer, ContactNo


varchar(15),Status varchar(10), primary key(PNRNo), foreign key(PNRNo) references
reservation(PNRNo));

Mysql> desc cancellation;


[10]
Viva Questions:

1What is relation schema and a relation?

2.What is Relation and Relationship?

3.Define Instance and Schema?

4.What is the difference between ER and Relational Model?

5.What is the degree of relation?

[11]
EXPERIMENT – 3
NORMALIZATION

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

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.

The given FD is a trival

P is a super key.

[12]
Normalized tables are:-

Mysql> create table Bus2(BusNo varchar(20) primary key,Source varchar(20),Destination varchar(20));

Mysql>Create table passenger4(PPN varchar(15) Primary key,Name varchar(20),Age integer,Sex char,Address


varchar(20));

Mysql> Create table PassengerTicket(PPN varchar(15) Primary key,TicketNo integer);

Mysql> Create table Reservation2(PNRNO integer Primary key, JourneyDate DateTime,NoofSeats int,Address
varchar(20),ContactNo Integer);

Mysql> create table Cancellation2(PNRNO Integer primary key,JourneyDate DateTime,NoofSeats


Integer,Address varchar(20),ContactNo Integer,foreign key(PNRNO) references Reservation2(PNRNO));

Mysql> Create table Ticket2(TicketNo Integer Primary key,JourneyDate DateTime, Age Int(4),Sex char(2),Source
varchar(20),Destination varchar(20),DeptTime varchar(2));

Viva Questions:

1.Define Redundancy?
2.What is decomposition?
3.What is Normalization?
4.What is fully functional dependency?
5.List the different types of Normal forms?

[13]
EXPERIMENT – 4
PRACTICING DDL COMMANDS

AIM : Creating Tables and altering the Tables

Mysql>Create table passenger2(passportId Integer Primary Key, Name varchar(10)


NotNull, Age Integer Not Null, Sex char, Address varchar(20) Not Null);

Mysql> desc passenger2;

USING ALTER COMMAND

Adding Extra column to Existing Table

Mysql>Alter table passenger3 add column TicketNo varchar(10);

[14]
Mysql>Alter Table passenger3 add Foreign key(TicketNo) references Ticket(TicketNo);

Mysql>Alter Table passenger3 Modify column Name varchar(20);

[15]
Mysql>Alter table passenger drop foreign key fk1;

Mysql> Alter table passenger2 Drop column TicketNo;

Viva Questions:
1.What is DDL?

2.What are the different types of commands used in DDL language?

3.Difference between drop and truncate?

4.What is the use of DDL language in DBMS?

5.Define Database?

[16]
EXPERIMENT – 5
PRACTICING DML COMMANDS

AIM: Create a DML Commands are used to manage data within the scheme objects.

DML Commands:

INSERT COMMAND ON BUS2 & PASSENGER2 RELATIONS

mysql> select * from Bus2; Empty set (0.00 sec)

mysql> insert into Bus2 values(1234,'Hyderabad','Tirupathi');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Bus2 values(2345,'Hyderabad','Banglore');

Query OK, 1 row affected (0.01 sec)

mysql> insert into Bus2 values(23,'Hyderabad','Kolkata');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Bus2 values(45,'Tirupathi','Banglore');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Bus2 values(34,'Hyderabad','Chennai');

Query OK, 1 row affected (0.03 sec)

[17]
mysql> select * from Bus2;

[18]
mysql> select * from Passenger2;

Empty set (0.00 sec)

mysql> insert into Passenger2 values(145,'Ramesh',45,'M','abc123');

Query OK, 1 row affected (0.05 sec)

mysql> insert into Passenger2 values(278,'Geetha',36,'F','abc124');

Query OK, 1 row affected (0.02 sec)

mysql> insert into Passenger2 values(4590,'Ram',30,'M','abc12');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Passenger2 values(6789,'Ravi',50,'M','abc14');

Query OK, 1 row affected (0.03 sec)

mysql> insert into Passenger2 values(5622,'Seetha',32,'F','abc55');

Query OK, 1 row affected (0.03 sec)

mysql> select * from Passenger2;

[19]
UPDATE COMMAND ON BUS2 RELATION

UPDATE Selected Rows & Multiple Rows

mysql> Update Bus2 SET Source='Secundrabad' where BusNo=1234; Query OK, 1 row affected (0.05 sec)

Rows matched: 1 Changed: 1 Warnings: 0

[20]
DELETE COMMAND ON BUS2 RELATION

DELETES Selected Rows and Multiple Rows

mysql> Delete from Bus2 where BusNo=1234; Query OK, 1 row affected (0.05 sec)

mysql> select * from Bus2;

[21]
mysql> Delete from Bus2 where Source=’Secundrabad’; Query OK, 1 row affected (0.05 sec)

mysql> select * from Bus2;

Viva Questions:

1.What is DML?
2.What is the use of DML in DBMS?
3.What are the DML Commands?
4.What is the use of Alter command in DBMS?
5.Define view?

[22]
EXPERIMENT – 6
Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT, Constraints etc.)

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

[23]
mysql> insert into passenger2 values(82302,'Smith',23,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82303,'Neha',23,'F','Hyderabad');

Query OK, 1 row affected (0.01 sec)

mysql> insert into passenger2 values(82304,'Neha',35,'F','Hyderabad');

Query OK, 1 row affected (0.03 sec)

mysql> insert into passenger2 values(82306,'Ramu',40,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82308,'Aakash',40,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82402,'Aravind',42,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82403,'Avinash',42,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82502,'Ramesh',23,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)

mysql> insert into passenger2 values(82602,'Rajesh',23,'M','Hyderabad');

Query OK, 1 row affected (0.02 sec)


[24]
RESERVATION2

mysql> insert into reservation2 values(10201,'2012-02-20 10:20:25',05,'HYD',9654 235242);

Query OK, 1 row affected (0.03 sec)

mysql> insert into reservation2 values(10202,'2012-02-22 10:22:25',05,'HYD',9654 232451);

Query OK, 1 row affected (0.02 sec)

mysql> insert into reservation2 values(10203,'2012-03-22 10:30:25',05,'DELHI',96 54587960);

Query OK, 1 row affected (0.01 sec)

mysql> insert into reservation2 values(10204,'2013-03-22 11:30:25',05,'CHENNAI', 9845761254);

Query OK, 1 row affected (0.02 sec)

1. Display unique PNR_NO of all reservation Mysql>Select

DISTINCT PNR_NO from Reservation;

PNR_No
10201
10202
10203
10204

[25]
2. Display all the names of male passengers.

mysql> Select p.name from passenger2 p


where p.passportid IN (select p2.passportid from passenger2 p2
where p2.sex='M');

[26]
[27]
3. Display the ticket numbers and names of all the passengers.

mysql> select t.ticketno,p.name from passengerticket t,passenger2 p where t.passportid = p.passportid;

[28]
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%H’

Name
Rajesh
Ramesh
Ramesh

[29]
5. Find the names of Passengers whose age is between 30 and 45.

MySQL> SELECT Name FROM PASSENGER WHERE AGE BETWEEN 30 AND 45

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

MySQL> SELECT * FROM PASSENGER WHERE NAME LIKE ‘A%’;

Name
Akash
Arivind
Avinash

[31]
7. Display the sorted list of Passengers names

MySQL> SELECT NAME FROM PASSENGER ORDER BY NAME;

Viva Questions:

1.What are the Different types of set operators?


2.What are the aggregate operators?
3.What is the difference between ANY and OR operators?
4.What is NULL Values?
5.What is the use of EXISTS operator?

[32]
EXPERIMENT – 7
Querying Aggregate Functions (GROUP BY, HAVING and 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.

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

MYSQL> CREATE TABLE CANCELLATION2(PNRNO INT PRIMARY KEY,JOURNEYDATE DATETIME,


NOOFSEATS INT,ADDRESS VARCHAR(20),CONTACTNO INT,STATUS VARCHAR(10),FOREIGN
KEY(PNRNO) REFERENCES RESERVATION2(PNRNO));

mysql> INSERT INTO CANCELLATION2 VALUES(10201,'2012-02-20


10:20:25',2,'HYD',9654235242,'CONFIRM');

mysql> INSERT INTO CANCELLATION2 VALUES(10202,'2012-02-22


10:22:25',2,'HYD',9654232451,'CONFIRM');

mysql> INSERT INTO CANCELLATION2 VALUES(10203,'2012-03-22


10:30:25',2,'DELHI',9654587960,'CONFIRM');

[33]
MySQL> SELECT * FROM RESERVATION UNION

SELECT * FROM CANCELLATION;

2. Display the Minimum age of the Passenger

MySQL> SELECT MIN(AGE) as MINAGE FROM PASSENGER;

[34]
3. Find number of tickets booked for each PNR_No using GROUP BY CLAUSE

MySQL> SELECT PNRNO,SUM(No_of_SEATS) AS SUM_OF_SEATS FROM


RESERVATION2 GROUP BY PNRNO;

4 Find the distinct PNR Numbers that are present.

MySQL> SELECT DISTINCT PNR_NO FROM RESERVATION2;

[35]
5 Mysql> select sum(Noofseats) from Cancellation2;

6 Find the total number of cancelled seats.

MySQL> select sum(noofseats) as canceled_seats from cancellation2;

[36]
Creation and Droping of Views

mysql> create table students(sid int primary key,name varchar(15),login varchar(15), age
int,gpa real); mysql> create table Enrolled(sid int,cid int,grade varchar(5),primary
key(sid,cid), foreign key(sid) references students(sid));

mysql>create view BStudents(name,sid,course) AS SELECT

s.name,s.sid,E.cid from students s,enrolled E where s.sid=e.sid AND

E.grade='B';

Syntax: Drop view view name;

Mysql> Drop view Bstudents; Mysql> Drop view Goodstudents;

Viva Questions:

1.What is Nested query?


2.What is the use of Group By Clause?
3.Define Join?List different types of joins?
4.What is difference between left outer join and right outer join?
5.What is Co-related nested query?

[37]
EXPERIMENT-8
Triggers

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

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

[38]
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'$$

[39]
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

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

MYSQL>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

[40]
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

Examples

CREATE TRIGGER updcheck1 BEFORE UPDATE ON passengerticket FOR EACH ROW

BEGIN

IF NEW.TicketNO > 60 THEN

SET New.TicketNo = New.TicketNo; ELSE

SET New.TicketNo = 0; END IF;

END;

[41]
Viva Questions:
1.Define Trigger?
2.What are the types of triggers?
3.What is the advantage of trigger in database
4.Define Active data bases?
5.When we apply trigger?
[42]
Experiment-9
Procedures
Aim: Creation of stored Procedures and Execution of Procedures and Modification of
Procedures.

Ex1:

CREATE PROCEDURE BUS_PROC1() BEGIN

SELECT * FROM BUS;

END$$

CALL BUS_PROC1()$$

Ex2:
CREATE PROCEDURE SAMPLE2() BEGIN
DECLARE X INT(3); SET X=10;
SELECT X;

END$$
Mysql> CALL SAMPLE2()$$

[43]
Ex3: CREATE PROCEDURE SIMPLE_PROC(OUT PARAM1 INT) BEGIN

SELECT COUNT(*) INTO PARAM1 FROM BUS;

END$$

Mysql> CALL SIMPLE_PROC(@a)$$ Mysql> select @a;

[44]
Viva Questions:

1.What do you mean by Procedure?


2.What is stored procedures used in databases?
3.What is stored procedure?
4.What are the advantage of using stored procedure?
5. List different types of keys in dbms?

[45]
EXPERIMENT-10
USAGE 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.

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.

[46]
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 thecursor.

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.

Delimiter $$

Create procedure p1(in_customer_id int) begin


declare v_id int;
declare v_name varchar(20); declare v_finished integer default 0;
declare c1 cursor for select sid,sname from students where sid=in_customer_id; declare
continue handler for NOT FOUND set v_finished=1;
open c1; std:LOOP
fetch c1 into v_id,v_name; if v_finished=1 then
leave std; end if;
select concat(v_id,v_name); end LOOP std;
close c1; end;

[47]
Viva Questions:

1.How Cursor used in Database?

2.How many types of Cursors in My Sql?


3.How to open and close the Cursor?
4.Differentiate Procedure and Cursor?
5.Can you pass a parameter to a Cursor?

[48]
ADDITIONAL PROGRAMMS

EMPLOYEES TABLE

mysql> create table Employees(ssn varchar(15),name varchar(20),lot int,PRIMARY


KEY(ssn)); mysql> insert into Employees values('123-22-3666','Attishoo',48);

mysql> insert into Employees values('321-31-5368','Smiley',22); mysql> insert into


Employees values('131-24-3650','Smethurst',35);

[49]
DEPARTMENT TABLE

mysql> create table Departments(did int,dname varchar(10),budget real, PRIMARY


KEY(did));

mysql> insert into Departments values(05,'CSE',500000);

mysql> insert into Departments values(04,'ECE',400000);

mysql> insert into Departments values(03,'ME',300000);

mysql> insert into Departments values(01,'CE',100000);

[50]
Sailors , Reserves , Boats Tables

Mysql> Create table Sailors(Sid integer PRIMARY KEY,sname varchar(15), rating int,age
real); Mysql>Create table Reserves(Sid int,Bid int,Day Date);

Mysql>Create table Boats(Bid int,Bname varchar(15),Color varchar(15);

[51]
mysql> select S.sname from sailors S, reserves R where S.sid=R.sid AND R.bid=103;

mysql> select sname from sailors s,Reserves R where S.sid=R.sid AND bid=103; mysql>
select R.sid from Boats B,Reserves R where B.bid=R.bid AND B.color='red';

mysql> select S.sname from sailors S,reserves R,Boats B where S.sid=R.sid AND
R.bid=B.bid AND B.color='red';

mysql> select B.color from Sailors S,Reserves R,Boats B where S.sid=R.sid AND
R.bid=B.bid AND S.sname='Lubber';

[52]
mysql> select S.sname,S.rating+1 AS rating from Sailors S,Reserves R1,Reserves R2 where
S.sid=R1.sid AND S.sid=R2.sid AND R1.day=R2.day AND R1.bid<>R2.bid;

mysql> select S1.sname AS name1,S2.sname AS name2 from sailors S1,sailors S2 where


2*S1.rating=S2.rating-1;

[53]
N , INTERSECT , AND EXCEPT

1).Find the names of sailors who have reserved a red or a green boat.

OR

[54]
2). Find the names of sailors who have reserved both a red and a green boat.

SELECT S.SNAME

FROM SAILORS S,RESERVES R,BOATS B

WHERE S.SID=R.SID AND R.BID=B.BID AND B.COLOR='red' INTERSECT

SELECT S2.SNAME

FROM SAILORS S2,RESERVES R2,BOATS B2

WHERE S2.SID=R2.SID AND R2.BID=B2.BID AND B2.COLOR='green';

NESTED QUERIES

1) Find the Names of sailors who have reserved boat 103

2) Find the names of Sailors who have reserved a red Boat

[53]
3) Find the names of Sailors who have NOT reserved a red Boat

Correlated Nested Queries:

1) Find the names of Sailors who have reserved a red Boat

Set Comparison Operators:

1) Find sailors whose rating is better than some sailor called Horatio

[54]
2) Find the sailors with the highest rating.

mysql> SELECT S.sid FORM Sailors WHERE S.rating>=ALL(SELECT S2.rating FROM


Sailors S2);

The GROUP BY and HAVING Clauses:

1) Find the age of the youngest sailor for each rating level.

2) Find the age of the youngest sailor who is eligible to vote for each rating level with at
least two such sailors

[55]
3) For each red boat , find the number of reservations for this boat

4) Find the average age of sailors for each rating level that has at least two sailors

[56]

You might also like