Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

Department of Computer Science & Engineering(AI&ML)

DATABASE MANAGEMENT SYSTEMS LAB (20CS407PC)

Lab Manual for the Academic Year 2021-2022

II B. Tech

CMR Technical Campus

INDEX:
S.No Contents Page No

1 Lab Objective 2

2 Introduction About Lab 3

3 Guidelines to Students 4

List of Week Wise Lab Programs


4 6

5 References 47

1
LAB OBJECTIVE:

The major objective of this lab is to provide a strong formal foundation in database concepts,
technology and practice to the participants to groom them into well-informed database application
developers.
A vast majority of the software applications being built use some kind of a data store mechanism to
permanently store the data generated/used by the software. Database management systems are complex
software systems that provide a wide variety of functionality for users to structure, organize and access data
quickly and efficiently. Database systems have been there since the early 1970’s but have grown in
complexity and size. Relational database management systems use relational algebra as the basis for
representation of data. RDBMS as relational database management systems are the most popular and widely
used DBMS in the market place.

In this lab, you would be exposed to one popular RDBMS. The broad one line objective of the lab is to get
familiar with the functionality and support provided by commercially popular RDBMS and understand how
to use it to meet your data storage and organization requirements.

Detailed objectives of the lab are:

 You learn SQL (Structured Query Language) which would provide functionality to:
o Learn how to create tables which are fundamental storage blocks of data.
o Learn how to place constraints on data that is entered on tables to ensure data integrity.
o Learn how to add, change and remove data from tables.
o Learn how to select a subset of the data you want to see from the collection of tables and
data.
o Learn how to combine table and group multiple rows of data in table.
 You learn PL/SQL which would provide the ability to do iterative programming at database level to:
o Write programming blocks with conditionals, assignments, loops, etc
o Exception Handling.
o Transaction oriented programs
o Stored procedures, functions, packages.
o Cursors which would allow row wise access of data.
o Triggers which would allow you define pre and post actions when something changes in the
database tables.

At the end of the lab, you should be comfortable using any popular RDBMS for data access and
updating and should be comfortable writing PL/SQL programs at database level using Oracle.

2
INTRODUCTION ABOUT LAB

There are 30 systems (Dell) installed in this Lab. Their configurations are as follows :
Processor : DUAL CORE, 3.2G.hz
RAM : 16 GB
Hard Disk : 1TB
Mouse : Optical Mouse

Software
1 All systems are configured in DUAL BOOT mode i.e, Students can boot from Windows XP or Linux
as per their lab requirement.
This is very useful for students because they are familiar with different Operating Systems so
that they can execute their programs in different programming environments.
2 Each student has a separate login for database access
Oracle 9i client version is installed in all systems. On the server, account for each student has been
created.
This is very useful because students can save their work ( scenarios’, pl/sql programs, data
related projects ,etc) in their own accounts. Each student work is safe and secure from other
students.
3 Systems are provided for students in the 1:1 ratio.
4 Software installation: Oracle 9i
5 Systems are assigned numbers and same system is allotted for students when they do the lab.

3
GUIDELINES TO STUDENTS:

1 Equipment in the lab for the use of student community. Students need to maintain a proper decorum
in the computer lab. Students must use the equipment with care. Any damage is caused is punishable.

2 Students are required to carry their observation / programs book with completed exercises while
entering the lab.

3 Students are supposed to occupy the machines allotted to them and are not supposed to talk or make
noise in the lab. The allocation is put up on the lab notice board.

4 Lab can be used in free time / lunch hours by the students who need to use the systems should take
prior permission from the lab in-charge.

5 Lab records need to be submitted on or before date of submission.

6 Students are not supposed to use floppy disks and pen drives

4
20CS407PC: DBMS Lab

L T P C
B.Tech. IV SEM
0 0 3 1.5

Co-requisites:
 Co-requisite of course “Database ManagementSystems”

Course Objectives:

 Introduce ER data model, database design andnormalization


 Learn SQL basics for data definition and datamanipulation

Course Outcomes:

 Designdatabaseschemaforagivenapplicationandapplynormalization
 AcquireskillsinusingSQLcommandsfordatadefinitionanddatamanipulation.
 Developsolutionsfordatabaseapplicationsusingprocedures,cursorsandtriggers

LIST OF EXPERIMENTS:

1. Concept design with E-RModel


2. RelationalModel
3. Normalization
4. PracticingDDLcommands
5. PracticingDMLcommands
6. Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT, Constraintsetc.)
7. QueriesusingAggregatefunctions,GROUPBY,HAVINGandCreationanddroppingof Views.
8. Triggers (Creation of insert trigger, delete trigger, updatetrigger)
9. Procedures
10. Usage ofCursors

TEXT BOOKS:

1. DatabaseManagementSystems,RaghuramaKrishnan,JohannesGehrke,TataMcGraw Hill, 3rdEdition


2. DatabaseSystemConcepts,Silberschatz,Korth,McGrawHill,Vedition.

REFERENCES BOOKS:

1. Database Systems design, Implementation, and Management, Peter Rob & Carlos Coronel
7thEdition.
2. Fundamentals of Database Systems, ElmasriNavrate, PearsonEducation
3. Introduction to Database Systems, C.J. Date, PearsonEducation
4. OracleforProfessionals,TheXTeam,S.ShahandV.Shah,SPD.
5. DatabaseSystemsUsingOracle:ASimplifiedguidetoSQLandPL/SQL,Shah,PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student Edition.
5
List of Week Wise - Programs

Week 1 Analyze the problem carefully and come up with entities in it. Identify what date
has to be persisted in the database. This contains the entities, attributes etc.Identify
the primary keys for all the entities. Identify the other keys like candidate keys,
partial keys, if any
Week-2 Relate the entities appropriately. Apply cardinalities for each relationship. Identify
strong entities and weak entities (if any). Indicate the type of relationship
(total/partial). Try to incorporate generalization, aggregation, specialization etc
wherever required.
Week-3
E-R DIAGRAM FOR BUS

Week 4 Represent all entities (strong, week) in tabular fashion. Represent relationships in
a tabular fashion. There are different ways of representing as tables based on the
cardinality. Represent attributes as columns in the tables or as tables based on the
requirement. Different types of attributes (composite, multivalued and derived).

Week-5 Database normalization is a technique for designing relational database tables to


minimize duplication of information and, in doing so , to safeguard the database
against certain types of logical or structural problems namely data anomalies
Week-6 Installation of MySQL. In this week you will learn Creating databases, How to
create tables, altering the database, dropping tables and databases if not required.
You will also try truncate, rename commands etc
Week 7
DML command care used for managing data within schema objects.
Week-8 In this week you are going to practice queries(along with sub queries) using ANY,
ALL, IN, EXISTS, NOT EXIST, UNION, INTERSECT, Constraints etc..
Week-9 You are going to practice queries using Aggregate functions (COUNT, SUM,
AVG, MAX,and MIN), GROUP BY, HAVING and Creation and dropping of
VIEWS..

Week 10 A Trigger is a named database object which defines some action that the database
should take when some databases related event occurs. Triggers are executed
when you issues a data manipulation command like INSERT, DELETE, UPDATE
on a table for which the trigger has been created. They are automatically executed
and also transparent to the user. But for creating the trigger the user must have the
CREATE TRIGGER privilege. In this section we will describe you about the
syntax to create and drop the triggers and describe you some examples of how to
use them.
Week-11 A stored procedure is a procedure (like a subprogram in a regular computing
language) that is stored (in the database). Correctly speaking, MySQL supports
"routines" and there are two kinds of routines: stored procedures which you call,
or functions whose return values you use in other SQL statements the same way
that you use pre-installed MySQL functions like pi(). I'll use the word "stored
procedures" more frequently than "routines" because it's what we've used in the
past, and what people expect us to use.
Week-12 Cursors are used when the SQL Select statement is expected to return more than

6
one row. Cursors are supported inside procedures and functions. Cursors must be
declared and its definition contains the query. The cursor must be defined in the
DECLARE section of the program. A cursor must be opened before processing
and close after processing.

Week: 1
Date:
E-R Model
Analyze the problem carefully and come up with entities in it. Identify what date has to be persisted in the
database. This contains the entities, attributes etc.
Identify the primary keys for all the entities. Identify the other keys like candidate keys, partial keys, if any.
Definitions:
Entity:the object in the ER Model represents is an entity which is thing in the real world with an
independent existence.
Eg:

ER-Model:
Describes data as entities, relationships and attributes .The ER-Model is important preliminary for its role in
database design. ER Model is usually shown pictorially using entity relationship diagrams.

Attributes:
The properties that characterize an entity set are called its attributes. An attribute is referred to by the terms
data items, data element, data field item.
Ex: attributes for bus entity and ticket entity.

Composite Attribute:
The attribute which is madeup of combination of values.
E.g. Address(village,mandal,district,state).
Derived attribute:
The value of this attribute has to be derived from another attribute.
E.g. Age(derived from DOB)
Multivalued Attribute:
An attribute which can have multiple values.
E.g.Contact number
Super Key:
7
It is a set of one or more attributes that taken collectively allow us to identify uniquely a tuple in a relation.
E.g
Busno servicen source destination deptime retime bustype noofseats
o

Busno,serviceno,source,destination------------>super key

Candidate key:
It can be defined as minimal super key or irreducible super key. In other words an attribute or combination
of attributes that identifies the record uniquely but none of its proper subsets can identify the record
uniquely.
Busno servicen source destination deptime retime bustype noofseats
o

Busno,serviceno--------------->candidate key
Primary key:
A candidate key that is used by the database designer for unique identification of each row in atable is
known as primary key. A primary key consists of one or more attributes of the table.

Foreign key:
A relation schema say r1,may include among its attributes the primary key of another relation schema say
r2.This attribute is called a foreign key from r1,referencing r2.
E.g: Bus_no is primary key of bus entity ticket entity can have busno attribute in it.so,busno is foreign key in
ticket entity.

Partial key:
A weak entity type normally has a partial key which is the set of attributes that can uniquely identify weak
entity that are related to the same owner entity.

The entities in the “Roadway travels” is


1) Bus 2) Ticket 3) Passenger 4)Reservation 5)Cancellation6)Branch

Bus entity:
Attributes for the bus entity are

Busno, Routeno, source, destination, bustype, noofseats

Bus schema:
Busno Routen source destination bustype noofseats
o

Busno,Routeno ,source -----> super key


Busno,Routeno,bustype-----> super key
Busno,Routeno--------------->candidate key
Busno ---------------> primary key

Ticket entity:
Attributes for the ticket entity are

Ticketno, Age,Gender,journeydate, source, destination,dep_time seatno, amount, Boarding_ at,bustype,


Ticket schema:
8
Ticketn Joudat Ag Ge Dep_tim Sourc Destinatio Seatn Amoun bustyp Boarding_
o e e n e e n o t e at

Ticketno, source, destination ------->Super key


Ticketno, source, seatno --------------> Super key
Ticketno, destination, seatno ---------> Super key
Ticketno-----------> candidate key
Ticketno----------- >primary key

Passenger entity:
Attributes for the Passenger entity are

pname, age,gen,ticket_nos, phno,tkt_no,occupation,email-id,address

Passenger schema:

pname age gen ticketno Address phn occupation Email-id


o

Pname,ticket_no…superkey
Pname,ticket_no-- super key
Pname------- super key
Pname----- candidate key
Pname-----primary key

Sample data for Bus entity:

Bus_n Type_of_bus src dest Route_no No_of_seats


o
1001 A/C HYD VJA 1 36
1002 A/C CHRL BPTL 2 36
1003 Non-A/C GNTR HYD 3 36
1004 Non-A/C HYD BNGR 4 36
1005 A/C HYD CHN 5 36

Sample data for ticket entity:

Ticket_n Journey ag Ge Dep_ti Booking Boardin Tota Bus_no amou Arr_ti


o _ e n me date g l nt me
date at seats
M501 26-08- 20 M 18:40 20-08-10 dsnr 2 1001 200 23:00
10

9
B536 01-09- 50 F 23:00 08-08-10 lbnr 4 1002 800 06:00
10
A500 23-07- 45 M 04:00 15-07-10 dsnr 2 1003 1000 01:00
10
B950 31-08- 27 F 12:00 12-08-10 mgbs 3 1004 600 06:00
10
C714 02-09- 18 F 20:20 22-08-10 jbs 1 1005 500 03:00
10

Sample data for Passenger entity:

Pname Age gen pp_no Email Occupation Ticket_no


Anirudh 23 M 9821 anirudh@gmail.com doctor M501
Amarnat 24 M 1390 amar@gmail.com student B536
h
Lakshmi 34 F 5043 lakshmi@gmail.com professor A500
Sameera 56 F 3454 sam@gmail.com doctor B950
Michael 45 F 3423 Michael@gmail.com engineer C714

Sample data for Reservation Entity:

pname Gen Age Addr phno Busno Src Dest Noof Jour Bus Confirmation
seats date type status
Amaranth M 24 Hyd 9123456789 1001 HY MUM 2 12-08- A/C yes
D 2010
Akshaya F 23 Hyd 9865688989 1002 Hyd Chn 1 14-08- Non yes
2010 A/C
Amulya F 24 Hyd 9834377459 1002 Hyd Chn 1 13-08- Non yes
2010 A/C
Sharanya F 25 Hyd 9685423133 1002 Hyd Bglore 2 1-08- A/C yes
2010

Cancellation Entity:

Ticket_no Bus_no Source Dest Journey_date Bus_typ No_of_seats Confirmation Amount


e status
1111 1001 Hyd Mum 12-08-2010 A/C 2 yes 1000
3333 1002 Hyd Chn 13-08-2010 Non A/C 1 Yes 700

10
Week: 2
Date:
Concept design with E – R model
Relate the entities appropriately. Apply cardinalities for each relationship. Identify strong entities and weak
entities (if any). Indicate the type of relationship (total/partial). Try to incorporate generalization,
aggregation, specialization etc wherever required.

Definitions:

The cardinality ratio: - for a binary relationship specifies the maximum number of relationships that an
entity can participate in.

Relationship: - it is defined as an association among two or more entities.

Weak and strong entity: - an entity set may not have sufficient attributes to form a primary key. Such an
entity set is termed a weak entity set. An entity set that has primary key is termed a strong entity set.

Total participation:-
Ex: - if a travel agency states that every passenger must make reservation then every passenger travels in
bus. Than a passengers entity can exist only if it participates in atleast one travels relationship
instances.Thus the participation of passenger in travel is called total participation meaning that every entity
in the “total set” passenger entities must be related to bus via travels relationship.

All passengers travel in one bus so it is total participation

Partial participation: a participation that is not total is called as partial participation.


11
Some passengers cancel ticket so it is partial participation

Generalization: consists of identifying some common characteristics of a collection of entity set and
creating new entity set that contains entities possessing these common characteristics.

Aggregation: allows us to indicate that a relationship set participates in another relationship set.

Specialization: in the process of identifying subsets of an entity set (the super set) that share some
distinguishing characteristics. This entity type is called the super class of the specialization.

Relationship between different entities:

Relationship between Bus and Ticket entities


1:M binary relationship

Relationship between Passenger and Bus entities


M:1 binary relationship

Relationship between Passenger and Ticket entities


M:N binary relationship

Entity diagram for BUS:

Entity diagram for passenger:


12
Entity diagram for Ticket:

13
Entity diagram for Branch:

Entity diagram for Reservation:

Entity diagram for Cancellation:

14
Generalization:

Generalization and specialization:

Aggregation

15
Week-3
Date:
Relational model
Represent all entities (strong, week) in tabular fashion. Represent relationships in a tabular fashion. There
are different ways of representing as tables based on the cardinality. Represent attributes as columns in the
tables or as tables based on the requirement. Different types of attributes (composite, multivalued and
derived).

Definitions:
Composite attributes: can be divided into smaller sub parts which represent more basic attributes with
independent meaning.

Multivalued attributes: for exthe attribute in the Bus entity Bustype can have different types of buses
according that the Bustype attribute contains the values as Garuda, Luxury, Express, and Ordinary. This type
of attribute is called multivalued attribute and may have lower and upper bounds to constrain the number of
values allowed for each individual entity.

Derived attributes:
In some cases, two or more attribute values are related. With the help of one attribute we get the value of
another attribute. Age and DOB attributes. With the DOB we get the age of the person to the current date.

Entity sets to tables:

Relational schema for Bus relation:

Bus(Busno:numeric,Routeno:numeric,source:varchar(10),destination:varchar(10), bustype:varchar(10),
noofseats:int)

Relational schema for Passenger relation:


Passenger(pname:varchar(10), age:int(4), gen:char(3), address:varchar(50), contactno:numeric(10),
ticket_no:numeric(5), occupation:varchar(5), emai-id:varchar(15))

16
Relational schema for Ticket relation:
Ticket(ticket_no:numeric,age:int(4),gen:char(5),journey_date,src:varchar,dest:varchar,dep_time,booking_da
te,bus_type:varchar(5),boarding_at:varchar(5))

Relational Schema for Branch relation:


Branch(branch_id:numeric(10),manager_id:numeric(5),manager_name:varchar(10),Location:varchar(10),L
ocation_id:numeric(5))

Relational schema for Reservation:


Reservation(pname:varchar(10),age:numeric,gen:char(5),adder:varchar(20),contact_no:numeric(10),bus_no
:numeric(5),src:varchar,dest:varchar(5),bus_type:varchar(10),confirmation_status:varchar(5))

Relational schema for Cancellation:

Cancellation(ticket_no:numeric, bus_no:numeric, src:varchar(20), dest:varchar(20),


journey_date,bus_type:varchar(10),no_of_seats:numeric(3),confirmation_status:varchar(5),amount:numeric(
5))

TABLES:
Bus:
Busno source destination bustype Noofseats
1001 HYD MUM Ac 24
1002 HYD CHN Non-A/c 36
1003 HYD VJA Non-A/c 36
1004 HYD NZBD Non-A/c 36
1005 HYD GNT A/c 24

ticket:

Ticket_n Age Gen Journey_ Src Dest Dep_time Booking date Bus_type Boarding_
o date at
100 23 M 12-08-2010 HYD MU 10:00 01-08-2010 A/C L.B Nagar
M
101 24 F 14-08-2010 HYD CHN 12:00 30-0-2010 Non-A/C IBP
102 29 M 13-08-2010 HYD VJA 19:00 01-08-2010 A/C JBS
103 30 F 22-08-2010 HYD GNT 13:00 10-08-2010 Non-A/c DSNR

17
Passenger:
Pname Age Ge Addr Contact_no Ticket_n Occupation Email-id
n o
Amarnat 23 M Lbnagar 9090867812 100 Engg amar@gmail.com
h
Amulya 24 F Banjara 9088888112 101 Doctor amulya@yahoo.com
hills
Avinash 29 M Jubilee 9089800065 102 lecturer avi@gmail.com
hills
Rani 30 F koti 90812343434 103 Teacher rani@gmail.com
lalitha 26 F dsnr 90889909000 104 student lalitha@gmail.com
Reservation:

pname Gen Age Addr phno Busno Src Dest Noof Jour Bus Confirmation
Seats date type status
Amaranth M 24 Hyd 9123456789 1001 HY MUM 2 12-08- A/C yes
D 2010
Akshaya F 23 Hyd 9865688989 1002 Hyd Chn 1 14-08- Non yes
2010 A/C
Amulya F 24 Hyd 9834377459 1002 Hyd Chn 1 13-08- Non yes
2010 A/C
Sharanya F 25 Hyd 9685423133 1002 Hyd Bglore 2 1-08- A/C yes
2010

Cancellation:

Ticket_no Bus_no Source Dest Journey_date Bus_typ No_of_seats Confirmation Amount


e status
101 1001 Hyd Mum 12-08-2010 A/C 2 yes 1000
102 1002 Hyd Chn 13-08-2010 Non A/C 1 Yes 700

18
Week: 4
Date:
Normalization:

Database normalization is a technique for designing relational database tables to minimize


duplication of information and, in doing so , to safeguard the database against certain types of logical
or structural problems namely data anomalies.

The normalization forms are:

Tick Age Ge Journe Src Dest Dep Bookin Bus Boar Seat_n Tota Am Bus_no
t n y _ g _typ ding_ o l t
_no date time date e at seats
100 23 M 12-08- HY MU 10:0 01-08- A/C L.B 20 1 800 1001
2010 D M 0 2010 Naga
r
101 24 F 14-08- HY CHN 12:0 30-0- Non IBP 22,23 2 500 1002
2010 D 0 2010 -A/C
102 29 M 13-08- HY VJA 19:0 01-08- A/C JBS 24,25 2 300 1003
2010 D 0 2010
103 30 F 22-08- HY GNT 13:0 10-08- Non DSN 28 1 250 1004
2010 D 0 2010 -A/c R
1. First Normal Form: Eliminate repeating groups: Make a separate each set of related attributes,and
give each table a primary key.

Tkt_i Ticket_no Seat_no Total_seats Amount Bus_no


d 1 800 1001
1 100 20 2 1000 1002
2 101 22,23 2 600 1003
3 102 24,25
Bus_no Ticket Journey Age Gen Src Dest Dep_ Booking Boarding Bus_ Total_ amt
_no _date time date at type seats
1001 100 12-08- 23 M HYD MUM 10:00 01-08- lbnagar A/C 1 800
2010 2010
1002 101 14-08- 24 F HYD CHN 12:00 30-08- IBP Non- 2 1000
2010 2010 A/C
1003 102 13-08- 9 M HYD VJA 19:00 01-08- JBS A/C 2 600
2010 2010

19
2. Second Normal Form: Eliminate Redundant data-If an attribute depends on only part of a
multivalued key remove it to a separate table.
In this example branch entity is having a column which has redundant data that is location.
Branch_i B_name manage location
d r
A1b1 Sv travels Rao Hyd
B2c4 Sv travels Ram Goa
C3d4 Sv travels Ramesh Chennai
D4e5 Sv travels Rakesh Mumbai

Loc_i Loc_name
Branch_i B_name manager Branch_id Loc_id
d
d A1b1 10
10 HYD
A1b1 Svtravels Rao B2c4 20
20 Goa
B2c4 Sv travels Ram C3d4 30
20 Chennai
C3d4 Sv travels Ramesh D4e5 40
40 Mumbai
D4e5 Sv travels Rakesh

3. Third Normal Form: Eliminates columns not dependent on key: If attributes do not contribute to a
description of the key, remove them out into distinct tables.

In branch entity, branch_id and b_name describe only a branch, not a manager. To achieve 3NF,
manager must be moved into a separate table.

Branch_i B_name manager


d
A1b1 Svtravels Rao
B2c4 Sv travels Ram
C3d4 Sv travels Ramesh
D4e5 Sv travels Rakesh

Branch_id B_name Mgr_Id Mgr_I Mgr_name Branch_Id


A1b1 Svtravels 01 d
B2c4 Sv 02 01 Svtravels A1b1
travels 02 Sv travels B2c4
C3d4 Sv 03 03 Sv travels C3d4
travels 04 Sv travels D4e5
D4e5 Sv 04
travels
20
Week 5:
Date:

Installation of MySQL: Download MySQL software from the web site:


http://www.softpedia.com/get/Internet/Servers/Database-Utils/MySQL-Workbench.shtml
Before downloading save the file and then run the set up after downloading. Before running Mysql
workbench we have to install .net frameworkof version 2.0 (or) higher.
Now we have to download the .net frameworkfromthe web site:
http://www.brothersoft.com/net.framework-download-112623.html
Before installing the .net frame work we have to download the Windows Installer 3.1 to support the .net
frame workfrom the web site:
http://www.microsoft.com/downloads/details.aspx?familyid=889482fc-5f56-4a38-b838-
de776fd4138c&displaylang=en
After downloading the Windows Installer 3.1 software run the set up.
 Start the set up wizard and click NEXT.

 Next click on the LICENSE agreement to ACCEPT and again click NEXT.

21
 Now updating the system process starts.

 After installing the Windows Installer 3.1 software click on FINISH.

22
Now start the installation process of .net frame work to install Mysql Work Bench.
 Start the set up wizard
 Next ACCEPT the LICENCE AGREEMENT and click INSTALL.

 Now the DOWNLOAD and INSTALLATION process starts.


 Before INSTALLATION, it first DOWNLOADS the components of .net frame work from
internet and then starts the INSTALLATION process.

23
 After completing the INSTALLATION process click on EXIT and the setup is completed.

24
Now start the installation process of MySQL Work Bench.
 Start the setup wizard.
 Now click on NEXT to start the INSTALLATION process.

 Now select the Setup Type.


 Complete
 Custom
 Click on COMPLETE to install all program feature and click NEXT.

25
 Now click on INSTALL to start the installation process.

 Now the INSTALLATION process starts.

26
 Now click on FINISH to complete the setup wizard.

 The overall INSTALLATION process has been completed. And we can perform QUERIES by
using MySQL Work Bench.

We use Wamp Server to execute the queries. Wamp server is easy and user friendly to use.

27
DDL Commands:

In wamp server we have created our own database “group d” . To create a new table in wamp server first it
will ask for new table name and no of fields.
After that it has shown field name and field data type.
Then we clicked on insert icon to insert values into table.
It has displayed the created table along with the related sql query in the upper block.

1. Create: It is used to create the tables in the database. These are used to manage the data over the
database.
Syntax: Create table ‘groupd’. ‘bus’(‘bus_no’ varchar(20) NOT NULL,’type_of_bus’ varchar(20) NOT
NULL,’src’ varchar(20),dest varchar(20),route_no int(20) NOT NULL,’no_of_seats’ int(20) NOT NULL,
PRIMARY KEY(bus_no) ENGINE=MYISAM;
A table is created and to insert the values into the table we use the command insert.
----insert into ‘groupd’.’bus’(‘bus_no,’type_of_bus’,’src’,’dest’,route_no’,’no_of_seats’)values(‘1001’,’A/
C’,’HYD’,’VJA’,’1’,’36’);
----insert into ‘groupd’.’bus’(‘bus_no,’type_of_bus’,’src’,’dest’,route_no’,’no_of_seats’)values(‘1002’,’A/
C’,’HYD’,’BPTL’,’2’,’36’);
28
----insert into
‘groupd’.’bus’(‘bus_no,’type_of_bus’,’src’,’dest’,route_no’,’no_of_seats’)values(‘1003’,’Non-A/
C’,’GNTR’,’HYD’,’3’,’36’);
----insert into
‘groupd’.’bus’(‘bus_no,’type_of_bus’,’src’,’dest’,route_no’,’no_of_seats’)values(‘1004’,’Non-A/
C’,’HYD’,’BNGR’,’4’,’36’);
----insert into ‘groupd’.’bus’(‘bus_no,’type_of_bus’,’src’,’dest’,route_no’,’no_of_seats’)values(‘1005’,’A/
C’,’HYD’,’CHN’,’5’,’36’);

Bus_n Type_of_bus src dest Route_no No_of_seats


o
1001 A/C HYD VJA 1 36
1002 A/C CHRL BPTL 2 36
1003 Non-A/C GNTR HYD 3 36
1004 Non-A/C HYD BNGR 4 36
1005 A/C HYD CHN 5 36

In the same way we have created the remaining tables in the wamp server.
Ticket_no Journey_ age Ge Dep_ti bookingd Boarding Total Bus_no amoun Arr
date n me ate at seats t _ti
me
M501 26-08-10 20 M 18:40 20-08-10 dsnr 2 1001 200 23:0
0
B536 01-09-10 50 F 23:00 08-08-10 lbnr 4 1002 800 06:0
0
A500 23-07-10 45 M 04:00 15-07-10 dsnr 2 1003 1000 01:0
0
B950 31-08-10 27 F 12:00 12-08-10 mgbs 3 1004 600 06:0
0

Passenger table:

Pname Age gen pp_no email Occupation Ticket_no

29
Anirudh 23 M 9821 anirudh@gmail.com doctor M501
Amarnat 24 M 1390 amar@gmail.com student B536
h
Lakshmi 34 F 5043 lakshmi@gmail.com professor A500
Sameera 56 F 3454 sam@gmail.com doctor B950
Michael 45 F 3423 Michael@gmail.com engineer C714

Branch Table:

Branch_i B_name manager


d
A1 Svs Rao
B2 Svs travels Ram
C3 Svs Ramesh
D4 Svs Ramana
E5 Svs bus travels Rakesh

Manager: Branch_Loc:

Mgr_I Mgr_name Branch_Id Branch_id Loc_id


d A1 L0
01 Svtravels A1 B2 L1
02 Sv travels B2 C3 L2
03 Sv travels C3 D4 L3
04 Sv travels D4 E5 L4

Location Table:
Loc_I Loc_name
d
L0 DSNR
L1 SEC
L2 MGBS
L3 LBNR
L4 KP

30
Cancellation Table:

Bus_n Source Dest Journey_date Bus_typ No_of_seats Confirmatio Amount


o e n status
1001 Hyd Mum 12-08-2010 A/C 2 yes 1000
1002 Hyd Chn 13-08-2010 Non A/C 1 Yes 700
1003 HYD VJA 22-08-2010 Non A/C 3 Yes 500
1004 HYD VIZ 29-08-2010 A/C 2 Yes 800
1005 HYD BNGLR 02-09-2010 A/C 5 Yes 1000

Reservation Table:

pname Gen Age Addr Contactno Busno Src Dest Noof Jour Bus Confirmation Booking date
Seats date type status
Amaranth M 24 Hyd 9123456789 1001 HYD MUM 2 12-08- A/C yes 01-08-2010
2010
Akshaya F 23 Hyd 9865688989 1002 Hyd Chn 1 14-08- Non yes 05-08-2010
2010 A/C
Amulya F 24 Hyd 9834377459 1002 Hyd Chn 1 13-08- Non yes 05-08-2010
2010 A/C
Sharanya F 25 Hyd 9685423133 1002 Hyd Bglor 2 1-08- A/C yes 0-0-2010
e 2010

Week 6: Practicing DML commands

DML commands are used to retrieve the data from the database and used to manage the data. The DML
commands are as follows:

SELECT:

Select * from branch;

Branch_i B_name manager


d
A1 Svs Rao
B2 Svs travels Ram
C3 Svs Ramesh
D4 Svs Ramana
E5 Svs bus travels Rakesh

31
Insert into groupd .branch(‘branch_id,’b_name’,’manager’)
values into(‘F6’,’SVS’,’Ramaiah’);

Branch_id B_name manager


A1 Svs Rao
B2 Svs travels Ram
C3 Svs Ramesh
D4 Svs Ramana
E5 Svs bus travels Rakesh
F6 Svs Ramaiah

Values has been inserted.

UPDATE:

Update branch set branch_id=G7 where branch_id=F6;


Table has been updated.

DELETE:

Delete table seat_info;


Table seat_info deleted

32
Week 7: Querying the Database
1. Display unique ticket_no from of all passengers
Select distinct ticket_no from passenger;

Ticket_no
M501
B536
A500
B950
C714

2. Display all the names of male passengers.


Select pname from passenger where gen=’male’;

pname
Anirudh
Amaranth
michael

3. Display the ticket number and names of all the passengers.


Select ticket_no,name from passenger;
Ticket_no Pname
M501 Anirudh
B536 Amarnath
A500 Lakshmi
B950 Sameera
C714 Michael

4. Display the source and destination having journey time more than 10 hours
Select src,dest from bus where bus_no in(select bus_no from ticket where
hour(timediff(arr_time,dep_time))>10);

Src dest
HYD BNGLR

33
HYD CHN

5. Find the ticket numbers of passengers whose name start with ‘A’ and end with ‘H’.
Select ticket_no from passenger where name like ‘A%H’

Ticket_no
M501
B536

6. Find the names of passengers whose age is between 30 and 45


Select pname from passenger where age>=30 && age<=45;

pname
Lakshmi
Sameera
Michael

7. Display all the passenger names beginning with ‘A’


Select name from passenger where name like ‘A%’;

Pname
Amaranth
Anirudh

34
8. Display the sorted list of passengers names
Select name from passenger order by name;

Pname
Amarnath
Anirudh
Anirudh
Michael
Sameera

9. Display the bus numbers that travels on Sunday and Wednesday

Select bus_no from ticket where dayofweek(journey_date)=1 or dayofweek(journey_date)=4;

Bus_no
1001
1003

10. Display the details of passengers who are travelling either in A/C or Non-A/C(using only IN
operator)
Select * from passenger where ticket_no in(select ticket_no from ticket where bus_no in(select
bus_no from bus where bus_type=’A/C’ or bus_type=’Non-A/C’;

Pname Age gen pp_no email Occupation Ticket_no


Anirudh 23 M 9821 anirudh@gmail.com doctor M501
Amarnat 24 M 1390 amar@gmail.com student B536
h
Lakshmi 34 F 5043 lakshmi@gmail.com professor A500
Sameera 56 F 3454 sam@gmail.com doctor B950
Michael 45 F 3423 Michael@gmail.com engineer C714

35
Week 8 and week 9: Querying continued………….

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

Select bus_no,src,dest from passenger UNION select bus_no,src dest from cancellation;
Src Bus_no dest
HYD 1001 Mum
HYD 1002 Chn
HYD 1003 VJA
HYD 1004 VIZ
HYD 1001 BNGLR
HYD 1002 Mum
HYD 1003 Chn
HYD 1004 VJA

2. Write a query to display different travelling options available in bus travels.


Select distinct bus_type from bus;

Bus_type
A/C
Non A/C

3. Display the number of days in a week on which 1003 bus is available

Select count(dayofweek(journey_date))from ticket where bus_no in(select bus_no from ticket where
bus_no=1003 and journey_date between ’12-08-2010’ and ’19-08-2010’;

36
4. Find the number of tickets booked for each ticket_no using group by clause
Select ticket_no(no_of_seats) from ticket groupby ticket_no;

Ticket_no Sum(no_of_seats)
M501 2
B536 1
A500 2
B950 3
C714 2

5. Find the distinct ticket_no from ticket


Select distinct ticket_no from ticket;

Ticket_no
M501
B536
A500
B950
C714

6. Find the number of tickets booked in each class where the number of seats is greater than 1.
Select b.bus_type,sum(t.total no_of_passengers) from ticket t,bus b where t.bus_no=b.bus_no
group by b.bustype;

Bus_type Sum(no_of_passengers)
A/C 2
Non A/C 1

37
7. Find the total number of cancelled seats.

Select count(*) from cancellation where status=’yes’;

8. Write a query to count the number of tickets for the buses, which travelled after the date ’14-
08-2010’

Select count(ticket_no) from ticket group by bus_no where journey_date >’14-08-2010’

Bus_no Count(ticket_no)
1001 1
1003 1

38
Week 10

Trigger: A Trigger is a named database object which defines some action that the database should take
when some databases related event occurs. Triggers are executed when you issues a data manipulation
command like INSERT, DELETE, UPDATE on a table for which the trigger has been created. They are
automatically executed and also transparent to the user. But for creating the trigger the user must have the
CREATE TRIGGER privilege. In this section we will describe you about the syntax to create and drop the
triggers and describe you some examples of how to use them.

Create Trigger: The general syntax of CREATE TRIGGER is:

CREATE TRIGGER trigger name trigger time trigger event ON tbl_name FOR EACH ROW trigger
statement.

By using above statement we can create the new trigger. The trigger can associate only with the table name
and that must be refer to a permanent table. Trigger time means trigger action time. It can be BEFORE or
AFTER. It is used to define that the trigger fires before or after the statement that executed it. Trigger
event specifies the statement that executes the trigger. The trigger event can be any of the DML Statement:
INSERT, UPDATE,DELETE.
We can not have the two trigger for a given table, which have the same trigger action time and event. For
Instance: we cannot have two BEFORE INSERT triggers for same table. But we can have a BEFORE
INSERT and BEFORE UPDATE trigger for a same table. Trigger statement have the statement that
executes when the trigger fires but if you want to execute multiple statement the you have to use the
BEGIN…END compound statement.We can refer the columns of the table that associated with trigger by
using the OLD and NEW keyword. OLD.column_name is used to refer the column of an existing row before
it is deleted or updated and NEW.column_name is used to refer the column of a new row that is inserted.

In INSERT trigger we can use only NEW.column_name because there is no old row and in a DELETE
trigger we can use only OLD.column_name because there is no new row. But in UPDATE trigger we can
use both, OLD.column_name is used to refer the columns of a row before it is updated
and NEW.Column_name is used to refer the column of the row after it is updated.

39
Insert

MySQL>Create trigger t1

-> before insert on passenger

-> for each row

-> begin

-> if new.age>30 then

-> set new.pnrno=3333;

-> else

-> set new.pnrno=' ';

-> end if;

-> end

-> //

Query OK, 0 rows affected (0.20 sec)

MySQL> Insert into Passenger Values(555,'lata',30,'F','Nacharam',’9999999234’,5439)

-> //

Query OK, 1 row affected (0.16 sec)

MySQL>Select * from Passenger;

-> //

PNR no Pname Age Gender Addr Phno Tno

456 Avinash 45 M Hyd 9008745625, 9000567834 6754

746 Vani 34 F Delhi 8146372897, 9856437893 2087

129 Meena 24 F Kurnool 9989764534 3475

231 Shashi 38 M B’lore 9248654891, 8145637689 2298

901 Navya 22 F Chennai 9867549072 6057

555 Lata 30 F Nacharam 9999999234 5439

40
6 rows in set (0.00 sec)

Update:

MySQL> Create trigger t1 before update on reservation

-> for each row

-> begin

-> if new.noofseats>30 then

-> set new.noofseats=old.noofseats;

-> else

-> set new.noofseats=new.noofseats;

-> end if;

-> end//

Query OK, 0 rows affected (0.03 sec)

MySQL> Update Reservation set No-of-seats=20 where PNRno=231;

-> //

Query OK, 1 row affected (0.01 sec)

Rows matched: 1 Changed: 1 Warnings: 0

MySQL> Select * from Reservation;

-> //

PNR no Journey Date No-of-seats Addr Phno Status

456 10/08/10 40 Hyd 9008745625 Yes


9000567834
129 20/08/10 40 Kurnool 9989764534 No
901 25/08/10 40 Chennai 9867549072 Yes
746 14/08/10 40 Delhi 8146372897 No
9856437893
231 18/08/10 20 B’lore 9248654891 Yes
8145637689

41
6 rows in set (0.00 sec)

Delete:

MySQL> delimiter //

MySQL> Create trigger rc before delete on cancellation

-> for each row

-> begin

-> Insert into Reservation Values (old.PNRno, old.No-of-seats, old.Addr, old.phno,old.status);

-> end//

Query OK, 0 rows affected (0.05 sec)

MySQL> Delete from cancellation where PNRno=129//

Query OK, 1 row affected (0.08 sec)

MySQL> Select * from Reservation//

PNR no Journey Date No-of-seats Addr Phno Status

456 10/08/10 40 Hyd 9008745625 Yes


9000567834
129 20/08/10 40 Kurnool 9989764534 No
901 25/08/10 40 Chennai 9867549072 Yes
746 14/08/10 40 Delhi 8146372897 No
9856437893
231 18/08/10 40 B’lore 9248654891 Yes
8145637689

42
MySQL> Select * from cancellation//

PNR no Journey Date No-of-seats Addr Phno Status

456 10/08/10 40 Hyd 9008745625 No


9000567834
901 25/08/10 40 Chennai 9867549072 No
746 14/08/10 40 Delhi 8146372897 Yes
9856437893
231 18/08/10 40 B’lore 9248654891 No
8145637689

43
Week 11
Procedures: A stored procedure is a procedure (like a subprogram in a regular computing language) that is
stored (in the database). Correctly speaking, MySQL supports "routines" and there are two kinds of routines:
stored procedures which you call, or functions whose return values you use in other SQL statements the
same way that you use pre-installed MySQL functions like pi(). I'll use the word "stored procedures" more
frequently than "routines" because it's what we've used in the past, and what people expect us to use.

MySQL> delimiter //

MySQL> Create procedure p2(p_age int)

-> begin

-> Select Pname, Phno, Gender from passenger where age>p_age;

-> end

-> //

Query OK, 0 rows affected (0.09 sec)

MySQL>call p2(25)

-> //

Pname Gender Phno

Vani F 8146372897,
9856437893

1 row in set (0.03 sec)

Query OK, 0 rows affected (0.05 sec)

44
Week 12
Cursor: Cursors are used when the SQL Select statement is expected to return more than one row. Cursors
are supported inside procedures and functions. Cursors must be declared and its definition contains the
query. The cursor must be defined in the DECLARE section of the program. A cursor must be opened
before processing and close after processing.
Syntax to declare the cursor:
DECLARE <cursor_name> CURSOR FOR <select_statement>

Multiple cursors can be declared in the procedures and functions but each cursor must have a unique name.
And in defining the cursor the select_statement cannot have INTO clause.
Syntax to open the cursor:
OPEN <cursor_name>

By this statement we can open the previously declared cursor.


Syntax to store data in the cursor :
FETCH <cursor_name> INTO <var1>,<var2>…….

The above statement is used to fetch the next row if a row exists by using the defined open cursor.
Syntax to close the cursor :
CLOSE <cursor_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.

MySQL> Create procedure kcur15(ti_id int)

-> begin

-> declare x_no int;

-> declare x_src varchar(30);

-> declare x_dst varchar(30);

-> declare c5 cursor for select Tno,Src,Dest from ticket where tno=ti_id;

-> open c5;

-> fetch c5 into x_no,x_src,x_dst;

-> select x_no,x_src,x_dst from ticket where tno=ti_id;

-> close c5;

45
-> end//

Query OK, 0 rows affected (0.00 sec)

MySQL> Call kcur15(2298)//

X_no X_src X_dst


2298 B’lore Hyd

1 row in set (0.03 sec)

Query OK, 0 rows affected (0.03 sec)

MySQL> Create procedure curb(bu_id varchar(10))

-> begin

-> declare x_no varchar(10);

-> declare x_type varchar(30);

-> declare c4 cursor for select busno,type from bus where busno=bu_id;

-> open c4;

-> fetch c4 into x_no,x_type;

-> select x_no,x_type from bu where busno=bu_id;

-> close c4;

-> end//

Query OK, 0 rows affected (0.00 sec)

MySQL> Call curb(‘AP1027’)//

X_no X_type
AP1027 a/c

1 row in set (0.00 sec)

46
REFERENCES
1)ORACLE PL/SQL by example. Benjamin Rosenzweig, Elena Silvestrova, Pearson
Education 3rd Edition
2)ORACLE DATA BASE LOG PL/SQL Programming SCOTT URMAN, Tata Mc-
Graw Hill.
3)SQL & PL/SQL for Oracle 10g, Black Book, Dr.P.S. Deshpande.

47
48

You might also like