You are on page 1of 74

St.

PETER’S ENGINEERING COLLEGE


Department of Computer Science
Engineering

Data Base Management Systems


Laboratory
INSTRUCTOR LAB MANUAL

Class :II Year II Semester Regulation : R-18

Prepared By

Mrs.Hema Mrs.T.Rupa Rani


Assistant Professor Assistant Professor

Academic Year: 2019 -20

Department of Computer Science &


Engineering
Opp. Forest Academy, Kompally Road, Dullapally,
Maisammaguda, Medchal (M)
R.R.Dist., Hyderabad

1
INSTITUTE VISION

To promote quality education accessible to all sections of the society without


any discrimination of caste, creed, color, gender and religion and helps the students to
discover their true potential.

INSTITUTE MISSION

IM1 To provide and equip the stakeholders with knowledge, skills, social values,
ethics, scientific attitude and orientation for lifelong learning.

IM2 To create an environment conducive to inhabitating the total involvement and


participation.

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

To emerge as a centre for computer technology meeting the needs of society.

DEPARTMENT MISSION

DM1: To provide quality education towards academic and industry requirements.

DM2: To offer state-of-art infrastructure for research and professional skill


development through value added programs.

DM3: To promote student centric activities that encourage interpersonal skills

2
INDEX

SNO NAME OF PROGRAM Page No

1. Syllabus 4

2. Required Work 5

3. Program Education Objectives 6

4. Program out comes 6

5. Course Outcome – PO mapping 9

6. Course Outcomes – Lab experiments mapping 11

7. Concept Design with E-R Model 14

8. Relational Model 21

9. Normalization 25

10. practicing DDL commands 30

11. Practicing DML Commands 35


Querying(using ANY, ALL, IN, Exists, NOT EXISTS, UNION,
39
12. INTERSECT, Constraints etc.)
Queries using Aggregate functions, GROUP BY, HAVING and Creation
49
13. and dropping of Views.

14. Triggers 53

15. Procedures 54

16. Usage of Cursors 56

17. Additional programs 57

18. Implementation of Data and Built in Functions in SQL 58

19. Numeric Functions 61

20. Math Functions 63

21. Open Ended Lab Programs 64


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?

22. Viva Questions 65

3
CS407PC: DATABASE MANAGEMENT SYSTEMS LAB

B.TECH II Year II Sem. LTPC


0 0 31.5
Co-requisites:
Co-requisite of course “Database Management Systems”
Course Objectives:
Introduce ER data model, database design and normalization
Learn SQL basics for data definition and data manipulation

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

There will be homework assignments of about 10 programmatic/project scripts/memos, most


of which will involve programming. Assignments are due at the beginning of its theoretic
class on the date specified. Late assignments will receive 75% of full credit if they are handed
in within one week of the specified due date. After one week, no credit will be given or else
losing of credits is made in practice. There is no specific attendance policy for the course,
although it is expected that absences will leave the student unprepared for tests and
assignments. Tests will not be rescheduled except in extreme circumstances. However, the
lowest quiz grade will be dropped. Grades will be determined as follows:

Day – to- Day evaluation Marks 15 marks


Internal practical Examination 10 marks
Final Exam (University / External End Exam) 50 marks

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)

Program Educational Objective 1


Learn and Integrate: Graduates shall apply knowledge to solve computer science and
allied engineering problems with continuous learning.
Program Educational Objective 2
Think and Create: Graduates are inculcated with a passion towards higher education and
research with social responsibility.
Program Educational Objective 3
Communicate and Organize: Graduates shall pursue career in industry, empowered
with professional and interpersonal skills.

PROGRAM OUTCOMES (PO’S):

1. ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
2. PROBLEM ANALYSIS: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. DESIGN/DEVELOPMENT OF SOLUTIONS: Design solutions for complex
engineering problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Use research-based
knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions.
5. MODERN TOOL USAGE: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modelling to
complex engineering activities with an understanding of the limitations.
6. THE ENGINEER AND SOCIETY: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. ENVIRONMENT AND SUSTAINABILITY: Understand the impact of the
professional engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development.
8. ETHICS: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. INDIVIDUAL AND TEAM WORK: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
10. COMMUNICATION: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to

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.

PROGRAM SPECIFIC OUTCOMES (PSO’s):

PSO-1 APPLICATIONS OF COMPUTING DOMAIN AND RESEARCH: Able to use


the professional , managerial, interdisciplinary skill set , and domain specific tools,
in development processes , identify the research gaps , and provide innovative
solutions to them.

PSO-2 COMPETITIVE APPLICATIVE: An ability to succeed in competitive


examinations like GATE, TOEFL,GRE etc.

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:

Introduce ER data model , database design and normalization.


1
2 Learn SQL basics for data definition and data manipulation.
3 Learn using procedures, cursors and trigger for database application problems.

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

C227.1: Demonstrate the basic elements of a relational database management system.(Apply)

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)

PO3 Designing ER daigrams for complex problems(Level 3)


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.3: Design database schema for a given application and apply Normalization..( Create).

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)

PO1 Acquiring knowledge about Database languages(Level 2)

PO2 Analyzing the given problem statement(Level 3)


PO3 Developing the query for the given problem statement(Level3)
PO5 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)

C227.5: Declare and enforce integrity constraints on a database using RDBMS(Remember).

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:

S.N EXPERIMENT PO PSO CO PI Justification


o

1. PO2 PSO2 C227.1 3.8.1 Identifies what


2.7.2 data has to be
PO3
Concept Design with E-R Model persisted
9.6.1
PO9

2. PO1 PSO2 C227.2 1.2.2 Represents


relationships in
PO5 5.4.1
Relational Model a tabular
PO9 9.6.1 format.

3. PO2 PSO2 C227.3 2.6.3 To minimize


4.6.1 duplication of
PO4 4.6.2 information
Normalization PO5 and safe guard
5.4.2
database.
PO9 9.6.1

4. PO1 PSO2 C227.4 1.6.1 Creation of


databases,
PO2 2.6.3
tables and
Practicing DDL commands PO3 dropping
3.8.1
them.
PO9 9.6.1

5. PO1 PSO2 C227.4 1.6.1 Manages data


with in schema
PO2 2.6.3
object.
Practicing DML Commands
PO3 3.8.1

PO9 9.6.1

6. PO3 PSO2 C227.5 3.6.1 Retrieves


selected
Querying (using ANY, ALL, IN, PO4 4.6.4
information
Exists, NOT EXISTS, UNION,
INTERSECT, Constraints etc.) PO9 9.6.1 from a
relation.

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

8. PO3 PSO2 C227.6 3.8.3 Invoking an


action
PO4 4.4.3
Triggers (Creation of insert trigger, automatically.
delete trigger, update trigger) PO5 5.4.1

PO9 9.6.1

9. PO3 PSO2 C227.6 3.8.3 To Perform an


action
PO4 4.4.3
repeatedly
Procedures with different
PO5 5.4.1
values.
PO9 9.6.1

10 PO3 PSO2 C227.6 3.8.3 Defines the


result set.
PO4 4.4.3
Cursors PO5 5.4.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

2 PO1 PSO2 C227.4 1.6.1 Built in


Functions
PO2 2.6.3
Numeric Functions
PO9 9.6.1

3. PO1 PSO2 C227.4 1.6.1 Built in


Functions
PO2 2.6.3
Math Functions
PO9 9.6.1

Open Ended Lab Programs


1 PO3 PSO2 C227.6 3.8.3 Real world
needs.
PO4 4.4.3
Write a function to accept the
PO5 5.4.1
empno and return exp with
minimum 3 decimal? 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

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:

Definition: An entity-relationship (ER) diagram is a specialized graphic that illustrates the


interrelationships between entities in a database. (or)
The E-R model is a top-down approach to database design that is based on uniquely
identifiable object. It begins by identifying that are uniquely distinguishable called
entities and relationship among these entities.
Entity: It is a 'thing' in the real world with an independent existence. (or)
A real word object that can be distinguished from other objects is called an entity.
There are two types of entities:
1) Strong Entity
2) Weak Entity

Entity type: It is a collection (set) of entities that have same attributes.

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:

1. Rectangle (Strong entity set)

2. Ellipse (Attributes)

3.Rhombus (Relationship set)

4. Double Rectangle (Weak Entity set)

5. Undirected Line(Flow of Relationship)

6. Directed Line (Flow of Relationship)

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:

The attributes are:

i. Bus_No
ii. Source
iii. Destination
iv. Dep_Time

The E-R Model is as follows:

Dep_Time Destination

Bus_No Source

BUS

In the above figure Bus_No is the Primary Key

2. TICKET Entity:
The attributes are:
i. Ticket_No
ii. Journey_Date
iii. Age
iv. Sex
v. Source
vi. Destination

1
vii. Dep_Time

The E-R Model is as follows:

Sex

Age Source

Journey_Date Destination

Ticket_No Dep_Time

TICKET

In the above figure Ticket_No is the Primary Key

3. PASSENGER Entity:

The attributes are:


i. PNR_No
ii. Ticket_No
iii. Name
iv. Age
v. Sex
vi. PPNo

The E-R Model is as follows:

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

In the above figure PNR_No is the Foreign Key

5. CANCELLATION Entity:

The attributes are:

i. PNR_No
ii. Journey_Date
iii. No_Of_Seats
iv. Address
v. Contact_No
vi. Status

The E-R Model is as follows:

No_OF_Seat Address

Journey_Date Contact_No

Status
PNR_No
CANCELLATION

In the above figure PNR_No is the Foreign Key

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

The relationship between BUS Entity and PASSENGER Entity is strong


relationship. Because the two entities consists of primary keys. Here the two entities
are strong entities. So the relationship is strong relationship.

1
Relationship between PASSENGER Entity and RESERVATION Entity:

The following diagram depicts the relationship exists between PASSENGER


Entity and

RESERVATION Entity.

Name Age

Ticket_No Sex

PNR_No PPNo
PASSENGER

Takes

RESERVATION

PNR_No Status

Journey_Date Contact_No

No_Of_Seats Address

The relationship between PASSENGER Entity and RESERVATION Entity is


weak relationship. Because the one entity consists of primary key and another entity
consists of foreign key. Here the one entity is strong entity (single border rectangle)
and another entity is weak entity (double border rectangle). The relationship between
strong entity and weak entity is weak relationship.

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

The relationship between PASSENGER Entity and CANCELLATION Entity is


weak relationship.
Because the one entity consists of primary key and another entity consists of
foreign key. Here the one
entity is strong entity (single border rectangle) and another entity is weak entity
(double border rectangle).
The relationship between strong entity and weak entity is weak relationship.

2
WEEK 2: Relational Model

Represent all the entities (Strong, Weak) in tabular fashion. Represent


relationships in a tabular fashion. There are different ways of representing
relationships as tables based on the cardinality. Represent attributes as columns in
tables or as tables based on the requirement. Different types of attributes
(Composite, Multivalve and Derived) have different way of representation.

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.

1. BUS Entity Table:

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.

SQL> Select * from Bus;

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

2.TICKET Entity Table:

SQL> CREATE TABLE Ticket(Ticket_No NUMERIC(9) Primary


Key,Journey_date Date, Age NUMERIC(4),Sex varchar(10),Source
Varchar(10),Arrival_time varchar(6),Destination Varchar(10),Dep_time varchar(6));
Table created.
SQL> insert into Ticket values(1,’2010-01-01’,35,'F','Hyderabad',9,'Karimnagar',23);
1 row created.
SQL> insert into Ticket values(2,’2010-01-02’,30,'F','Delhi',5,'Mumbai',18);
1 row created.
SQL> insert into Ticket values(3,’2010-01-03’,22,'F','Chennai',6,'Srinagar',16);
1 row created.
SQL> insert into Ticket values(4,’2010-01-04’,25,'M','Bangalore',8,'Hyderabad',14);
1 row created.
SQL> insert into Ticket values(5,’2010-01-
05’,28,'M','Karimnagar',5,'Warangal',13); 1 row created.
SQL> Select * from Ticket;

Ticket_N Journey Age Sex Source Arrival_ Destinati Dep_Tim


o _date time on e
1 2010-01-01 5 F Hyderabad 9 Karimnagar 23
2 2010-01-02 30 F Delhi 5 Mumbai 18
3 2010-01-03 22 F Chennai 6 Srinagar 16
4 2010-01-04 25 M Bangalore 8 Hyderabad 14
5 2010-01-05 28 M Karimnagar 5 Warangal 13

3. PASSENGER Entity Table:

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),Category varchar (8));
Table created.
SQL> insert into Passenger values(1000,01,'Anitha',35,'F',10,’A/C’);
1 row created.
SQL> insert into Passenger values(2000,02,'Haritha',30,'F',20,’NONA/C’) ;
1 row created.
SQL> insert into Passenger values(3000,03,'Srilatha',22,'F',30, ’A/C’) ;
1 row created.
SQL> insert into Passenger values(4000,04,'Chaitanya',25,'M',40, ’A/C’) ;
1 row created.
SQL> insert into Passenger values(5000,05,'Saketh',28,'M',50, ’NONA/C’) ;
1 row created.
SQL> insert into Passenger values(6000,06,'Anirudh',27,'M',60, ’NONA/C’);
1 row created.
SQl> Select * from Passenger;

22
PNR_No Ticket_No Name Age Sex PPNO Category

1000 1 Anitha 35 F 10 A/C


2000 2 Haritha 30 F 20 NONA/C
3000 3 Srilatha 22 F 30 A/C
4000 4 Chaitanya 25 M 40 A/C
5000 5 Saketh 28 M 50 NONA/C
6000 6 Anirudh 27 M 60 NONA/C

4. RESERVATION Entity Table:

SQL> CREATE TABLE Reserve(PNR_No NUMERIC(9),foreign


key(PNR_No) references passenger(PNR_NO), Journey_date date, No_of_seats
number(8),Address Varchar(40),Contact_No NUMERIC(10),Status Char(2));
Table Created.
SQL> insert into reserve values(1000,'2010-02-01’,5,'Ramanthpur',0123456789,'Y');
1 row created.
SQL> insert into reserve values(2000,’2010-02-02’,2,'KPHB',1234567890,'Y');
1 row created.
SQL> insert into reserve values(3000,’2010-02-03’,3,'Dilsukhnagar',1234567809,'Y');
1 row created.
SQL> insert into reserve values(4000,’2010-02-04’,4,'Tarnaka',1234123412,'Y');
1 row created.
SQL> insert into reserve values(5000,’2010-02-
05’,5,'DDCOLONY',1234512345,'Y');
1 row created.

SQL> Select * from Reserve;


PNR_No Journey_date No_of_seats Address Contact_No Status
1000 2010-02-01 1 Ramanthpur 0123456789 Y
2000 2010-02-02 2 KPHB 1234567890 Y
3000 2010-02-03 3 Dilsukhnagar 1234567809 Y
4000 2010-02-04 4 Tarnaka 1234123412 Y
5000 2010-02-05 5 DDCOLONY 1234512345 Y

4. CANCELLATION Entity Table:

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),Status char(2));
Table Created.

SQL> insert into cancellation values(1000,'2010-01-


01',5,'Ramanthpur',0123456789,'N');
1 row created.
SQL> insert into cancellation values(2000,'2010-02-02',5,'KPHB',1234567890,'N'); 1
row created.

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

Database Normalization is a technique for designing relational database tables to


minimize duplication of
information and, in 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: 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.

2ND NORMAL FORM:

The relation is said to be in second normal form if and only if:


1. It is in the first normal form
2. No partial dependency exists between non-key attributes and key attributes.

Key Attributes:

In a given relationship if the attribute X uniquely defines all other attributes, then the
attribute

X is a key attribute.

In the above tables Bus_No, Ticket_No, PNR_No are key attributes.

Non-Key Attributes:

In a given relationship R, all the attributes which are not key attributes are called non-key

attributes. The remaining attributes are non-key attributes.

Let us visit again 1NF table.

 Bus_No is the key attribute for Bus


 Ticket_No is the key attribute for Ticket
 PNR_No is the key attribute for passenger
 Other attributes like name, age, sex, Journey_Dateetc are non-key attributes

To make the table 2NF we have to remove all the partial dependencies

 Source, Destination and Dep_Time depends only on Bus_No


 Journey_Date depends only on Ticket_No
 Ticket_No, Name, Age, Sex, PPNo depends on PNR_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

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

3RD NORMAL FORM:

A relation R is said to be in third normal form if and only if


1. It is in 2NF
2. No transitive dependency exists between non-key attributes and key attributes.

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.

1. Reservation status table

PNR_No Journey_Date Status


1 20-08-2016 Yes
3 30-08-2016 No
2 25-08-2016 Yes
4 05-09-2016 No

2. Reservation details table

PNR_No No_of_seats Address Contact_No


1 2 Anantapur 9003345678
3 1 Bangalore 9989892731
2 2 Hyderabad 9885252069
4 2 Kadapa 9247212345

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.

1. Cancellation status table

PNR_No Journey_Date Status


3 30-08-2016 No

2. Cancellation details table

PNR_No No_of_seats Address Contact_No


3 1 Bangalore 9989892731

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…

Example for creation of a table.

Create table passenger (passport id Integer primary key, name


char(50) null, age integer, Sex char);

Different types of commands in SQL:


A). DDL commands: - To create a database objects
B). DML commands: - To manipulate data of a
database objects C). DQL command: - To
retrieve the data from a database.
D). DCL/DTL commands: - To control the data of a database…
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 <table name> (<col1> <datatype>(<size>),<col2>
<datatype><size>));
Ex: Create table emp(empno integer(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:Alter table <tablename>add(<newcol><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 <tablename> drop column <col>;
Ex: alter table emp drop column sal;

4. Modifying existing columns: By using modify, we can change


the datatype of a particular field
Syntax: Alter table <tablename> modify <col> <newdatatype>(<newsize>);
Ex: alter table emp modify ename varchar(15);
5. Renaming the tables: It is used to change the table name which was
already created.
Syntax: Rename <oldtable> to <new table>;

Ex: rename emp to emp1;


6. Truncating the tables: This DDL will support to delete all the rows

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

Name Null? Type

BusNo varchar2(10)
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)

SQL> Alter table Bus modify (BusNo varchar(10));


Table Altered.
SQL> Alter table Bus drop column BusNo;
Table Altered.

SQL> desc Bus

Name Null? Type


Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)

SQL> Drop table bus;

Table Dropped.

SQL> Rename Bus to Bus1;

Table Renamed.

SQL> desc Bus1

3
Name Null? Type
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)

SQL> Truncate table bus;

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.

SQL> desc Passenger

Name Null? Type

PNR_No Not Null Number(9)


Ticket_No Number(9)
Name varchar2(15)
Age Number(4)
Sex Char(10)
PPNO varchar2(15)

SQL> Alter table Passenger add


(Category varchar (8)); Table Altered.
SQL> desc Passenger

Name Null? Type

PNR_No Not Null Number(9)


Ticket_No Number(9)
Name varchar(15)
Age Number(4)
Sex Char(10)
PPNO varchar(15)
Category varchar(8)

SQL> Alter table Passenger modify (PNR_No number(9));


Table Altered.

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)

SQL> Alter table Cancellation add (status char(2));


Table Altered.

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)
Status Char(2)

SQL> Alter table Cancellation modify (PNR_No number(9));


Table Altered.

SQL> Alter table Cancellation drop column PNR_No;


Table Altered.

SQL> desc Cancellation

Name Null? Type

Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)

SQL> Drop table Cancellation;

Table Dropped.

SQL> Rename Cancellation to Cancellation1;

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)

SQL> Truncate table Cancellation1;

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

INSERT – Insert data into the table

UPDATE – Updates existing data within the table

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;

Here A1,A2,……An are the attributes and P is the condition

Example:

 SQL> SELECT * FROM Bus;

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.

SQL> INSERT INTO tablenameVALUES(value list);


 To insert the multiple values into the table the following syntax is used.
SQL> INSERT INTO tablenameVALUES(&value1,&value2,………,valueN);

Example:

 SQL> INSERT INTO Bus VALUES (‘1AB’,’Hyderabad’,’Chennai’,’19:00’),


(‘76C’,’Kurnool’,’Warangal’,’05:30’),(‘8FR’,’Delhi’,’Jaipur’,’16:30’);

Values inserted in Bus table.

 SQL> INSERT INTO Cancellation VALUES (1,’2016-


0317’,2,’Hyderabad’,9974656891,’No’),
(2,’2016-04-26’,3,’Kurnool’,9654862661,’No’);

Values inserted in Cancellation table.

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.

Example: SQL> UPDATE tablename SET value WHERE condition;


 SQL> UPDATE Reservation_details SET Status=’Yes’ WHERE PNR_No=1;

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.

SQL> DELETE FROM tablename WHERE condition;

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…

Practice the following Queries:

1. Display unique PNR_no of all passengers.

SQL>SELECT PNR_No FROM Passenger;

Output:

2. Display all the name of male passengers.


SQL>SELECT Name FROM Passenger WHERE Sex=’M’;

Output:

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

SQL>SELECT Ticket_No, Name FROM Passenger;

Output:

4. Display the sorted list of passenger names.

SQL> SELECT * FROM Passenger ORDER BY NAME;

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:

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

SQL>SELECT Name FROM Passenger WHERE Age >=30 and Age <=50;

Output:

4
7. Display the bus numbers that travel on Sunday and Monday.

SQL>SELECT Bus_No FROM Bus WHERE Days IN (‘Tuesday’);

Output:

8. Display the source and the destination having journey time more than 10
hours.

SQL>SELECT Source, Destination FROM Bus WHERE Hours>=8;

Output:

4
9. Display the details of passengers who are travelling either in A/c or Non-A/c
(using in operator).

SQL> SELECT * FROM Passenger WHERE Service in(‘A/c’, ‘Non-A/c’);

Output:

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

SQL>SELECT Name FROM Passenger WHERE Name LIKE ‘a%%’;

Output:

4
11. Find the names of sailors who have reserved a red or a green boat.

SQL> SELECT S.sname


FROM Sailors S, Reserves R, Boats B
WHERE S.sicl = R.sid AND R.bid = B.bid AND B.color = 'red'
UNION
SELECT S2.sname
FROM Sailors S2, Boats B2, Reserves H2
WHERE S2.sid = H2.sid AND R2.bid = B2.bicl AND B2.color = 'green'

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 )

SQL> SELECT S.sname


FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R. bid IN (SELECT B.bid
FROM Boats B
WHERE B.color =

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

SQL> SELECT S.sname


FROM Sailors S
WHERE NOT EXISTS (( SELECT B.bid
FROM Boats B )
EXCEPT
(SELECT R. bid
FROM Reserves R
WHERE R.sid = S.sid ))

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.

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


and cancellation tables (using UNION operator).

SQL>SELECT PNR_No FROM Passenger UNION SELECT PNR_No FROM


Cancellation;
Output:

2. Display the number of days ina week on which the 9wo1 bus is available.

SQL>SELECT count(Days) FROM Bus WHERE Bus_No= ‘8FR’;

Output:

4
3. Find the distincet numbers that are present.

SQL>SELECT DISTINT PNR_No FROM Passenger;


Output:

4. Find the number of tickets booked for each pnr_no using GROUP B
CLAUSE (use

GROUP BY on pnr_no).

SQL>SELECT PNR_No, sum(No_of_seats) No_of_seats FROM


Reservation_details GROUP BY
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:

6. Find the total no of cancellation seats.

SQL>SELECT sum(No_of_seats) No_of_seats FROM Cancellation;

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

SQL> SELECT PNR_No, Name, sum(No_of_seats) No_of_seats, Service FROM


Passenger WHERE Service IN ('A/c','Non-A/c') GROUP BY Name, PNR_No, Service
HAVING sum(No_of_seats)>2;
Output:

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.

NOTE: Triggers can be used on only existing tables.

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.

Write a program to create stored procedures, execution of procedure


and modification
of procedure.

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;

FETCH cur INTO pnr, jdate, seats, address, pno, stat;


SELECT , jdate, seats, address, pno, stat;
CLOSE cur;
END //
DELIMITER ;
Output:
Procedure created
Call not_reserved();

5
Additional Programs

5
19.1 IMPLEMENTATION OF DATA AND BUILT IN FUNCTIONS IN SQL

CHARACTER/STRING FUNCTION:

SQL> select upper('welcome') from dual;

WELCOME

SQL> select upper('hai') from dual;

---

HAI

SQL> select lower('HAI') from dual;

LOW

---

hai

SQL> select initcap(‘hello world') from dual;

INITCAP('Hello

Hello World

SQL> select ltrim(' hai') from

dual; LTR

---

hai

SQL> select rtrim('hai ')from dual;


RTR

5
---

hai

SQL> select rtrim(' hai ')from dual;

RTRIM('

hai

SQL> select concat('JNTU',' university')from dual;

JNTU university

SQL> select length('JNTU’)from dual;

LENGTH('JNTU')

12

SQL> select replace('JNTU university', 'JNTU','SPEC')from dual;

SPEC university

SQL> select substr('JNTU', 7,6)from dual;

SUBSTR

5
lingam

SQL> select rpad('hai',3,'*')from dual;

RPAD('

hai***

SQL> select lpad('hai',3,'*')from dual;

LPAD('

***hai

SQL> select replace('Dany','y','ie')from dual;

REPLACE

Danie

SQL> select translate('cold','ld','ol')from dual;

TRANSL

cool

6
19.2 NUMERIC FUNCTION

SQL> select round(15.6789)from dual;


ROUND(15.6789)

16

SQL> select ceil(23.20)from dual;


CEIL(23.20)

24

SQL> select floor(34.56)from dual;


FLOOR(34.56)

34

SQL> select trunc(15.56743)from dual;


TRUNC(15.56743)

15

SQL> select sign(-345)from


dual; SIGN(-345)

-1

6
SQL> select abs(-70)from dual;

ABS(-70)

70

6
19.3 MATH FUNCTION:

SQL> select abs(45) from dual;

ABS(45)

45

SQL> select power(10,12) from dual;

POWER(10,12)

1.000E+12

SQL> select mod(11,5) from dual;

MOD(11,5)

SQL> select exp(10) from dual;

EXP(10)

22026.466

SQL> select sqrt(225) from dual;

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.

3. What is a Database system?

The database and DBMS software together is called as Database system.

4. Advantages of DBMS?

? Redundancy is controlled.

? Unauthorized access is restricted.

? Providing multiple user interfaces.

? Enforcing integrity constraints.

? Providing backup and recovery.

5. Disadvantage in File Processing System?

? Data redundancy & inconsistency.

? Difficult in accessing data.

? Data isolation.

? Data integrity.

? Concurrent access is not possible.

? Security Problems.

6
6. Describe the three levels of data

abstraction? Three levels of abstraction:

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

7. Define the "integrity

rules" There are two

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.

8. What is extension and intension?

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.

9. What is System R? What are its two major subsystems?

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.

Its two subsystems are

? Research Storage

? System Relational Data System.

10. How is the data structure of System R different from the relational

structure? Unlike Relational systems in System R


6
? Domains are not supported

? Enforcement of candidate key uniqueness is optional

? Enforcement of entity integrity is optional

? Referential integrity is not enforced

11. What is Data Independence?

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.

Two types of Data Independence:

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

NOTE: Logical Data Independence is more difficult to achieve

12. What is a view? How it is related to data independence?

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.

13. What is Data Model?

A collection of conceptual tools for describing data, data relationships data semantics and
constraints.

14. What is E-R model?

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.

16. What is an Entity?

It is a 'thing' in the real world with an independent existence.

17. What is an Entity type?

It is a collection (set) of entities that have same attributes.

18. What is an Entity set?

It is a collection of all entities of particular entity type in the database.

19. What is an Extension of entity type?

The collections of entities of a particular entity type are grouped together into an entity set.

20. What is Weak 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.

21. What is an attribute?

It is a particular property, which describes the entity.

22. What is a Relation Schema and a Relation?

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

23. What is degree of a Relation?

It is the number of attribute of its relation schema.

24. What is Relationship?

It is an association among two or more entities.

25. What is Relationship set?

The collection (or set) of similar relationships.

26. What is Relationship type?

Relationship type defines a set of associations or a relationship set among a given set of entity
types.

27. What is degree of Relationship type?

It is the number of entity type participating.

25. What is DDL (Data Definition Language)?

A data base schema is specifies by a set of definitions expressed by a special language called
DDL.

26. What is VDL (View Definition Language)?

It specifies user views and their mappings to the conceptual schema.

27. What is SDL (Storage Definition Language)?

7
This language is to specify the internal schema. This language may specify the mapping
between two schemas.

28. What is Data Storage - Definition Language?

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.

29. What is DML (Data Manipulation 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.

31. What is DML Compiler?

It translates DML statements in a query language into low-level instruction that the query
evaluation engine can understand.

32. What is Query evaluation engine?

It executes low-level instruction generated by compiler.

33. What is DDL Interpreter?

It interprets DDL statements and record them in tables containing metadata.

34. What is Record-at-a-time?

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.

35. What is Set-at-a-time or Set-oriented?

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.

36. What is Relational Algebra?

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.

37. What is Relational Calculus?

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.

38. How does Tuple-oriented relational calculus differ from domain-oriented


relational calculus

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.

39. What is normalization?

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

? Minimizing insertion, deletion and update anomalies.

40. What is Functional Dependency?

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 replace any dependency X A in F with a dependency Y A where Y is a proper


subset of X and still have a set of dependency that is equivalent to F.

? We cannot remove any dependency from F and still have set of dependency that is equivalent
to F.

42. What is multivalued dependency?

Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are


both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and
t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following
properties

? t3[x] = t4[X] = t1[X] = t2[X]

? t3[Y] = t1[Y] and t4[Y] = t2[Y]

? t3 [Z] = t2[Z] and t4[Z] = t1[Z]

Where [Z = (R-(X U Y)) ]

43. What is Lossless join property?

It guarantees that the spurious tuples generation does not occur with respect to relation
schemas after decomposition.

44. What is 1 NF (Normal Form)?

The domain of attribute must include only atomic (simple, indivisible) values.

45. What is Fully Functional dependency?

It is based on concept of full functional dependency. A functional dependency X Y is full


functional dependency if removal of any attribute A from X means that the dependency does
not hold any more.

46. What is 2NF?

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.

47. What is 3NF?

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.

48. What is BCNF (Boyce-Codd Normal Form)?

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.

49. What is 4NF?

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 subset or equal to (or) XY = R.

? X is a super key.

50. What is 5NF?

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.

You might also like