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

DBMS Lab Manual R22

The document is a lab manual for a Database Management Systems course, detailing experiments related to the design and implementation of databases using E-R models, relational models, normalization, and DDL/DML commands. It covers concepts such as entities, attributes, relationships, and various SQL commands for creating and manipulating database tables. The manual includes practical exercises for students to apply their knowledge in real-world scenarios, specifically focusing on a bus reservation system.

Uploaded by

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

DBMS Lab Manual R22

The document is a lab manual for a Database Management Systems course, detailing experiments related to the design and implementation of databases using E-R models, relational models, normalization, and DDL/DML commands. It covers concepts such as entities, attributes, relationships, and various SQL commands for creating and manipulating database tables. The manual includes practical exercises for students to apply their knowledge in real-world scenarios, specifically focusing on a bus reservation system.

Uploaded by

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

DATA BASE MANAGEMENT SYSTEMS LAB MANUAL

(R22 REGULATION)

II B.TECH II SEM CSE,AIML

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

ER model
The ER (Entity Relationship) Model was designed and developed and is represented by an ER
diagram.
The ER model is a high-level data model which stands for the Entity-Relationship Model. The
ER Model is used for defining the relationship and elements for any specific system.
The ER model or the structureof the database is represented as a diagram known as the entity-
relationship diagram.

Component of ER Diagram

Entity
An entity can be any place, person, object, or class.In an ERDiagram,the entity can be
portrayed as rectangles.

Weak Entity-A weak entity is the one which is dependent on another entity.It is portrayed by a
double rectangle.

Attribute
The attribute describes the entity property. An eclipse is considered to show an attribute. For
instance, Contact number, ID, age, etc.
2
Key Attribute - It is used to represent the major characteristics of any entity. It is represented
the underlined text inside the ellipse.

Composite Attribute-A composite attribute refers to an attribute which is composed of various


other attributes. It is portrayed by an eclipse, which is linked with other eclipses.

Multivalued Attribute - A multivalued attribute consists of more than one value. Multivalued
attributes are represented by a doubleoval.Forinstance, any student can have one or mor ethan
phone numbers.

3
Derived Attribute - Any attribute which can be acquired by any other attribute is considered as
a derived attribute. It is portrayed by a dash ecllipse.For instance, the age of the person can be
changed with time and can even be derived from any other attribute such as Date of Birth.

Relationship
A diamond-shaped box represents relationships. All the entities(rectangle-shaped)participating
in a relationship get connected using a line.

There are four types of relationships. These are:


One-to-one: When only a single instance of an entity is associated with the relationship, it is
termed as '1:1'.

One-to-many: When more than one instance of an entity is related and linked with a
relationship, it is termed as '1:N'.

Many-to-one: When more than one instance of an entity is linked with the relationship, it is
termed as 'N:1'.

Many-to-many: When more than one instance of an entity on the left and more than one
instance of an entity on the right can be linked with the relationship, then it is termed as ‘N:N’
relationship.

4
ROADWAY TRAVELS
“RoadwayTravels”is in business since 1977 with several buses connecting different places in
India.Its main office is located in Hyderabad.
The company wants to computerize its operations in the following areas:
Reservations Ticketing
Cancellations
Reservations: Reservations are directly handled by booking office. Reservations can be made
60days in advance in either cash or credit.In case the ticket is not available, a waitlisted ticket
is issued to the customer. This ticket is confirmed against the cancellation.
Cancellation and modification: Cancellations are also directly handed at the booking office.
Cancellation charges will be charged. Wait listed tickets that do not get confirmed are fully
refunded.
AIM: Analyze the problem and come with the entities in it.Identifywhat Data has to be
persisted in the databases.
The Following are the entities:
1. Bus
2. Reservation
3. Ticket
4. Passenger
5. Cancellation

Bus (Entity)

Reservation (Entity)

5
Ticket (Entity)

Passenger (Entity)

Cancellation (Entity)

6
Concept design with E-R Model

7
Experiment-2
RELATIONAL MODEL

AIM:TO REPRESENT ALL THE ENTITIES (STRONG,WEAK) IN TABULAR FASHION.


REPRESENT RELATIONSHIPS IN A TABULAR FASHION.
1. BUS
BUS: BUS (BUSNO: STRING, SOURCE: STRING, DESTINATION: STRING, COACHTYPE:
STRING)
MYSQL> SHOW DATABASES;
MYSQL>CREATE DATABASE DBMS;
MYSQL> USE DBMS;

MYSQL>CREATE TABLE BUS (BUSNO VARCHAR(10),SOURCE VARCHAR(20),DESTINATION


VARCHAR(20), COACHTYPE VARCHAR(10), PRIMARY KEY(BUSNO));
MYSQL>DESC BUS;

2. TICKET
TICKET:TICKET(TICKETNO:STRING,DOJ:DATE,ADDRESS:STRING,CONTACTNO:INT,
BUSNO: STRING, SEATNO: INTEGER, SOURCE: STRING, DESTINATION: STRING)
MYSQL> CREATE TABLE TICKET(TICKETNOVARCHAR(20)PRIMARYKEY, DOJ DATE,
ADDRESS VARCHAR(20),CONTACT NO INT,BUS NO VARCHAR(20), SEAT NOI
NT,SOURCE

8
VARCHAR(10), DESTINATION VARCHAR(10), FOREIGN KEY(BUSNO) REFERENCES
BUS(BUSNO));
MYSQL>DESC TICKET;

3. PASSENGER
PASSENGER: PASSENGER (PASSPORTID: STRING,TICKETNO: STRING, NAME: STRING,
CONTACTNO: STRING, AGE: INTEGER, SEX: CHARACTER, ADDRESS: STRING)
MYSQL>CREATE TABLE PASSENGER(PASSPORT ID VARCHAR(15),PNR NO VARCHAR(10),
TICKET NO VARCHAR(15),NAME VARCHAR(15),CONTACT NO VARCHAR(20),AGE
INTEGER, SEX CHAR(2),ADDRESSVARCHAR(20),PRIMARYKEY
(PASSPORTID,TICKETNO),FOREIGN KEY(TICKETNO) REFERENCES TICKET(TICKETNO));
MYSQL>DESC PASSENGER;

4. RESERVATION
RESERVATION:RESERVATION(PNRNO:STRING, DOJ:DATE, NO OF SEATS:INTEGER,
ADDRESS: STRING, CONTACT NO: STRING, BUS NO: STRING, SEATNO: INTEGER)
MYSQL>CREATE TABLE RESERVATION(PNRNO VARCHAR(20),DOJ DATE,NO O F
SEATES INTEGER,ADDRESS VARCHAR(20), CONTACT NO VARCHAR(20), BUS NO
VARCHAR(20), SEAT NO INTEGER,
PRIMARYKEY(PNRNO,BUSNO),FOREIGNKEY(BUSNO)REFERENCES BUS(BUSNO));

9
MYSQL>DESC RESERVATION;

5. CANCELLATION
CANCELLATION: CANCELLATION (PNRNO: STRING, DOJ: DATE, SEATNO: INTEGER,
CONTACTNO: STRING, STATUS: STRING)
MYSQL>CREATE TABLE CANCELLATION (PNRNOVARCHAR(10),DOJ DATE,SEATNO
INTEGER,CONTACT NO VARCHAR(15),STATUS VARCHAR(10),PRIMARYKEY(PNRNO),
FOREIGN KEY(PNRNO) REFERENCES RESERVATION(PNRNO));
MYSQL>DESC CANCELLATION;

10
Experiment-3
NORMALIZA
TION
Database normalization is a technique for designing relational database tables to minimize
duplication of information and, in so doing, to safeguard the database against certain types of logical
(or) structural problems, namely data anomalies. For example, when multiple instances of a given
piece of information occur in a table, the possibility exists that these instances will not be kept
consistent when the data within the table is updated, leading to a loss of data integrity. A table that is
sufficiently normalized is less vulnerable to problems of this kind, because its structure reflects the
basic assumptions for when multiple instances of the same information should be represented by a
single instance only.
Normalization: It is a process of analyzing the given relation schema sbased on their Functional
Dependencies (FDS) and primary key to achieve the properties
● Minimizing redundancy
● Minimizing insertion, deletion and update anomalies.

Functional Dependencies: A Functional dependency is denoted by X → Y between two sets of


attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a
relation state r of R.The constraint is for any two tuples t1andt2 in r if t1[X]=t2[X] then they have
t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of
component Y.
Normal forms:The process of normalization is based on the concept of normal forms, Each &every
normal form has its own set of properties & Constraints. A table / relation is said to be in normal
form if it satisfies all the properties of that normal form.
1 NF:The domain of attribute must include only atomic(simple, indivisible)values.

2 NF:A relation schema R is in2NF if it is in1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.

3 NF:A relation schema R is in 3NF if it Is in 2NF and for every FD X→A either of the following is
true
a. X is a Super-key of R.
b. A is a prime attribute of R.
In other words, if every nonprime attribute e is non-transitively dependent on primary key.

4 NF:A relation schema R is said to be in 4NF if for every multi-valued dependency X Yt hat holds
over R, one of following is true
a. X is subset or equal to (or) XY= R.
b. X is a super key.

5 NF:A Relation schema R is said to be 5 NFif for every join dependency{R1,R2...Rn} that holds
R, one the following is true
a. Ri=R for some i.
b. The join dependency is implied by the set of FD, over R in which the left side is
key of R.

BCNF(Boyce-Codd Normal Form):A relation schema R Is in BCNF if it is in3NF and satisfies an


Additional constraint that for every FD X →A,X must be a candidate key.

11
Experiment-4
PRACTICING DDL COMMANDS

AIM: Creating Tables and altering the Tables


DDL commands:
1. The Create Table Command:-it defines each column of the table uniquely. Each column has
minimum of three attributes, a name, data type and size.
Syntax: Create table<tablename>(<col1><datatype>(<size>),<col2><datatype>(<size>));
Ex: Create table Emp (emp no number(4) primary key, ename char(10));
2. Modifying the structure of tables:Alter command is used to add the column to the already
created table.
a) add new columns
Syntax: Altertable<tablename>add(<new_col><datatype(size),<new_col>datatype(size));
Ex: alter table emp add sal number(7,2);
3. Dropping a column from a table:
Syntax: Alter table<table name> drop column<col>;
Ex: alter table mp drop column sal;
4. Modifying existing columns: By using modify, we can change the data type of a particular
field Syntax: Alter table <table name> modify(<col><new datatype>(<new size>));
Ex: alter table emp modify ename varchar2(15);
5. Renaming the tables: It is used to change the tablename which was already created.
Syntax: Rename table <old table> to <new table>;
Ex: rename table emp to emp1;
6. Truncating the tables: This DDL will support to delete all the rows of a table for
permanent Syntax: Truncate table <table name>;
Ex: trunc table emp1;
7. Destroying tables :Drop command is used to destroy the existing table (or) a
view Syntax: Drop table <table name>;
Ex: drop table emp;
BUS:
MYSQL>DESC BUS;

MYSQL>ALTER TABLE BUS ADD(WEEK DAY VARCHAR(10));


MYSQL>DESC BUS;

12
MYSQL>ALTER TABLE BUS MODIFY BUS NO VARCHAR(20);
MYSQL>DESC BUS;

MYSQL> ALTER TABLE BUS DROP COLUMN BUSNO;


MYSQL>ALTER TABLE BUS DROP COLUMN COACHTYPE;
MYSQL>DESC BUS;

We cannot delete BUS NO column as it is used as PRIMARY KEY

13
MYSQL>RENAME TABLE BUS TO BUS1;
MYSQL> DESC BUS1;

MYSQL> TRUNCATE TABLE BUS;


MYSQL>TRUNCATE TABLE BUS1;

As we have renamed BUS table to BUS1 table it gives an error


MYSQL> DROP TABLE BUS1;

As we have used BUSNO as FOREIGN KEY we cannot delete BUS1 table


TICKET:
MYSQL>DESC TICKET;

MYSQL>ALTER TABLE TICKETADD DEPT_TIMEVARCHAR (6);


MYSQL>DESC TICKET;

14
MYSQL>ALTER TABLE TICKET MODIFY SEAT NO INT(5);
MYSQL>DESC TICKET;

MYSQL>ALTER TABLE TICKET DROP COLUMN TICKET NO;


MYSQL>ALTER TABLE TICKET DROP COLUMN
DEPT_TIME;
MYSQL>DESC TICKET;

15
We can not delete TICKET NO column as it is used as PRIMARY
KEY
MYSQL> RENAME TABLE TICKET TO TICKET1;
MYSQL>DESC TICKET1;

MYSQL> TRUNCATE TABLE TICKET;


MYSQL>TRUNCATE TABLE TICKET1;

As we have renamed TICKET table to TICKET1 table it gives an error


MYSQL> DROP TABLE TICKET;

16
As we have used TICKET NO as FOREIGN KEY we cannot deleteTICKET1table
PASSENGER:
MYSQL>DESC PASSENGER;

MYSQL>ALTER TABLE PASSENGERADD(CATEGORY VARCHAR(8));


MYSQL> DESC PASSENGER;

MYSQL>ALTER TABLE PASSENGER MODIFY CATEORY NUMERIC(10);


MYSQL> DESC PASSENGER;

17
MYSQL>ALTER TABLE PASSENGER DROP COLUMN PASSPORT ID;
MYSQL> DESC PASSENGER;

MYSQL> RENAME TABLE PASSENGER TO PASSENGER1;

18
MYSQL>TRUNCATE TABLE PASSENGER1;

MYSQL>DROP TABLE PASSENGER1;

We can delete passenger table because no PRIMARY KEY of passenger table is used as FOREIGN KEY

19
RESERVATION:
MYSQL>DESC RESERVATION;

MYSQL>ALTER TABLE RESERVATION ADD STATUS


CHAR(2); MYSQL> DESC RESERVATION;

MYSQL>ALTER TABLE RESERVATION MODIFY NO OF SEATS NUMERIC (10);


MYSQL> DESC RESERVATION;

20
MYSQL>ALTER TABLE RESERVATION DROP COLUMN NOOF SEATS
MYSQL> DESC RESERVATION;

MYSQL>RENAME TABLE RESERVATION TO RESERVATION1;


MYSQL> DESC RESERVATION1;

21
MYSQL>TRUNCATE TABLE RESERVATION1;
MYSQL> DESC RESERVATION1;

MYSQL>DROPTABLERESERVATION1;

As we have used PNR NO as FOREIGN KEY we cannot delete RESERVATION1 table


CANCELLATION:
MYSQL>DESC CANCELLATION;

22
MYSQL>ALTER TABLE CANCELLATION ADD BUSNO CHAR(2);
MYSQL>DESC CANCELLATION;

MYSQL>ALTER TABLE CANCELLATION MODIFY SEAT NO NUMERIC(10);


MYSQL>DESC CANCELLATION;

MYSQL>ALTER TABLE CANCELLATION DROP COLUMN SEATNO;


MYSQL>DESC CANCELLATION;

23
MYSQL>RENAME TABLE CANCELLATION TO CANCELLATION1;
MYSQL>DESC CANCELLATION1;

MYSQL>TRUNCATE TABLE CANCELLATION1;


MYSQL>DESC CANCELLATION;

MYSQL>DROP TABLE CANCELLATION;

24
25
Experiment-5

PRACTICING DML COMMANDS


AIM: DML Commands-to manipulate data of a database objects
1. Insert-Once a table is created the most natural thing to do is load this table with data
to be manipulated later.
Syntax: insert into<table name>(<col1>,<col2>) values(<exp>,<exp>);
2. Update–
a) Remove all rows
Syntax: delete from<table name>;
b) Removal of a specified rows
Syntax: delete from<table name>where<condition>;
3. Delete–
a) Updating all rows
Syntax: Update<table name>set<col>=<exp>,<col>=<exp>;
b) Updating selected records.
Syntax: Update<tablename>set<col>=<exp>,<col>=<exp>where<condition>;

BUS:
MYSQL>CREATE TABLE BUS(BUSNO VARCHAR(10) PRIMARYKEY,SOURCE
VARCHAR (15), DESTINATION VARCHAR (15), WEEKDAY VARCHAR (10));
MYSQL>INSERT INTO BUS VALUES('AP01', 'HYDERABAD', 'KARIMNAGAR',
’SUNDAY’);
MYSQL>INSERT INTO BUS VALUES ('AP02','DELHI','MUMBAI',’MONDAY’);
MYSQL>INSERT INTO BUS VALUES('AP03', 'CHENNAI', 'SRINAGAR',
’WEDNESDAY’);
MYSQL>INSERT INTO BUS VALUES ('AP04','BANGALORE','HYDERABAD',
’SUNDAY’);
MYSQL>INSERT INTO BUS VALUES('AP05', 'KARIMNAGAR', 'WARANGAL',
’FRIDAY’);

26
MYSQL>SELECT * FROM BUS;

MYSQL>UPDATE BUS SET DESTINATION=’NIZAMABAD’WHERE BUSNO=’AP01’;


MYSQL> SELECT * FROM BUS;

MYSQL>UPDATE BUS SET WEEKDAY=NULL;


MYSQL> SELECT * FROM BUS;

27
MYSQL>DELETE FROM BUS WHERE SOURCE='CHENNAI';
MYSQL>SELECT * FROM BUS;

PASSENGER:
MYSQL>CREATE TABLE PASSENGER(PNR_NONUMERIC(9)PRIMARYKEY,
TICKET_NO NUMERIC(9),NAME VARCHAR (15),AGE NUMERIC(4),SEX
CHAR(10),PPNO VARCHAR (15),CATEGORYVARCHAR (8));
MYSQL> INSERT INTO PASSENGER VALUES(1000,01,'ANITHA',35,'F',10,’A/C’);
MYSQL> INSERT INTO PASSENGER VALUES(2000,02,'HARITHA',30,'F',20,’NONA/C’);
MYSQL> INSERT INTO PASSENGER VALUES(3000,03,'SRILATHA',22,'F',30, ’A/C’);
MYSQL> INSERTINTOPASSENGERVALUES(4000,04,'CHAITANYA',25,'M',40, ’A/C’);
MYSQL> INSERT INTO PASSENGER VALUES(5000,05,'SAKETH',28,'M',50, ’NONA/C’);
MYSQL> INSERT INTO PASSENGER VALUES(6000,06,'ANIRUDH',27,'M',60,
’NONA/C’); MYSQL> SELECT * FROM PASSENGER;

28
MYSQL>UPDATE PASSENGER SET NAME=’RAJITHA’WHERE PNR_NO=’2000’;
MYSQL>SELECT* FROM PASSENGER;

MYSQL>UPDATE PASSENGER SET SEX=NULL;


MYSQL>SELECT * FROM PASSENGER;

29
MYSQL>DELETE FROM PASSENGER WHERE NAME='ANIRUDH';
MYSQL>SELECT * FROM PASSENGER;

TICKET:
MYSQL>CREATE TABLE TICKET(TICKET_NONUMERIC(9)PRIMARYKEY,
JOURNEY_DATE DATE, AGE NUMERIC(4), SEX VARCHAR(10),SOURCE
VARCHAR(10),ARRIVAL_TIME VARCHAR(6),DESTINATIONVARCHAR(10),
DEP_TIME VARCHAR(6));
MYSQL>INSERT INTO TICKET VALUES (1,’2010-01-01’,35,'F','HYDERABAD',9,
'KARIMNAGAR',23);
MYSQL>INSERT INTO TICKET VALUES (2,’2010-01-02’,30,'F','DELHI',5,'MUMBAI',18);
MYSQL>INSERT INTO TICKET VALUES(3, ’2010-01-03’, 22, 'F', 'CHENNAI', 6,
'SRINAGAR', 16);
MYSQL>INSERT INTO TICKET VALUES (4,’2010-01-04’,25,'M','BANGALORE',8,
'HYDERABAD',14);
MYSQL>INSERT INTO TICKET VALUES (5,’2010-01-05’,28,'M','KARIMNAGAR',5,
'WARANGAL',13);

30
MYSQL>SELECT * FROM TICKET;

MYSQL>UPDATE TICKET SET SOURCE=’NIZAMABAD’WHERE TICKET_NO=’1’;


MYSQL>SELECT * FROM TICKET;

MYSQL>UPDATE TICKET SET SEX=NULL;


MYSQL>SELECT * FROM TICKET;

31
MYSQL>DELETE FROM TICKET WHERE SOURCE='CHENNAI';
MYSQL>SELECT * FROM TICKET;

RESERVATION:
MYSQL>CREATE TABLE RESERVE (PNR_NONUMERIC(9),FOREIGN KEY(PNR_NO)
REFERENCES PASSENGER(PNR_NO), JOURNEY_DATE DATE, NO_OF_SEATS
NUMERIC(8), ADDRESS VARCHAR(40), CONTACT_NO NUMERIC(10), STATUS
CHAR(2));
MYSQL>INSERT INTO RESERVE VALUES (1000,'2010-02-1’,5,'RAMANTHPUR',
0123456789,'Y');
MYSQL>INSERT INTO RESERVE VALUES (2000,’2010-02-2’,2,'KPHB',1234567890,'Y');
MYSQL>INSERT INTO RESERVE VALUES(3000,’2010-02-3’, 3, 'DILSUKHNAGAR',
1234567809, 'Y');
MYSQL>INSERT INTO RESERVE VALUES (4000,’2010-02-4’,4,'TARNAKA',
1234123412,'Y');
MYSQL>INSERT INTO RESERVE VALUES (5000,’2010-02-5’, 5,'DDCOLONY',
1234512345,'Y');

32
MYSQL>SELECT * FROM RESERVE;

MYSQL>UPDATE RESERVE SET ADDRESS=’HYD’WHERE PNR_NO=’2000’;


MYSQL>SELECT * FROM RESERVE;

MYSQL>UPDATE RESERVE SET STATUS=NULL;


MYSQL>SELECT * FROM RESERVE;

33
MYSQL>DELETE FROM RESERVE WHERE JOURNEY_DATE='2010-02-2';
MYSQL>SELECT * FROM RESERVE;

CANCELLATION:
MYSQL>CREATE TABLE CANCELLATION(PNR_NO NUMERIC(9), FOREIGN
KEY(PNR_NO) REFERENCES PASSENGER(PNR_NO), JOURNEY_DATE DATE,
NO_OF_SEATSNUMERIC(8),ADDRESS VARCHAR(40),CONTACT_NONUMERIC(10),
STATUS CHAR(2));

MYSQL>INSERT INTO CANCELLATION VALUES (1000,'2010-02-1’,5,


'RAMANTHPUR',0123456789,'N');
MYSQL>INSERT INTO CANCELLATION VALUES (2000,’2010-02-2’,2,'KPHB',
1234567890,'N');
MYSQL>INSERT INTO CANCELLATION VALUES (3000,’2010-02-3’,3,
'DILSUKHNAGAR',1234567809,'N');
MYSQL>INSERT INTO CANCELLATION VALUES (4000,’2010-02-4’,4,'TARNAKA',
1234123412,'N');

34
MYSQL>INSERT INTO CANCELLATION VALUES (5000,’2010-02-5’,5,'DDCOLONY',
1234512345,'N');
MYSQL>SELECT * FROM CANCELLATION;

MYSQL>UPDATE CANCELLATION SET ADDRESS=’KARIMNAGAR’WHERE


PNR_NO=’2000’;
MYSQL>SELECT * FROM CANCELLATION;

MYSQL>UPDATE CANCELLATION SET STATUS=NULL;


MYSQL>SELECT * FROM CANCELLATION;

35
MYSQL>DELETE FROM CANCELLATION WHERE NO_OF_SEATS=’2';
MYSQL>SELECT * FROM CANCELLATION;

36
Experiment-6
Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT, Constraints etc.)

Query: A query with respect to DBMS relates to user commands that are used to interact with a database.
The query language can be classified into data definition language and data manipulation language.

Sub Query: Sub queries, or nested queries, are used to bring back a set of rows to be used by the parent
query. Depending on how the sub query is written,it can be executed once for the parent query or it can
be executed once for each row returned by the parent query.If the sub query is executed for each rowof
the parent, this is called a correlated sub query.

Correlated sub query: A correlated sub query can be easily identified if it contains any references to the
parent sub query columns in its WHERE clause. Columns from the sub query cannot be referenced
anywhere else in the parent query. The following example demonstrates a non-correlated sub query.

E.g. Select *From CUSTWhere'10/03/1990' IN(Select ODATE from ORDER Where CUST.CNUM=
ORDER CNUM)

Any:This operator will make inner query to return multiple rows, where from those rows, least value is
extracted & then sends that value for comparison at the condition of outer query.
Syntax: select select-list1from<TN><aliasname1>where(condition1<comparisonoperator)Any (select
select-list2 from <TN><alias name2> where <condition>

All: This operator also makes inner query to return multiple rows of which it selects the biggest value &
sends that value for comparison at the condition of outer query.
Syntax: select<select list>from<TN><aliasname1>where <condition (op)All>(select<selectlist>) from
<TN><alias name2> where <condition list>

IN:
Syntax:select<select-list>from<TN><aliasname>where<condition>IN(select<select-list1>from
<TN><aliasname2>where<condition>

Exists: This operator is used to co-related queries that returns those rows of outer query for which the
inner query condition get satisfied.
Syntax: select<select-list>from<TN><alias name>where Exists (select*from<TN><alias name> where
<condition>

Not Exists: This operator will return true for that condition which doesn’t get satisfy at inner query. If the
Condition becomes true it becomes false at the Boolean value & those rows will be avoided at retrieval.
Syntax: select <select-list> from <TN><alias name> where Not Exists (select * from <TN><alias
name> where <condition>

Union: It joins the rows returned by 2(or) more queries,by avoiding duplicates & arranging the rows in
ascending order.
MYSQL>SELECT SOURCE FROM BUS UNION SELECT SOURCE FROM TICKET;

Intersect: This operator will extract the common values which are found in the rows returned by 2(or)
more queries.
MYSQL>SELECT SOURCE FROM BUS INTERSECT SELECT SOURCE FROM TICKET;
Constraints: They are used to specify rules for the data in a table. Constraints are used to limit the type

37
of data that can go into a table.This ensures the accuracy and reliability of the data in the table.
Types of data constraints
NOTNULL-Ensures that a column cannot have a NULL value
UNIQUE - Ensures that all values in a column are different
PRIMARYKEY-A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
FOREIGNKEY-Prevents actions that would destroy links between tables
CHECK-Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATEINDEX-Used to create and retrieve data from the database very quickly

QUERIES

1) Display unique PNR_no of al lpassengers


MYSQL>SELECT DISTINCT(PNR_NO) FROM PASSENGER;

2) Display all the names of male passengers


MYSQL>SELECT NAME FROM PASSENGER WHERE SEX='M';

3) Display the ticket numbers and names of all the numbers


MYSQL>SELECT TICKET_NO,NAME FROM PASSENGER;

4) Find the ticket numbers of the passengers whose name start with ‘A’ and ends with ‘A’.
MYSQL>SELECT TICKET_NO FROM PASSENGER WHERE NAMELIKE'A%A';

38
5) Find the age of passengers whose age is between 30 and 45.
MYSQL>SELECT NAME FROM PASSENGER WHERE AGE BETWEEN 30 AND 45;

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


MYSQL>SELECT NAME FROM PASSENGER WHERE NAME LIKE'A%';

7) Display the sorted list of the passenger names.


MYSQL>SELECT NAME FROM PASSENGER ORDER BY NAME;

8) Display the Bus numbers that travel to Hyderabad or Warangal.


MYSQL>SELECT BUSNO FROM BUS WHERE DESTINATION=’HYDERABAD’OR
DESTINATION =’WARANGAL’;

9) Display the details of Passengers who are travelling either in AC or NON AC.
MYSQL>SELECT* FROM PASSENGER WHERE CATEGORY IN('A/C','NONA/C');`

39
Experiment-7
AIM: You are going to practice queries using Aggregate functions (Count,Sum,Avg,Max&Min) Group
By, Having & Creation & dropping of views.
Aggregate Operator:
SQL supports 5 aggregate operators, which can be applied on any column of a relation.
1. Count-It is used to count the number of unique columns (or) values in a given column.
Syntax: select count(*) from <TN>(alias name);
2. Sum-It is used to retrieve the sum of unique values of a given column.
Syntax select sum (column name) from<TN><alias name>where<where condition>;
3. Avg- It retrieves the average of all (unique) values in the given column.
Syntax: select Avg (column name) from <TN> <alias name>where<where condition>;
4. Max-It is used to find the maximum value of a given number
Syntax: select Max(Column name) from <TN> (alias name);
5. Min-It is used to find the minimum value of a given number.
Syntax: select Min(column name)from<TN>(alias number);

Group By & Having Clause:


Group By and having clause is used to group the related data into one& having is used to group
qualification.
Syntax: select select-list from from-list where condition Group By Group-list Having group-qualification;

QUERIES:
1. Write a Query to display the information present in the passenger and cancellation tables.
Hint: use Union Operator.
MYSQL>SELECT PNR_NO FROM PASSENGER UNION SELECTPNR_NO FROM
CANCELLATION;

2. Find number of tickets booked for each pnr_no using group by clause.Hint:Use Group By on
pnr_no
MYSQL>SELECT PNR_NO,COUNT(TICKET_NO)FROMPASSENGERSGROUPBY
PNR_NO;

40
3. Find the distinct PNR numbers that are present.
MYSQL>SELECT DISTINCT(PNR_NO) FROM PASSENGER RESERVE;

4. Find the Total number of cancelled seats.


MYSQL>SELECT COUNT(NO_OF_SEATS) FROM CANCELLATION;

View:
The view is a table whose rows are not explicitly stored in the database,but are computed as needed from
the view definition.
Creating &dropping of views:
● A view is a representation of one(or) more tables.
● To reduce reductant (duplicate) data to the main possible create allows the creation of an object
called a view.
● If a view is used to only look at table data and nothing done the view is called “read only view”.
Syntax: create view<view name>as select<col name>from <Table name>where col name=expression-
list group by <grouping creation> having condition

MYSQL>CREATE TABLE STUDENT(SID INT PRIMARY KEY,NAME VARCHAR(15),LOGIN VARCHAR(15),


AGE INT, GPA REAL);

MYSQL> INSERT INTO STUDENT VALUES(5000,‘Dave’, ‘Dave@cs’,19,3.3);


MYSQL>INSERTINTOSTUDENT VALUES(53650,‘Smith’,‘Smith@math’,19,3.8);
MYSQL> INSERT INTO STUDENT VALUES(53666, ‘Jones’, ‘jones@cs’,18,3.4);
MYSQL> INSERT INTO STUDENT VALUES(53688,‘Smith’, ‘smith@ee’,18,3.2);
MYSQL>INSERTINTOSTUDENT VALUES(53831,‘Madayan’,‘Madayan@music’,11,1.8);
MYSQL> INSERT INTO STUDENT VALUES(53832,‘Guldu’, ‘guldu@music’,12,2);

41
MYSQL>SELECT*FROMSTUDENT;

MYSQL>CREATE TABLE ENROLLED(SID INT,CID INT,GRADE VARCHAR(5),PRIMARY


KEY(SID,CID), FOREIGN KEY(SID) REFERENCES STUDENTS(SID));

MYSQL>INSERT INTO ENROLLED VALUES(53650,4,‘A’);


MYSQL>INSERT INTO ENROLLED VALUES(53666,3,‘B’);
MYSQL>INSER TINTO ENROLLED VALUES(53831,5,‘C’);
MYSQL>INSERT INTO ENROLLED VALUES(53832,2,‘B’);

MYSQL>SELECT*FROM ENROLLED;

42
MYSQL>CREATE VIEW BSTUDENTS(NAME,SID,COURSE) AS SELECTS.NAME,S.SID,E.CID
FROM STUDENTS S,ENROLLED E WHERE S.SID=E.SID AND E.GRADE= ‘B’;

MYSQL>SELECT * FROM BSTUDENT;

MYSQL>DROP VIEW BSTUDENT;

43
Experiment-8
TRIGGERS
Aim: Creation of insert trigger, delete trigger and update trigger.
MYSQL> CREATE TABLE BUS_TRIGGER(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');

MYSQL> CREATE TABLE BUS_AUDIT(ID INT NOT NULL


AUTO_INCREMENT,SOURCE VARCHAR(10)NOTNULL,CHANGEDON
DATE TIME DEFAULT NULL,ACTION VARCHAR(10) DEFAULT NULL,
PRIMARY KEY(ID));

i) UPDATE
MYSQL>DELIMITER$$
MYSQL>CREATE TRIGGER BEFORE_BUS_UPDATE
BEFORE UPDATE ON BUS_TRIGGER
FOR EACH ROW
BEGIN
INSERT INTO BUS_AUDIT
SET ACTION='UPDATE',
SOURCE=OLD.SOURCE,
CHANGED ON=NOW();
END $$

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

ii) INSERT
MYSQL>CREATE TRIGGER BEFORE_BUS_INSERT
BEFORE INSERT ON BUS_TRIGGER
FOR EACH ROW
BEGIN
INSERT INT BUS_AUDIT
SETACTION='INSERT',
SOURCE=NEW.SOURCE
, CHANGED ON=NOW();
END$$

MYSQL>INSERT INTO BUS VALUES('AP789','VIZAG',


'HYDERABAD', 30) $$

45
iii) DELETE
MYSQL>CREATE TRIGGER BEFORE_BUS_DELETE
BEFORE DELETE ON BUS_TRIGGER
FOR EACH ROW
BEGIN
DELETE FROM BUS_AUDIT
SETACTION=’DELETE’,
SOURCE=NEW.SOURCE
, CHANGED ON=NOW();
END $$

MYSQL>DELETE FROM BUS WHERE SOURCE=’HYDERABAD’


$$

46
Experiment-9
PROCEDURES
Aim: Creation of stored Procedures and Execution of Procedures and
Modification of Procedures.
EX1
DELIMITER$$
CREATE PROCEDURE BUS_PROC()
BEGIN
SELECT *FROM BUS;
END$$
CALL BUS_PROC()$$

EX2
CREATE PROCEDURES AMPLE()
BEGIN
DECLARE X INT(3);
SET X=10;
SELECT X;
END$$
MYSQL>CALL SAMPLE()$$

47
EX3
CREATE PROCEDURE SIMPLE_PROC (OUT PARAM1
INT) BEGIN
SELECT COUNT(*) INTO PARAM1 FROM BUS;
END$$
MYSQL>CALL SIMPLE_PROC(@A)$$
MYSQL> SELECT @A; END $$

48
Experiment-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.
Cursors
In MySQL,a cursor allows row-by-row processing of the result sets. A cursor is usedfor
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 SQLcommands
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
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;
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;
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;

49
If any row exists ,then the above statement fetches the next row and cursor pointer moves
ahead to the next row.
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_IDINT)
BEGIN DECLARE V_ID INT;
DECLARE V_NAME VARCHAR(20);
DECLAREV_FINISHEDINTEGERDEFAULT0;
DECLARE C1 CURSOR FOR SELECTSID,SNAME FROM STUDENTS
WHERE SID=IN_CUSTOMER_ID;
DECLARE CONTINUE HANDLER FOR NOTFOUND SETV_FINISHED=1;
OPEN C1;
STD:LOOP

FETCH C1 INTO V_ID,V_NAME;


IFV_FINISHED=1THEN LEAVESTD; END
IF;
SELECT CONCAT(V_ID,V_NAME);
END LOOP STD;
CLOSEC1;
END$$

50
51

You might also like