Professional Documents
Culture Documents
Data Base Management Systems Laboratory: Department of Computer Science Engineering
Data Base Management Systems Laboratory: Department of Computer Science Engineering
Prepared By
1
INSTITUTE VISION
INSTITUTE MISSION
IM1 To provide and equip the stakeholders with knowledge, skills, social values,
ethics, scientific attitude and orientation for lifelong learning.
IM3 Provide infrastructure to arm the students with the competence to be at the
forefront of cutting edge technology and entrepreneurship in the highly
competitive global market.
DEPARTMENT VISION
DEPARTMENT MISSION
2
INDEX
1. Syllabus 4
2. Required Work 5
8. Relational Model 21
9. Normalization 25
14. Triggers 53
15. Procedures 54
3
CS407PC: DATABASE MANAGEMENT SYSTEMS LAB
Course Outcomes:
Design database schema for a given application and apply normalization
Acquire skills in using SQL commands for data definition and data manipulation.
Develop solutions for database applications using procedures, cursors and triggers
LIST OF EXPERIMENTS:
1. Concept design with E-R Model
2. Relational Model
3. Normalization
4. Practicing DDL commands
5. Practicing DML commands
6. Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION, INTERSECT,
Constraints etc.)
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and dropping
of Views.
8. Triggers (Creation of insert trigger, delete trigger, update trigger)
9. Procedures
10. Usage of Cursors
TEXT BOOKS:
1. Database Management Systems, Raghurama Krishnan, Johannes Gehrke, Tata Mc
Graw Hill, 3rd Edition
2. Database System Concepts, Silberschatz, Korth, McGraw Hill, V edition.
REFERENCES BOOKS:
1. Database Systems design, Implementation, and Management, Peter Rob & Carlos
Coronel 7th Edition.
2. Fundamentals of Database Systems, Elmasri Navrate, Pearson Education
3. Introduction to Database Systems, C.J. Date, Pearson Education
4. Oracle for Professionals, The X Team, S. Shah and V. Shah, SPD.
5. Database Systems Using Oracle: A Simplified guide to SQL and PL/SQL, Shah, PHI.
6. Fundamentals of Database Management Systems, M. L. Gillenson, Wiley Student Edition.
4
2. Required Work
At the minimum, traditional grading cutoffs will apply. That is, 90% is guaranteed an A, 87%
is guaranteed a B+, etc. Depending on class performance, some shifting of grades (in an
upward direction only) may occur as final letter grades are assigned.
5
PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
6
comprehend and write effective reports and design documentation, make effective
presentations, give and receive clear instructions.
11. PROJECT MANAGEMENT AND FINANCE: Demonstrate knowledge and
understanding of the engineering and 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.
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.
7
COURSE: DATABASE MANAGEMENT SYSTEMS LAB (CS407PC )
CLASS / SEM: II B. TECH. CSE / II SEM SECTION: A ,B & C A.Y: 2019-20
Course Objectives:
Course Outcomes:
After completion of this course the students will be able to
Course Bloom’s
Course Outcome Statement
Outcome Taxonomylevel
Demonstrate the basic elements of a relational database Apply
C227.1 management system.
Design entity relationship model and convert entity Create
C227.2 relationship diagrams in to RDBMS.
Design database schema for a given application and Create
C227.3
apply Normalization.
Acquire skills in using SQL commands for data definition Analyse
C227.4
and data manipulation.
Declare and enforce integrity constraints on a database using Remember
C227.5
RDBMS.
Develop solutions for database applications using Create
C227.6
procedures,cursors and triggers.
Faculty Incharge
8
COURSE: DATABASE MANAGEMENT SYSTEMS LAB ( CS407PC )
CLASS / SEM: II B. TECH. CSE / II SEM SECTION: A , B& C A.Y: 2019-20
NAME OF THE FACULTY: T.Rupa Rani
CO-PO MAPPING
PO PO PO PO PO PO PO PO PO PO PO PO PSO1 PSO2
1 2 3 4 5 6 7 8 9 10 11 12
C227.1 3 2 2 3 3
C227.2 2 3 2 3 3
C227.3 3 3 2 3 3
C227.4 2 3 3 3 2 3 3
C227.5 3 3 2 3 3
C227.6 2 3 3 2 3 3
C227 2.5 2.5 2.75 3 3 2 2 3 3
Justification
PO1 Identify the principles of RDMS(Level 3)
PO6 Identify and apply the Knowledge(Level 2)
PO9 Function effectively as an individual in finding solutions.(Level 2)
PSO1 Identify specific tools and solutions(Level 3)
PSO2 Succeeds in competitive exams like GATE,IES,GRE etc.(Level 3)
C227.2: Design entity relationship model and convert entity relationship diagrams into
RDBMS (Create)
Justification
Po2 Identifying ,Analysing and creating ER models and converting them into relations(Level 2)
Justification
PO3 Designing schema and normalizing(Level 3)
PO9 Function effectively as an individual in finding solutions to problems.
(Level 2)
PSO1 Use tools for the design and the analysis(Level 3)
9
PSO2 Succeeds in competitive exams likeGATE,IES,GRE etc. .(Level 3)
C227.4:Acquire skills in using SQL commands for data definition and data
manipulation.(Analyse)
PO4 Analyzing relations based on the given problem statement and applying integrity
constraints(Level 3)
PO5 Applying integrity constraints using Mysql tool(Level 3)
PO9 Function effectively as an individual in finding solutions to problems.
(Level 2)
PSO1 Identify specific tools and solutions(Level 3)
PSO2 Succeeds in competitive exams like GATE,IES,GRE etc. .(Level 3)
C227.6 Develop solutions for database applications using procedures,cursors and triggers(Create)
PO3 Analyzing the problem statement and developing solutions using procedures,cursors
and triggers (Level 2)
PO4 Developing solutions using procedures,cursors and triggers(level 3)
PO 5 Execution of Queries with Mysql tool(Level 3)
PO9 Function effectively as an individual in finding solutions to problems.(Level 2)
PSO1 Identify specific tools and solutions(Level 3)
PSO2 Succeeds in competitive exams like GATE,IES,GRE etc. .(Level 3)
Faculty Incharge
10
COURSE: DATABASE MANAGEMENT SYSTEMS LAB(CS407PC)
Class / Sem: II B. Tech. CSE / IISem Section: A, B & C A. Y.: 2019-20
Name of the Faculty: T .Rupa Rani
CO-POs/PSOs Mapping:
PO9 9.6.1
11
7. PO3 PSO2 C227.5 3.6.1 Queries using
Queries using Aggregate functions,
aggregate
GROUP BY, HAVING and PO4 4.6.4
function
Creation and dropping of
Views. PO9 9.6.1
PO9 9.6.1
PO9 9.6.1
Additional programs
1 PO1 PSO2 C227.4 1.6.1 Built in
Functions
Implementation of Data and Built in PO2 2.6.3
Functions in SQL
PO9 9.6.1
12
2 PO3 PSO2 C227.6 3.8.3 Real world
needs.
PO4 4.4.3
PO5 5.4.1
Write a function to accept a grade
and return the number of emps PO9 9.6.1
belongs to that grade?
3 PO3 PSO2 C227.6 3.8.3 Real world
needs.
PO4 4.4.3
PO5 5.4.1
Write a function to accept a PO9 9.6.1
character string and print it in case?
Faculty Incharge
13
WEEK 1: Concept Design with E-R Model
Analyze the problem carefully and come up with the entities in it. Identify what data 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.
E-R Model:
Entity set: It is a collection of all entities of particular entity type in the database.
Extension of entity type: The collections of entities of a particular entity type are grouped
together into an entity set.
Attribute: It is a particular property, which describes the entity.(or) Each entity &
relationship has a property called Attributes.
The difference symbols which are used to draw E-R models:
2. Ellipse (Attributes)
1
Super Key:
A Super Key of an entity set is a set of one (or) more attributes whose values uniquely
determine each entity.
Candidate Key:
A Candidate Key of an entity set is a minimal super key. For example:
1) Customer_Id is Candidate Key of Customer
2) Account_ Number is Candidate Key of Account
Primary Key:
Although several Candidate keys may exist, one of the Candidate keys is selected to be the
Primary Key.
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same
owner entity. It is sometime called as Discriminator.
The entities for the above company named “Roadway Travels” are as follows
1. Bus
2. Ticket
3. Passenger
4. Reservation
5. Cancellation
Now we will identify the attributes for each entity and construct the E-R Model.
1. BUS Entity:
i. Bus_No
ii. Source
iii. Destination
iv. Dep_Time
Dep_Time Destination
Bus_No Source
BUS
2. TICKET Entity:
The attributes are:
i. Ticket_No
ii. Journey_Date
iii. Age
iv. Sex
v. Source
vi. Destination
1
vii. Dep_Time
Sex
Age Source
Journey_Date Destination
Ticket_No Dep_Time
TICKET
3. PASSENGER Entity:
Name Age
Ticket_No Sex
PNR_No PPNo
PASSENGER
In the above figure PNR_No is the Primary Key and Ticket_No is Foreign
Key
4. RESERVATION Entity:
The attributes are:
i. PNR_No
ii. Journey_Date
iii. No_Of_Seats
iv. Address
v. Contact_No
vi. Status
1
The E-R Model is as follow:
No_Of_Seats
Address
Contact_No
Journey_Date
Status
PNR_No
RESERVATION
5. CANCELLATION Entity:
i. PNR_No
ii. Journey_Date
iii. No_Of_Seats
iv. Address
v. Contact_No
vi. Status
No_OF_Seat Address
Journey_Date Contact_No
Status
PNR_No
CANCELLATION
1
Relationship between BUS Entity and PASSENGER Entity:
The following diagram depicts the relationship exists between BUS Entity and
PASSENGER Entity.
Dep_Time Destination
Bus_No Source
BUS
Travel in
PASSENGER
PNR_No PPNo
Ticket_No Sex
Name Age
1
Relationship between PASSENGER Entity and RESERVATION Entity:
RESERVATION Entity.
Name Age
Ticket_No Sex
PNR_No PPNo
PASSENGER
Takes
RESERVATION
PNR_No Status
Journey_Date Contact_No
No_Of_Seats Address
1
Relationship between PASSENGER Entity and CANCELLATION Entity:
The following diagram depicts the relationship exists between PASSENGER Entity
and
CANCELLATION Entity.
Name Age
Ticket_No Sex
PNR_No PPNo
PASSENGER
Cancels
CANCELLATION
PNR_No Status
Journey_Date Contact_No
No_Of_Seats Address
2
WEEK 2: Relational Model
Relationship:-
It is defined as an association among several entities. A relationship can be one-to-
one, one-to-many (or) many-to-many.
A Collection of similar relationships is called a relationship set and is denoted by a
Rhombus.
• Unary Relationship---Where the association is within a single entity
• Binary Relationship---A relationship that associates two entities
• Ternary Relationship---A relationship that association three entities
• Quaternary Relationship—A relationship that associates with four entities
Attribute: It is a particular property, which describes the entity. (or) Each entity &
relationship has a property called Attributes.
1) Simple Attribute -- These attributes are also called as atomic attribute. These
cannot be subdivided further.
2) Composite Attributes -- An attribute which can be further divided into smaller
components are called Composite Attribute.
3) Single-Valued Attributes -- Certain Attribute take only a single value in all
instances.
4) Multi-Valued Attributes -- Attributes that can have more than one value at a
time for an instance.
5) Stored & Derived Attributes -- Some attributes need not be stored but can be
derived from available other attributes.
The following are the tabular representations of the entities used in this company.
SQL> CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar
(15), Destination varchar (15), Weekday varchar (10));
Table Created.
SQL> insert into Bus values('AP01','Hyderabad','Karimnagar',’Sunday’);
1 row created.
SQL> insert into Bus values('AP02','Delhi','Mumbai',’Monday’);
1 row created.
SQL> insert into Bus values('AP03','Chennai','Srinagar',’Wednesday’);
1 row created.
SQL> insert into Bus values('AP04','Bangalore','Hyderabad',’Sunday’);
1 row created.
SQL> insert into Bus values('AP05','Karimnagar','Warangal',’Friday’);
1 row created.
2
BusNo Source Destination Weekday
AP01 Hyderabad Karimnagar Sunday
AP02 Delhi Mumbai Monday
AP03 Chennai Srinagar Wednesday
AP04 Bangalore Hyderabad Sunday
AP05 Karimnagar Warangal Friday
22
PNR_No Ticket_No Name Age Sex PPNO Category
2
SQL> insert into cancellation values(3000,'2010-02-
03',4,'Dilsukhnagar',12345679,'N');
1 row created.
SQL> insert into cancellation values(4000,'2010-04-04',2,'tarnaka',1234123412,'N');
1 row created.
SQL> insert into cancellation values(5000,'2010-05-
05',6,'DDCOLONY',1234512345,'N');
1 row created.
SQL> Select * from Cancellation;
PNR_No Journey_date No_of_seats Address Contact_No Status
1000 2010-01-01 5 Ramanthpur 0123456789 Y
2000 2010-02-02 5 KPHB 1234567890 Y
3000 2010-02-03 4 Dilsukhnagar 1234567809 Y
4000 2010-04-04 2 Tarnaka 1234123412 Y
5000 2010-05-05 6 DDCOLONY 1234512345 Y
2
WEEK 3: NORMALIZATION
Normalization: Database designed based on the E-R model may have some amount of
inconsistency,
ambiguity and redundancy. To resolve these issues some amount of refinement is required.
This
refinement process is called normalization.
Let us now consider the “transportation table”.
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_N Journey_D Age Sex Source Destination Dep_Time
o ate
2345 20-08-2016 25 F Anantapur Kurnool 10:30am
5678 25-08-2016 20 M Hyderabad Chennai 07:00pm
2457 30-08-2016 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2016 28 F Kadapa Hyderabad 10:30pm
PASSENGER
PNR_No Ticket_No Name Age Sex PPNo
1 2345 Varuni 25 F 9003345678
2 5678 Rahul 20 M 9247212345
3 2457 Ajay 32 M 9989892731
4 4679 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Dat No_of_seats Address Contact_No Status
e
1 20-08-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No
2
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 1 Bangalore 9989892731 No
The above table shows the data file of the transportation in a table format. To reduce the
anomalies
normalization is applied
1ST NORMAL FORM:
A relation R is said to be in the first normal form (1NF) if and only if all the attributes
of the relation R are
atomic in nature.
Consider the Transportation table to reproduce the table. The following table shows
the table in 1NF.
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Da Age Sex Source Destination Dep_Time
te
2345 20-08-2016 25 F Anantapur Kurnool 10:30am
5678 25-08-2016 20 M Hyderabad Chennai 07:00pm
2457 30-08-2016 32 M Bangalore Hyderabad 12:30pm
4679 05-09-2016 28 F Kadapa Hyderabad 10:30pm
PASSENGER
PNR_No Ticket_No Name Age Sex PPNo
1 2345 Varuni 25 F 9003345678
2 5678 Rahul 20 M 9247212345
3 2457 Ajay 32 M 9989892731
4 4679 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 1 Bangalore 9989892731 No
2
In the new form, all the attributes are atomic, meaning that they are not further
decomposable.
Key Attributes:
In a given relationship if the attribute X uniquely defines all other attributes, then the
attribute
X is a key attribute.
Non-Key Attributes:
In a given relationship R, all the attributes which are not key attributes are called non-key
To make the table 2NF we have to remove all the partial dependencies
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date
2345 20-08-2016
5678 25-08-2016
2457 30-08-2016
4679 05-09-2016
2
PASSENGER
PNR_No Name Age Sex PPNo
1 Varuni 25 F 9003345678
2 Rahul 20 M 9247212345
3 Ajay 32 M 9989892731
4 Suni 28 F 9885252069
RESERVATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 1 Bangalore 9989892731 No
BUS
Bus_no Source Destination Dep_Time
1234 Anantapur Kurnool 10:30am
4567 Kadapa Hyderabad 10:30pm
1245 Hyderabad Chennai 07:00pm
3467 Bangalore Hyderabad 12:30pm
TICKET
Ticket_No Journey_Date
2345 20-08-2016
5678 25-08-2016
2457 30-08-2016
4679 05-09-2016
PASSENGER
PNR_No Name Age Sex PPNo
1 Varuni 25 F 9003345678
2 Rahul 20 M 9247212345
3 Ajay 32 M 9989892731
4 Suni 28 F 9885252069
RESERVATION
2
PNR_No Journey_Date No_of_seats Address Contact_No Status
1 20-08-2016 2 Anantapur 9003345678 Yes
3 30-08-2016 1 Bangalore 9989892731 No
2 25-08-2016 2 Hyderabad 9885252069 Yes
4 05-09-2016 2 Kadapa 9247212345 No
Here the reservation table is split into two tables in order to remove transitive
dependency. The following
tables shows the 3rd normal form.
CANCELLATION
PNR_No Journey_Date No_of_seats Address Contact_No Status
3 30-08-2016 1 Bangalore 9989892731 No
Here the cancellation table is split into two tables in order to remove transitive
dependency. The following
tables shows the 3rd normal form.
2
WEEK 4: Practicing DDL commands
Installation of MySQL. In this week you will learn creating databases. How to
create table altering
the database, dropping table and databases if not required. You will also try
truncate, rename
commands etc…
3
of a table for permanent
Syntax: Truncate table <tablename>;
Ex: trunc table emp1;
7. Destroying tables. Drop command is used to destroy the existing table (or) a view.
Syntax: Drop table <tablename>;
Ex: drop table emp;
BUS:
SQL> CREATE TABLE BUS (BusNo varchar (10) primary key,
Source varchar (15), Destination varchar (15));
Table Created.
SQL> desc Bus
Name Null? Type
BusNo varchar2(10)
Source varchar2(15)
Destination varchar2(15)
SQL> Alter table Bus add (Weekday varchar (10));
Table Altered.
SQL> desc Bus
BusNo varchar2(10)
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
Table Dropped.
Table Renamed.
3
Name Null? Type
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
Table Truncated.
PASSENGER:
SQL> CREATE TABLE Passenger(PNR_No NUMERIC (9) primary key,
Ticket_No Numeric(9),Name varchar (15),Age number(4),Sex Char(10),PPNO
varchar (15));
Table created.
CANCELLATION:
3
SQL> CREATE TABLE Cancellation(PNR_No NUMERIC(9), foreign key(PNR_NO)
references passenger(PNR_NO),Journey_date date,No_of_seats NUMERIC(8),
Address Varchar(40),Contact_No NUMERIC(10));
Table Created.
SQL> desc Cancellation
Name Null? Type
PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
PNR_No Number(9)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Table Dropped.
Table Renamed.
3
SQL> desc Cancellation1
Name Null? Type
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Table Truncated.
3
WEEK 5: Practicing DML Commands
DML Commands are used to for managing data within schema objects. Some
examples: SELECT
Retrieve data from the database
DELETE – Deletes all records from a table, the space for the records remain
1. SELECT Command:
The SELECT Command is used to retrieve data from the database. The syntax of the
command is as follows.
SELECT A1,A2,……,An
FROM Tablename WHERE P;
Example:
2.INSERT Command:
The INSERT Command is used to insert data into a relation, we either specify a tuple to be
3
inserted or write a
query whose result is a set of tuples to be inserted. The syntax is as follows.
To insert a single value into the table the following syntax is used.
Example:
3
3. UPDATE Command:
UPDATE Command is used to update the existing data within the table. In certain
situations we may wish to
change a value in a tuple (row) without changing all values in the table. For this purpose,
the update statement
can be used. The syntax of the command is as follows.
1 row updated.
3
4. DELETE Command:
DELETE Command is used to delete all records from a table, the space for the records
remain. The syntax of
the command is as follows.
Example:
SQL> DELETE FROM Cancellation WHERE PNR_No=1;
1 row deleted.
3
WEEK 6: Querying (using ANY, ALL, IN, Exists, NOT EXISTS, UNION,
INTERSECT, Constraints etc.)
In this week you are going to practice queries (along with sub queries) using ANY,
ALL,
IN, EXISTS, NOT EXISTS, UNION, INTERSECT, Constraints etc…
Output:
Output:
3
3. Display the ticket numbers and names of all the passengers.
Output:
Output:
4
5. Find the ticket numbers of the passengers whose name starts with ‘A’ and
ends with
‘A’.
SQL>SELECT Ticket_No FROM Passenger WHERE Name LIKE ‘a%%a’;
Output:
SQL>SELECT Name FROM Passenger WHERE Age >=30 and Age <=50;
Output:
4
7. Display the bus numbers that travel on Sunday and Monday.
Output:
8. Display the source and the destination having journey time more than 10
hours.
Output:
4
9. Display the details of passengers who are travelling either in A/c or Non-A/c
(using in operator).
Output:
Output:
4
11. Find the names of sailors who have reserved a red or a green boat.
12.Find the sids of all sailor's who have reserved red boats but not green boats.
SQL>SELECT S.sid
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'red'
EXCEPT
SELECT S2.sid
FROM Sailors S2, Reserves R2, Boats B2
WHERE S2.sid = R2.sid AND R2.bid = B2.bid AND B2.color = 'green'
4
13. Find the names of sailors who have reserved boat 103.(Using IN )
SQL>SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid = 103 )
14. Find the names of sailors 'who have reserved a red boat.( Using IN )
'red')
4
15. Find the names of sailors who have not reserved a red boat.(Using IN)
SQL>SELECT S.sname
FROM Sailors S
WHERE S.sid NOT IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN ( SELECT B.bid
FROM Boats B
WHERE B.color = 'red')
16. Find the names of sailors who have reserved boat number 103.(Using EXISTS)
SQL>SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103 AND R.sid = S.sid )
4
17. Find sailors whose rating is better than some sailor called Horatio. (Using ANY)
SQL>SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERES2.sname = 'Horatio' )
18. Find the Sailor's with the highest rating. (Using ALL)
SQL>SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2 )
4
19. Find the names of sailors who have reserved all boats.
4
WEEK 7: Querying (aggregate functions, GROUP BY, HAVING and Creation and
dropping of Views.)
You are going to practice queries using Aggregate Functions (COUNT, SUM, AVG,
MAX and MIN),
GROUP BY, HAVING and Creation and Dropping of Views.
2. Display the number of days ina week on which the 9wo1 bus is available.
Output:
4
3. Find the distincet numbers that are present.
4. Find the number of tickets booked for each pnr_no using GROUP B
CLAUSE (use
GROUP BY on pnr_no).
Output:
5
5. Write a query to count the number of tickets for the buses , which travelled
after the date 14/13/2009(use HAVING CLAUSES).
SQL> SELECT sum(No_of_seats) No_of_seats FROM Passenger WHERE
Journey_Date BETWEEN
‘2016-03-12’ AND ‘2016-05-23’ HAVING count(PNR_No)>=0;
Output:
Output:
5
7. Find the number of tickets booked in each class where the number of seats
is greater than 1 (use GROUP BY ,WHERE and HAVING VLAUSES).
5
WEEK 8: TRIGGERS
In this week you are going to work on Triggers. Creation of Insert Trigger, Delete
Trigger,
Update Trigger.
Practice Triggers using above database.
DELIMITER //
CREATE TRIGGER insert_trig BEFORE INSERT ON Passenger
FOR EACH ROW
BEGIN
IF NEW.Age<0 THEN
SET NEW.Age=0;
END IF;
END //
DELIMITER ;
Output:
Trigger created
Insert into Passenger values (4,4895, ‘Ajay’, 12, ‘M’, 9985642589, ‘A/c’, 3),( 5,5568,
‘Madhu’, -23, ‘F’,
8845623587, ‘Non-A/c’, 1);
The inserted Age -23 is inserted as 0.
5
WEEK 9 : Procedures
In this session you are going to learn Creation of stored procedure, execution of
procedure and
modification of procedure. Practice procedures using above database.
DELIMITER / /
CREATE PROCEDURE p1 ()
BEGIN
SELECT Ticket_No, Name, Ph_no FROM Passenger WHERE
No_of_seats>2;
END //
DELIMITER ;
Output:
Procedure created
Call p1();
5
DELIMITER //
CREATE PROCEDURE p2 (IN n varchar (20))
BEGIN
SELECT Ticket_No, PNR_No, Age, Ph_no FROM Passenger WHERE Name=n;
END //
DELIMITER ;
Output:
Procedure created
Call p2(‘Anita’);
5
WEEK 10: Cursors
In this week you need to do the following: Declare a cursor that defines the result set. Open
the cursor
that establishes the result set. Fetch the data into local variables as needed from the cursor,
one row at a
time. Close the cursor when done.
Write a program for declare a cursor that defines a resultset .Open the cursor to establish the
resultset.
Fetch the data into local variable as needed from the cursor ,one row at a time.Close the
cursor when
done.
DELIMITER //
CREATE PROCEDURE not_reserved ()
BEGIN
DECLARE pnr, seats, pno numeric;
DECLARE jdate date;
DECLARE address, stat varchar (20);
CREATE cur CURSOR FOR SELECT * FROM Reservation_details WHERE Status=
‘No’;
OPEN cur;
5
Additional Programs
5
19.1 IMPLEMENTATION OF DATA AND BUILT IN FUNCTIONS IN SQL
CHARACTER/STRING FUNCTION:
WELCOME
---
HAI
LOW
---
hai
INITCAP('Hello
Hello World
dual; LTR
---
hai
5
---
hai
RTRIM('
hai
JNTU university
LENGTH('JNTU')
12
SPEC university
SUBSTR
5
lingam
RPAD('
hai***
LPAD('
***hai
REPLACE
Danie
TRANSL
cool
6
19.2 NUMERIC FUNCTION
16
24
34
15
-1
6
SQL> select abs(-70)from dual;
ABS(-70)
70
6
19.3 MATH FUNCTION:
ABS(45)
45
POWER(10,12)
1.000E+12
MOD(11,5)
EXP(10)
22026.466
SQRT(225)
15
6
Open Ended Programs
1. Write a function to accept the empno and return exp with minimum 3 decimal?
2. Write a function to accept a grade and return the number of emps belongs to that grade?
3. Write a function to accept a character string and print it in case?
6
Viva Questions
6
1. What is database?
A database is a logically coherent collection of data with some inherent meaning, representing
some aspect of real world and which is designed, built and populated with data for a specific
purpose.
2. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
4. Advantages of DBMS?
? Redundancy is controlled.
? Data isolation.
? Data integrity.
? Security Problems.
6
6. Describe the three levels of data
? Physical level: The lowest level of abstraction describes how data are stored.
? Logical level: The next higher level of abstraction, describes what data are stored in database
and what relationship among those data.
? View level: The highest level of abstraction describes only part of entire database.
Integrity rules.
? Entity Integrity: States that? Primary key cannot have NULL value?
? Referential Integrity: States that? Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
Extension -It is the number of tuples present in a table at any instance. This is time dependent.
Intension -It is a constant value that gives the name, structure of table and the constraints laid
on it.
System R was designed and developed over a period of 1974-79 at IBM San Jose Research
Center. It is a prototype and its purpose was to demonstrate that it is possible to build a
Relational System that can be used in a real life environment to solve real life problems, with
performance at least comparable to that of existing system.
? Research Storage
10. How is the data structure of System R different from the relational
Data independence means that? The application is independent of the storage structure and
access strategy of data? In other words, the ability to modify the schema definition in one
level should not affect the schema definition in the next higher level.
? Physical Data Independence: Modification in physical level should not affect the logical
level.
? Logical Data Independence: Modification in logical level should affect the view level.
A view may be thought of as a virtual table, that is, a table that does not really exist in its own
right but is instead derived from one or more underlying base table. In other words, there is no
stored file that direct represents the view instead a definition of view is stored in data
dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate
users from the effects of restructuring and growth in the database. Hence accounts for logical
data independence.
A collection of conceptual tools for describing data, data relationships data semantics and
constraints.
This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.
6
15. What is Object Oriented model?
This model is based on collection of objects. An object contains values stored in instance
variables with in the object. An object also contains bodies of code that operate on the object.
These bodies of code are called methods. Objects that contain same types of values and the
same methods are grouped together into classes.
The collections of entities of a particular entity type are grouped together into an entity set.
An entity set may not have sufficient attributes to form a primary key, and its primary key
compromises of its partial key and primary key of its parent entity, then it is said to be Weak
Entity set.
6
A relation Schema denoted by R (A1, A2,…?, An) is made up of the relation name R and the
list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation
which contains set tuples (t1, t2, t3... tn). Each tuple is an ordered list of n-values t= (v1, v2...
vn).
Relationship type defines a set of associations or a relationship set among a given set of entity
types.
A data base schema is specifies by a set of definitions expressed by a special language called
DDL.
7
This language is to specify the internal schema. This language may specify the mapping
between two schemas.
The storage structures and access methods used by database system are specified by a set of
definition in a special type of DDL called data storage-definition language.
This language that enable user to access or manipulate data as organized by appropriate data
model.
? Procedural DML or Low level: DML requires a user to specify what data are needed and how
to get those data.
? Non-Procedural DML or High level: DML requires a user to specify what data are needed
without specifying how to get those data.
It translates DML statements in a query language into low-level instruction that the query
evaluation engine can understand.
The Low level or Procedural DML can specify and retrieve each record from a set of records.
This retrieve of a record is said to be Record-at-a-time.
7
The High level or Non-procedural DML can specify and retrieve many records in a single
DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.
It is procedural query language. It consists of a set of operations that take one or two relations
as input and produce a new relation.
It is an applied predicate calculus specifically tailored for relational databases proposed by E.F.
Codd. E.g. of languages based on it are DSL ALPHA, QUEL.
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are
tuples of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the
underlying domains instead of over relation. E.g. ILL, DEDUCE.
It is a process of analysing the given relation schemas based on their Functional Dependencies
(FDs) and primary key to achieve the properties
? Minimizing redundancy
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 t1 and t2 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.
7
41. When is a functional dependency F said to be minimal?
? Every dependency in F has a single attribute for its right hand side.
? We cannot remove any dependency from F and still have set of dependency that is equivalent
to F.
It guarantees that the spurious tuples generation does not occur with respect to relation
schemas after decomposition.
The domain of attribute must include only atomic (simple, indivisible) values.
7
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is
true
? X is a Super-key of R.
? A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for
every FD X A, X must be a candidate key.
A relation schema R is said to be in 4NF if for every multivalued dependency X Y that holds
over R, one of following is true
? X is a super key.
A Relation schema R is said to be 5NF if for every join dependency {R1, R2... Rn} that holds
R, one the following is true
? Ri = R for some i.
? The join dependency is implied by the set of FD, over R in which the left side is key of R.