Professional Documents
Culture Documents
DATABASE MANAGEMENT
SYSTEMS LAB MANUAL
Dress Code:
Discipline in LAB
Fill columns & System No in the register & then only enter into lab
After end of the lab if any component is missing then the student has to be penalized.
Moving in and around the lab is strictly prohibited
If any student found chitchatting or misbehavior in lab then he/she must punished
Bags and mobiles are not allowed.
Keep keyboard, mouse and chair properly after completion of lab
To clarify doubts call the concerned lab faculty and don’t discuss with co friends
CSE-HOD
2
Index Page
Page Sign /
S. No. Date Program / Experiment
No. Remarks
2. Relational Model
Normalization
3.
8.
Triggers
9.
Procedures
3
INTRODUCTION:
Database:
“A Collection of data files (or) Collection of interrelated data (or) an individual enterprise (or) A
Collection of related files (Containing records) into different groups is known as Database”
Database System:
“It is a Collection of programs that are used to store the data, Manipulate the data & retrieve the
information”y
Advantages of DBMS:
Reduction of Redundancies
Data independence & efficient Access
Data integrity
Data Security
Reduced Application Development
Conflict Resolution
Data Administration
Concurrent Access
Crash Recovery
Disadvantages of DBMS:
Conversion costs
Installation & Management Cost
New Specialized Personnel
Need for Explicit Backup & Recovery
Security Breaches
4
Databases Lab
Objective:
This lab enables the students to practice the concepts learnt in the subject DBMS by
developing a database for an example company named “Roadway Travels” whose description is
as follows: The student is expected to practice the designing, developing and querying a database
in the context of example database “Roadway Travel”. Students are expected to use “Mysql”
database.
Roadways Travels:
“Roadway travels” is in business since 1997 with several buses connecting different places
in India .Its main office is located in Hyderabad.
Reservations:
Reservations are directly handled by booking office. Reservation can be made 60 days in
advance in either cash or credit .In Case the ticket is not available, a wait listed ticket is issued to
the customer. This ticket is confirmed against the cancellation.
5
EXPERIMENT- 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.
Example: Entities:
1. Bus
2. Ticket
3. Passenger
Primary key Attributes:
1. Ticket Id (Ticket Entity)
2. Passport Id (Passenger Entity)
A part from the above mentioned entities you can identify more. The above mentioned are few.
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.
6
The difference symbols which are used to draw E-R models:
2. Ellipse (Attributes)
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.
Example: Entities:
1. Bus
2. Ticket
3. Passenger
Primary key Attributes:
1. Ticket Id (Ticket Entity)
2. Passport Id (Passenger Entity)
Bus Attributes:
BusNo, Dept_time, Source, Destination, WeekDay
Ticket Attributes:
Ticket_No, Journey_Date, Source, Destination, Age, Arrival Time, Depature Time, SEX
7
Passenger Attributes:
Name, PNO_NO, Ticket_No, PPNO, SEX, Age
Reservation Attributes:
No_of_Seats, PNR_NO, Status, Journey_Date, Address, Contact_No
Cancellation Attributes:
No_of_Seats, PNR_NO, Waiting List, Status, Journey_Date, Address, Contact_No
Reading
PNR_NO
Relate the entities appropriately. Apply cardinalities for each relationship. Identify
Strong entities and Weak entities (if any). Indicate the type of relationships (total/Partial).
Try to incorporate generalization, Aggregation, Specialization etc. wherever required.
Bus NO Source
Bus Destination
Departure Time
8
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.
Strong Entity: It is the one that does not depend on other entities.
Weak Entity: It is the one that depends on other entities for existence.
Specialization: All the entities within an entity set do not share all the attributes.
Dept_time Source
BUS:
BUS Destination
BusNo
WeekDay
9
Passenger: PNR_NO Ticket_N
o
NAME Passenger
PPNO
Age SEX
RESERVATION:
PNR_NO
Status
No_of_Seats
Reservation Journey_Date
Contact_No ADDRESS
10
Cancellation
Status
No_of_Seats Cancellation
Journey_Date
Contact_No ADDRESS
Ticket:
TICKET_No Journey_Date
Source
SEX TICKET
Destination
Age
DEPATURE
TIME Arrival Time
11
EXPERIMENT- 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.
BUS:
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.
12
SQL> Select * from Bus;
BusNo Source Destination Weekday
----------- ------------- ------------------ ----------------
AP01 Hyderabad Karimnagar Sunday
AP02 Delhi Mumbai Monday
AP03 Chennai Srinagar Wednesday
AP04 Bangalore Hyderabad Sunday
AP05 Karimnagar Warangal Friday
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),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;
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
13
TICKET:
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,’01-jan-2010’,35,'F','Hyderabad',9,'Karimnagar',23);
1 row created.
SQL> insert into Ticket values(2,’02-jan-2010’,30,'F','Delhi',5,'Mumbai',18);
1 row created.
SQL> insert into Ticket values(3,’03-jan-2010’,22,'F','Chennai',6,'Srinagar',16);
1 row created.
SQL> insert into Ticket values(4,’04-jan-2010’,25,'M','Bangalore',8,'Hyderabad',14);
1 row created.
SQL> insert into Ticket values(5,’05-jan-2010’,28,'M','Karimnagar',5,'Warangal',13);
1 row created.
SQL> Select * from Ticket;
Ticket_No Journey_date Age Sex Source Arrival_time Destination Dep_Time
------------- ---------------- ------ ------ ----------- ----------------- -------------- --------------
1 01-jan-2010 35 F Hyderabad 9 Karimnagar 23
2 02-jan-2010 30 F Delhi 5 Mumbai 18
3 03-jan-2010 22 F Chennai 6 Srinagar 16
4 04-jan-2010 25 M Bangalore 8 Hyderabad 14
5 05-jan-2010 28 M Karimnagar 5 Warangal 13
RESERVATION:
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,'1-feb-2010’,5,'Ramanthpur',0123456789,'Y');
1 row created.
SQL> insert into reserve values(2000,’2-feb-2010’,2,'KPHB',1234567890,'Y');
1 row created.
SQL> insert into reserve values(3000,’3-feb-2010’,3,'Dilsukhnagar',1234567809,'Y');
1 row created.
SQL> insert into reserve values(4000,’4-feb-2010’,4,'Tarnaka',1234123412,'Y');
1 row created.
SQL> insert into reserve values(5000,’5-feb-2010’,5,'DDCOLONY',1234512345,'Y');
1 row created.
14
PNR_No Journey_date No_of_seats Address Contact_No Status
------------ -------------------- ------------------ ------------- ------------------ ----------
1000 1-feb-2010 1 Ramanthpur 0123456789 Y
2000 2-feb-2010 2 KPHB 1234567890 Y
3000 3-feb-2010 3 Dilsukhnagar 1234567809 Y
4000 4-feb-2010 4 Tarnaka 1234123412 Y
5000 5-feb-2010 5 DDCOLONY 1234512345 Y
CANCELLATION:
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,'1-Jan-2010',5,'Ramanthpur',0123456789,'N');
1 row created.
SQL> insert into cancellation values(2000,'2-feb-2010',5,'KPHB',1234567890,'N');
1 row created.
SQL> insert into cancellation values(3000,'3-feb-2010',4,'Dilsukhnagar',1234567809,'N');
1 row created.
SQL> insert into cancellation values(4000,'4-Apr-2010',2,'tarnaka',1234123412,'N');
1 row created.
SQL> insert into cancellation values(5000,'5-May-2010',6,'DDCOLONY',1234512345,'N');
1 row created.
SQL> Select * from Cancellation;
PNR_No Journey_date No_of_seats Address Contact_No Status
------------ -------------------- ------------------ ------------- ------------------ ----------
1000 1-jan-2010 5 Ramanthpur 0123456789 Y
2000 2-feb-2010 5 KPHB 1234567890 Y
3000 3-feb-2010 4 Dilsukhnagar 1234567809 Y
4000 4-Apr-2010 2 Tarnaka 1234123412 Y
5000 5-May-2010 6 DDCOLONY 1234512345 Y
15
EXPERIMENT- 3: Normalization:
Database normalization is a technique for designing relational database tables to minimize
duplication of information and, in so doing, to safeguard the database against certain types of
logical (or) structural problems, namely data anomalies. For example, when multiple instances of
a given piece of information occur in a table, the possibility exists that these instances will not be
kept consistent when the data within the table is updated, leading to a loss of data integrity. A
table that is sufficiently normalized is less vulnerable to problems of this kind, because its
structure reflects the basic assumptions for when multiple instances of the same information
should be represented by a single instance only.
Normalization: It is a process of 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.
Normal forms: The process of normalization is based on the concept of normal forms, Each &
every normal form has its own set of properties & Constraints. A table / relation is said to be in
normal form if it satisfies all the properties of that normal form.
1 NF : The domain of attribute must include only atomic (simple, indivisible) values.
2 NF: A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.
3 NF: A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the
following is true
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.
4 NF: 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
16
5 NF: 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.
Installation of MySql. In this week you will learn Creating Databases, How to create tables,
altering the database, dropping tables & databases if not required. You will also try
truncate, rename commands etc.
Create table passenger (passport id Integer primary key, name char(50) null, age integer,
Sex char);
17
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 varchar2(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 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.
18
SQL> desc Bus
Name Null? Type
------------------------------------------------- ------------------- -------------------------
Source varchar2(15)
Destination varchar2(15)
Weekday varchar2(10)
Table Dropped.
Table Renamed.
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.
19
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)
Category varchar2(8)
SQL> Alter table Passenger modify (PNR_No number(9));
Table Altered.
SQL> Alter table Passenger drop column PNR_NO;
Table Altered.
SQL> desc Passenger
Name Null? Type
------------------------------------------------- ------------------- -------------------------
Ticket_No Number(9)
Name varchar2(15)
Age Number(4)
Sex Char(10)
PPNO varchar2(15)
Category varchar2(8)
Table Dropped.
Table Renamed.
20
SQL> Truncate table passenger1;
Table Truncated.
TICKET:
21
SQL> desc Ticket
Name Null? Type
------------------------------------------------- ------------------- -------------------------
Journey_Date Date
Age Number(4)
Sex varchar2(10)
Source varchar2(10)
Arrival_Time varchar2(6)
Destination varchar2(10)
Dept_Time varchar2(6)
Table Dropped.
Table Renamed.
Table Truncated.
RESERVATION:
Table Created.
22
SQL> desc Reserve
Table Dropped.
Table Renamed.
23
SQL> desc Reserve1
Name Null? Type
------------------------------------------------- ------------------- -------------------------
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)
Table Truncated.
CANCELLATION:
24
SQL> Alter table Cancellation drop column PNR_No;
Table Altered.
Table Dropped.
Table Renamed.
Table Truncated.
25
EXPERIMENT- 5: Practicing DML commands:
1. Inserting Data into Tables: - once a table is created the most natural thing to do is load
this table with data to be manipulated later.
Syntax:
insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
2. Delete operations.
BUS:
SQL> CREATE TABLE BUS (BusNo varchar (10) primary key, Source varchar (15),
Destination varchar (15), Weekday varchar (10));
Table Created.
26
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.
1 row updated.
5 rows updated.
27
SQL> delete from bus where Source='Chennai';
1 row deleted.
PASSENGER:
Table created.
28
SQL> update Passenger set Name=’Rajitha’ where pnr_no=’2000’;
1 row updated.
6 rows updated.
1 row deleted.
29
TICKET:
5 rows updated.
30
SQL> Select * from Ticket;
1 row deleted.
RESERVATION:
Table Created.
31
SQL> Select * from Reserve;
5 rows updated.
32
5000 5-feb-2010 5 DDCOLONY 1234512345
CANCELLATION:
5 rows updated.
33
SQL> Select * from Cancellation;
PNR_No Journey_date No_of_seats Address Contact_No Status
------------ -------------------- ------------------ ------------- ------------------ ----------
1000 1-jan-2010 5 Ramanthpur 0123456789
2000 2-feb-2010 5 Karimnagar 1234567890
3000 3-feb-2010 4 Dilsukhnagar 1234567809
4000 4-Apr-2010 2 Tarnaka 1234123412
5000 5-May-2010 6 DDCOLONY 1234512345
34
EXPERIMENT-6: Querying:
In this week you are going to practice queries (along with sub queries) using ANY, All, In,
Exists, Not Exists, Union, Intersect, Constraints etc
Query: A query with respect to DBMS relates to user commands that are used to interact with a
data base. The query language can be classified into data definition language and data
manipulation language.
Sub Query: Sub queries, or nested queries, are used to bring back a set of rows to be used by the
parent query. Depending on how the sub query is written, it can be executed once for the parent
query or it can be executed once for each row returned by the parent query. If the sub query is
executed for each row of the parent, this is called a correlated sub query.
Correlated sub query: A correlated sub query can be easily identified if it contains any
references to the parent sub query columns in its WHERE clause. Columns from the sub query
cannot be referenced anywhere else in the parent query. The following example demonstrates a
non-correlated sub query.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE from ORDER Where
CUST.CNUM = ORDER.CNUM)
Any:
This operator will make inner query to return multiple rows, where from those rows, least value
is extracted & then sends that value for comparison at the condition of outer query.
All:
This operator also makes inner query to return multiple rows of which it selects the biggest value
& sends that value for comparison at the condition of outer query.
Syntax: select <select list> from <TN><alias name1>where<condition (op) All > (select<select
list>) from <TN><alias name2> where <conditionlist>
IN:
35
Exists:
This operator is used to co-related queries that returns those rows of outer query for which the
inner query condition get satisfied.
Not Exists:
This operator will return true for that condition which doesn’t get satisfy at inner query. If the
condition becomes true it becomes false at the Boolean value & those rows will be avoided at
retrieval.
Syntax: select <select-list> from <TN><alias name> where Not Exists(select * from<TN><alias
name> where <condition>
Union:
It joins the rows returned by 2 (or) more queries, by avoiding duplicates & arranging the rows in
ascending order.
SQL> select source from bus union select source from ticket;
Intersect:
This operator will extract the common values which are found in the rows returned by 2 (or)
more queries.
SQL> select source from bus intersect select source from ticket;
36
e) primary key constraint at table level.
Syntax:
Create table tablename(col=format,col=format
primary key(col1>,<col2>);
f) foreign key constraint at column level.
Syntax:
<col><datatype>(size>) references <tablename>[<col>];
g) foreign key constraint at table level
Syntax:
foreign key(<col>[,<col>])references <tablename>[(<col>,<col>)
h) check constraint
check constraint constraint at column level.
Syntax: <col><datatype>(size) check(<logical expression>)
i) check constraint constraint at table level.
Syntax: check(<logical expression>)
PNR_NO
------
1000
2000
3000
4000
5000
2) Display all the names of male passengers
NAME
---------------
chaitanya
saketh
TICKET_NO NAME
---------- ---------------
1 Anitha
2 haritha
37
3 Srilatha
4 chaitanya
5 saketh
4) Display the source and destination having journey time more than 10 hours.
5) Find the ticket numbers of the passengers whose name start with ‘A’ and ends with ‘H’.
TICKET_NO
----------
6
SQL> select name from passenger where age between 30 AND 45;
NAME
---------------
Anitha
Haritha
NAME
---------------
Anitha
Anirudh
NAME
---------------
Anirudh
Anitha
Srilatha
chaitanya
haritha
saketh
38
9) Display the Bus numbers that travel on Sunday and Wednesday.
39
EXPERIMENT-7: Querying
You are going to practice queries using Aggregate functions(Count, Sum, Avg, Max & Min)
Group By, Having & Creation & dropping of views.
Aggregate Operator:
SQL supports 5 aggregate operators, which can be applied on any column of a relation.
1. Count
2. Sum
3. Avg
4. Max
5. Min
1) Count: It is used to count the number of unique columns (or) values in a given column.
Syntax: select count (*) from <TN>(alias name);
3)Average(Avg): It retrieves the average of all (unique) values in the given column.
Syntax : select Avg (column name) from <TN> <alias name>where <where condition>
Syntax: select select-list from from-list where condition Groupby Group list Having group-
qualification;
View:
The view is a table whose rows are not explicity stored in the database, but are computed as
needed from the view definition.
40
Creating & dropping of views:
“view (or) virtual tables”
In the SQL Languages a view is a representation of one (or) more tables.
To reduce reductant (duplicate) data to the main possible create allows the creation of an
object called a view.
If a view is used to only look at table data and nothing done the view is called ”read only
view”.
1. Write a Query to display the information present in the passenger and cancellation
tables. Hint: use Union Operator
SQL> Select pnr_no from passenger union select pnr_no from cancellation;
Pnr_no
----------
1000
2000
3000
4000
5000
6000
3. Display the number of days in a week on which the 9w01 bus is available
41
4. Find number of tickets booked for each pnr_no using group by clause. Hint: Use Group
By on pnr_no
Pnr_no
----------
1000
2000
3000
4000
5000
6000
6. Find the number of tickets booked in each class where the number of seats is
greater than 1. Hint: Use Group by, Where & Having Clauses
8. Write a query to count the number of tickets for the buses, which traveled after the
date ‘14/3/2009’ Hint: Use Having Clauses
42
EXPERIMENT-8: Triggers
In this week you are going to work on triggers. Creation of insert trigger, delete trigger,
update trigger. Practice triggers using the above database
Triggers:
Example:
A trigger called check_sal which runs every time a new employee is getting inserted to enforce
some rules on what should be the minimum salary.
Elements in a Trigger:
Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
Trigger event: INSERT, UPDATE, OR DELETE
Table name: On table, view
Trigger Type: Row or statement
When clause: Restricting condition
Trigger body: PL/SQL block
43
Before triggers:
“Before triggers” execute the trigger body before the triggering DML event on a table. These are
frequently used to determine whether that triggering statement should be allowed to complete.
This situation enables you to eliminate unnecessary processing of the triggering statement and it
eventual rollback in cases where an exception is raised in the triggering action.
After triggers
“After triggers” are used when the triggering statement is to be completed before the triggering
action and to perform a different action on the same triggering statement if a BEFORE trigger is
already present.
Instead of Triggers
“Instead of Triggers” are used to provide a transparent way of modifying views that cannot be
modified directly through SQL DML statements because the view is not inherently modifiable.
You can write INSERT, UPDATE, and DELETE statements against the view. The INSTEAD
OF trigger works invisibly in the background performing the action coded in the trigger body
directly on the underlying tables.
Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering event. A
row trigger is not executed if the triggering event affects no rows.
Trigger Body:
The trigger body is a PL/SQL block or a call to a procedure.
Syntax:
44
EXPERIMENT-9: Procedures
In this session you are going to learn creation of stored procedure, execution of procedure
& modification of procedure. Practice procedures using the above database.
Stored Procedure:
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more
specific task. This is similar to a procedure in other programming languages. A procedure has a
header and a body. The header consists of the name of the procedure and the parameters or
variables passed to the procedure. The body consists or declaration section, execution section
and exception section similar to a general PL/SQL Block. A procedure is similar to an
anonymous PL/SQL Block but it is named for repeated usage.
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks. The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional. By using CREATE OR REPLACE
together the procedure is created if no other procedure with the same name exists or the existing
procedure is replaced with the current code.
45
The below example creates a procedure ‘employer_details’ which gives the details of the
employee.
procedure_name;
NOTE: In the examples given above, we are using backward slash ‘/’ at the end of the program.
This indicates the oracle engine that the PL/SQL program has ended and it can begin processing
the statements.
46
EXPERIMENT-10: Usage of Cursors
In this week you need to do the following: Declare a cursor that defines a result set.
Open the cursor to establish the result set. Fetch the data into local variables as needed
from the cursor, one row at a time. Close the cursor when done.
Cursors:
Every SQL statement executed by the Oracle server has an individual cursor associated with it
and are called implicit cursors.
There are two types of cursors.
Implicit cursors: Declared for all DML and PL/SQL SELECT statements.
Explicit cursors: Declared and names by the programmer.
Explicit Cursors:
o Individually process each row returned by a multiple row select statement.
o A PL/SQL program opens a cursor, processes rows returned by a query, and then closes
the cursor. The cursor marks the current position in the active set.
o Can process beyond the first row returned by the query, row by row.
o Keep track of which row is currently being processed.
o Allow the programmer to manually control explicit cursors in the PL/QL block.
o Declare the cursor by naming it and defining the structure of the query to be performed.
Within it.
o Open the cursor: The OPEN statement executes the query and binds the variables that are
referenced. Rows identified by the query are called the active set and are now available
for fetching.
o Fetch data from the cursor: After each fetch, you test the cursor for any existing row. If
there are no more rows to process, then you must close the cursor.
o Close the cursor: The CLOSE statement releases the active set of rows. It is now possible
to reopen the cursor to establish a fresh active set
47
Syntax:
Declaring a cursor:
CURSOR cursor_name IS
Select_statement;
Opening a cursor:
OPEN cursor_name;
Closing a cursor:
Close cursor_name;
Example:
Set SERVEROUTPUT ON
DECLARE
V_empno employees.employee_id%TYPE;
V_ename employees.last_name%TYPE;
CURSOR emp_cursor IS
SELECT employee_id, last_name
FROM employees;
BEGIN
OPEN emp_cursor;
FOR I IN 1..10 LOOP
FETCH emp_cursor INTO v_empno, b_ename;
DBMS_OUTPUT. PUT_LINE (TO_CHAR(v_empno) || ‘ ‘ || v_ename);
END LOOP
CLOSE emp_cursor;
Cursors can be passed parameters. Cursors also have FOR UPDATE option which allows more
fine grained control of locking at a table level. WHERE CURRENT OF can be used to apply the
update or delete operation to current row in the cursor.
48
DBMS viva-voce Questions
1. What is a database?
Ans: A database is a collection of related data. A database is a logically coherent collection of data with
some inherent meaning.
2. What is DBMS?
Ans: Database Management system is a collection of programs that enables user to create and maintain
a database.
3. What is a Catalog?
Ans: A catalog is a table that contains the information such as structure of each file, the type and storage
format of each data item and various constraints on the data. The information stored in the catalog is
called Metadata. Whenever a request is made to access a particular data, the DBMS s/w refers to the
catalog to determine the structure of the file.
4. How is the data stored in a database?
Ans: Data is stored in the form of tables.
5. What is a table?
Ans: A table is a collection of records. Record is also known as a Row.
6. What is a column/field?
Ans: It is known as an attribute which is a property of a table.
7. What is SQL?
Ans: Structured Query language.
8. What are the applications of databases?
Ans: Airlines, banking, universities, credit card transactions, tele communications, Finance, Sales etc.
9. In E-R Model what does the term E and R mean?
Ans: E means Entity and R means Relation.
10. In E-R model attributes are represented using Oval symbol.
11. In E-R model relations are represented using Rhombus symbol.
12. FPS stands for?
Ans: File Processing System.
13. What is data Redundancy?
Ans: Duplication of data is called data redundancy.
14. What is real time database technology?
Ans: These are all the techniques used in controlling industrial and manufacturing
processes.
15. What is program-data independence?
Ans: Unlike in the traditional file sys. the structure of the data files is stored in the
DBMS catalog separately from the access programs . This property is called
program-data independence.
16. What is ORDBMS?
Ans: Object oriented RDBMS is a relational DBMS in which every thing is treated as
objects. User can define operations on data as a part of the database definition.
17. What is program-operation independence?
Ans: An operation is specified in two parts.
1. Interface (operation name and data types of its arguments).
2. Implementation (the code part)
The implementation part can be changed without affecting the interface. This is called
program-operation independence.
18. What is a view?
Ans: A view may be a subset of the database or it may contain virtual data that is
derived from the database files but is not explicitly stored.
49
19. What are the different database models?
Ans: Flat model, Hierarchical models, Network model, Relational model and Dimensional model.
20. What is OLTP?
Ans: Online transaction processing is an application that involve multiple database accesses
from different parts of the world. OLTP needs a multi-user DBMS s/w to ensure that concurrent
transactions operate correctly.
21. What is the job of DBA?
Ans: A database administrator is a person or a group responsible for authorizing access to the
database, for coordinating and monitoring its use, and for acquiring s/w and h/w resources as needed.
22. Who are db designer?
Ans: Data base designers are responsible for identifying the data to be stored in the database and for
choosing appropriate structure to represent and store this data.
23. What are different types of end users?
Ans:
1. Casual end-users
2. Naive or parametric end users
3. Sophisticated end users
4. Stand alone users.
24. What are the advantages of using a dbms?
Ans:
1. Controlling redundancy.
2. Restricting unauthorized access.
3. Providing persistent storage for program objects and data structures.
4. Providing multi-user interfaces.
5. Representing complex relationships among data.
6. Enforcing integrity constraints.
7. Providing backups and recovery.
25. What are the disadvantages of using a dbms?
Ans:
1. High initial investments in h/w, s/w, and training.
2. Generality that a DBMS provides for defining and processing data.
3. Overhead for providing security, concurrency control, recovery, and integrity functions.
26. What is a data model?
Ans: It is a collection of concepts that can be used to describe the structure of a database. It provides
necessary means to achieve this abstraction. By structure of a database we mean the data types,
relations, and constraints that should hold on the data.
27. What are different categories of data models?
Ans:
1. High-level or conceptual data models.
2. Representational data models.
3. Low-level or physical data models.
High level data models provide the concepts that are close to the way many users perceive data.
Representational data models are provide concepts that provide the concepts that may be understood
by end users but that are not too far removed from organization of data in the database.
Physical data models describe the details of how data is stored in the computers.
28. What is schema?
Ans: The description of a data base is called the database schema, which is specified during database
design and is not expected to change frequently. A displayed schema is called schema diagram.
29. What is Instance of Database?
50
Ans: The collection of information stored in the database at a particular movement is called the Instance
of the Database.
30. What are types of schema?
Ans:
1. Internal schema defines physical storage structures.
2. Conceptual schema integrates external schema.
3. External schemas or user views.
31. What is Data independency?
Ans: Data independency is defined as the capacity to change the conceptual schema without having to
change the schema at the next higher level.
32. What are the types of Data Independency?
Ans: We can define two types of data independence:
1. Logical data independence (LDI).
2. Physical data independence (PDI).
LDI is the capacity to change the conceptual schema without having to change external schemas or
application programs.
PDI is the capacity to change the internal schema without having to change conceptual (or external)
schemas.
33. What are different DBMS languages?
Ans:
1. DDL (Data definition language)
2. DML (Data manipulation language)
3. DRL (Data Retrieval Language)
4. DCL (Data Control Language)
5. TCL (Transaction control language)
34. What are different types of DBMS?
Ans:
1. DBMS
2. RDBMS (Relational)
3. ORDBMS (Object Relational)
4. DDBMS (Distributed)
5. FDBMS (Federated)
6. HDDBMS (Homogeneous)
7. HDBMS (Hierarchical)
8. NDBMS (Networked)
35. What is an entity?
Ans: An entity is a thing in the real world with an independent existence.
36. What are attributes?
Ans: These are the particular properties that describe an entity.
37. What are diff. types of attributes?
Ans:
1. Composite Vs simple attributes.
2. Single valued Vs multi-valued attributes.
3. Stored Vs derived attribute.
4. Null valued attributes.
5. Complex attributes.
38. What is difference between entity set and entity type?
Ans:
Entity type: An entity type defines a collection of entities that have the same attributes.
Entity set: the collection of all entities of a particular entity type in the database at any point of time is
51
called Entity set.
39. What is domain value or value set of an attribute?
Ans: It is the set of values that may be assigned to that attribute for each individual entities
40. What is degree of a relationship?
Ans: The no of entities participating in that relation.
41. What is recursive relationship?
Ans: It is the relationship where both the participating entities belong to same entity type
42. What is cardinality ratio in DBMS?
Ans: The ration between total Participation and partial participation is called as Cardinality ration.
43. What are relationship constraints?
Ans:
1. Cardinality ratio.
2. Participation constraints.
44. What is a Participation constraint?
Ans: The participation constraint specifies whether the existence of an entity depends on its being
related to another entity via the relationship type. This is of two types:
1. Total participation.
2. Partial participation.
45. What is a weak entity types?
Ans: The entity types that do not have key attributes of their own are called weak entity types.
46. What is an ER Diagram?
Ans:
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.
47. What is meta data?
Ans: Data about the data is called meta data.
48. What is specialization?
Ans: It is the process of defining a set of subclasses of an entity type where each subclass contain all the
attributes and relationships of the parent entity and may have additional attributes and relationships
which are specific to itself.
49. What is generalization?
Ans: It is the process of finding common attributes and relations of a number of entities and defining a
common super class for them.
50. What is a ternary relationship?
Ans: A relationship with a degree 3 is called a ternary relationship.
51. What is aggregation and association?
Ans: Aggregation is an abstraction concept for building composite objects from their component
objects. The abstraction of association is used to associate objects from several independent classes.
52: What is RAID?
Ans: Redundant array of inexpensive (or independent) disks.
52
2. External hashing
3. Extendible hashing
4. Linear hashing
5. Partitioned hashing.
55. What are different types of relational constraints?
Ans:
1. Domain constraints
2. Key constraints
3. Entity integrity constraints
4. Referential integrity constraints
Domain constraints specify that the value of each attribute must be an atomic value from the domain of
the attributes.
Key constraints tell that no two tuples can have the same combination of values for all their attributes.
Entity integrity constraint states that no primary key value can be null.
Referential integrity constraints states that a tuple in one relation that refers to another relation must
refer to an existing tuple in that relation it is specified between two relations and is used to maintain the
consistency among tuples of the two relations.
56. What is a super key?
Ans: A superkey is defined as a set of attributes of a relation variable for which it holds that in all
relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for
the attributes in this set.
57. What is a Candidate Key?
Ans: Candidate key - A candidate key is a field or combination of fields that can act as a primary key field
for that table to uniquely identify each record in that table.
58. What is a Compound key?
Ans: Compound key (also called a composite key or concatenated key) is a key that consists of 2 or more
attributes.
59. What is a primary key?
Ans: A primary key is a value that can be used to identify a unique row in a table.
60. What is a foreign key?
Ans: A key of a relation schema is called as a foreign key if it is the primary key of some other relation to
which it is related to.
61. What is difference between a super key, a key, a candidate key and a primary key?
Ans: A super key specifies uniqueness constrain that no two distinct tuples in a state can have the same
value for the super key. Every relation has at least one default super key. A key is a minimal super key or
the subset of the super key which is obtained after removing redundancy. A relation schema may have
more than one key. In this case each key is called a candidate key. One of the candidate key with
minimum number of attributes is chosen as primary key.
62. What is a transaction?
Ans: A transaction is a logical unit of database processing that includes one or more
database access operations.
53
Ans:
1. Write_item(x)
2. Read_item(x)
54
Ans: Dead lock occurs when each transaction T in a set of two or more transactions is waiting for some
item that is locked by some other transaction T’ in the set. Hence each transaction is in a waiting queue,
waiting for one of the other transactions to release the lock on them.
55
It specifies user views and their mappings to the conceptual schema.
90. What is DML Compiler?
Ans: It translates DML statements in a query language into low-level instruction that the query
evaluation engine can understand.
91. What is Query evaluation engine?
Ans: It executes low-level instruction generated by compiler.
56
Ans: create table student(name varchar2(15), id number(7), branch varchar2(10));
107. How do you insert records into a table? Show with an example.
Ans: insert into student values(‘smith’ 100, ‘IT’);
108. What is truncate in DBMS?
Ans: It deletes all the records in the table. It results in an empty table.
109. What is drop?
Ans: It removes records and table.
110: What is delete statement?
Ans: The DELETE statement is used to delete rows in a table.
111. What is the difference between delete and drop?
Ans: After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make
the change permanent or to undo it.
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will
also be removed. No DML triggers will be fired. The operation cannot be rolled back.
112. What is ALTER statement used for?
Ans: It is used to modify a table.
113. What are the various DDL operations?
Ans: create, alter, truncate, drop
114. What are the various DML operations?
Ans: insert, delete, update
115. What is DRL?
Ans: DRL stands for data retrieval language.
116. What is DCL and what are its operations?
Ans: DCL stands for Data control language. Its operations are grant and revoke
117. What is Grant?
Ans: GRANT is a command used to provide access or privileges on the database objects to the users.
118. What is revoke?
Ans: The REVOKE command removes user access rights or privileges to the database objects.
119. What is TCL and what are its operations?
Ans: TCL stands fore Transaction Control Language. Its operations are Savepoint, Rollback and
Commit.
120. What is a Savepoint statement?
Ans: The SAVEPOINT statement names and marks the current point in the processing of a transaction.
121. What is Commit statement?
Ans: The COMMIT statement makes permanent any changes made to the database during the current
transaction.
122. What is Rollback Statement?
Ans: The ROLLBACK statement is the inverse of the COMMIT statement. It undoes some or all database
changes made during the current transaction.
123. Write a query to show the details of all the employees whose salaries is in the range 20,000 to
50,000$.
Ans: select * from emp where sal >=20,000 and sal <= 50,000
124. Write a query to list the employees whose name start with j and ends with s.
Ans: select * from emp where ename like ‘j%s’
125. What are SQL Aggregate functions?
Ans: SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
57
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
126. What is groupby statement?
Ans: The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset
by one or more columns.
127. What is orderby statement?
Ans: The GROUP BY statement is used in conjunction with the aggregate functions to group the resultset
by one or more columns.
128. What is a SQL join?
Ans: The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
129. What are different SQL joins?
Ans:
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables
130. What is inner join?
Ans: The INNER JOIN keyword return rows when there is at least one match in both tables.
131. What is a constraint? And what are the levels of constraints?
Ans: Constraint is the restriction on values that can be entered in a table. There are two levels of
constraints. 1. Column level 2. Table level.
132: What are the types of constraints?
Ans: We have three types of constraints.
1. Domain integrity constraint.
2. Entity integrity constraint
3. Referential constraint
133. What is column level constraint?
Ans: The constraint that is based on a single column and is applicable to that column only. All types of
constraints can be placed at column level.
134. What is table level constraint?
Ans: In table level constraint, the constraints can be placed on more than one column. All types of
constraints can be placed at Table level except NOT NULL.
135. What is the need for Locks in DBMS?
Ans: Locking is needed to allow only one user at a time to access the table. Other users are made to wait
until the lock is released.
136. What is a database trigger?
Ans: A database trigger is procedural code that is automatically executed in response to certain events
on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the
information on the database.
137. What is a Cursor?
Ans: A cursor comprises a control structure for the successive traversal (and potential processing) of
records in a result set. Database programmers use cursors for processing individual rows returned by
the database system for a query.
138. What is database Normalization?
Ans: Database normalization is the process of removing redundant data from your tables in to improve
storage efficiency, data integrity, and scalability.
139. What is 1st normal form?
58
Ans: First normal form (1NF) sets the very basic rules for an organized database:
Eliminate duplicative columns from the same table.
Create separate tables for each group of related data and identify each row with a unique column or set
of columns (the primary key).
140. What is 2nd Normal form?
Ans: In order to be in Second Normal Form, a relation must first fulfill the requirements to be in First
Normal Form. Additionally, each non-key attribute in the relation must be functionally dependent upon
the primary key.
141. What is 3rd Normal form?
Ans: In order to be in Third Normal Form, a relation must first fulfill the requirements to be in Second
Normal Form. Additionally, all attributes that are not dependent upon the primary key must be
eliminated.
142. What Boyce-Codd Normal Form (BCNF)?
Ans: A relation is in Boyce-Codd Normal Form (BCNF) if every determinant is a candidate key.
143. What is 4th Normal form?
Ans: To be in Fourth Normal Form, a relation must first be in Boyce-Codd Normal Form. Additionally, a
given relation may not contain more than one multi-valued dependency.
144. What is distributed database?
Ans: A distributed database is defined as collection of logically distributed database which are
connected with each other through a network. A distributed database management system is used for
managing distributed database. Each side has its own database and operating system.
145. What is centralized database?
Ans: A centralized database has all its data on one place. As it is totally different from distributed
database which has data on different places. In centralized database as all the data reside on one place
so problem of bottle-neck can occur, and data availability is not efficient as in distributed database.
146. What is Data fragmentation?
Ans: Data fragmentation occurs when a piece of data is not able to fit in (available) memory-slot as a
whole and is broken up into many pieces (that are not close together) so that each piece is able to fit the
available memory locations.
148. What is internal fragmentation?
Ans: Internal fragmentation occurs when storage is allocated without ever intending to use it. This space
is wasted. It is often accepted in return for increased efficiency or simplicity.
149. What is external fragmentation?
Ans: External fragmentation refers to the division of free storage into small pieces over a period of time,
due to an inefficient memory allocation algorithm, resulting in the lack of sufficient storage for another
program because these small pieces are not contiguous.
150. What is concurrency control?
Ans: Concurrency control mechanism ensures that correct results for concurrent operations are
generated, while getting those results as quickly as possible.
151. What is Two-Phase Commit?
Ans: Two-phase commit is mechanism that guarantees a distributed transaction either commits on all
involved nodes or rolls back on all involved nodes to maintain data consistency across the global
distributed database. It has two phases, a Prepare Phase and a Commit Phase.
152. What is data mining?
Ans: Data mining the process of extracting patterns from data.
153. What is data warehousing?
Ans: A data warehouse is a repository of an organization's electronically stored data. Data warehouses
are designed to facilitate reporting and analysis.
154. Differentiate between Data Mining and Data warehousing.
Ans: Data warehousing is merely extracting data from different sources, cleaning the data and storing it
59
in the warehouse. Where as data mining aims to examine or explore the data using queries.
155. What is data mart?
Ans: A data mart is a subset of an organizational data store, usually oriented to a specific purpose or
major data subject, which may be distributed to support business needs.
156. Explain the storage models of OLAP.
Ans: MOLAP Multidimensional Online Analytical processing - In MOLAP data is stored in form of
multidimensional cubes and not in relational databases.
60
166. What is Discrete and Continuous data in Data mining world?
Ans: Discrete data
- Only finite set of values are available ex: zip codes, no. of words etc.
- Integer variables are represented very often.
Continuous data
- Only real numbers are available – ex : height, weight, length, temperature
- Represents floating point variables.
61
Ans: An interrupt that can be turned off by the programmer is known as Maskable interrupt.
183. What is Non-Maskable interrupts?
Ans: An interrupt which can be never be turned off (ie. disabled) is known as Non-Maskable interrupt
184. What are the various segment registers in 8086?
Ans: Code, Data, Stack, Extra Segment registers in 8086.
185. What are the flags in 8086?
Ans: In 8086 Carry flag, Parity flag, Auxiliary carry flag, Zero flag, Overflow flag, Trace flag, Interrupt flag,
Direction flag, and Sign flag.
186. How many pins are there in 8086 micro processor?
Ans: 40 pins
62
63