You are on page 1of 63

MRIET

DATABASE MANAGEMENT
SYSTEMS LAB MANUAL

SVSV PRASAD SANABOINA


Assoc. Professor
CSE Department
Department of CSE
LAB INSTRUCTIONS
Timings:

 Students should enter into LAB as per Time-Table


 They should sign for each time they come to lab
 Grace time is 15 min. only.
 After 15 minutes automatically the first period of Lab periods is observed as ABSENT

Observations & Records:

 Observation book is compulsory for every lab.


 20 minutes before the end of lab time student must take signature of concerned lab in
charge in their observation.
 From the first lab onwards the student should maintain record books and have to write the
corresponding experiment.
 Write the experiment date and page no in both record and observation books

Dress Code:

 Students with formal dresses are only allowed.


 ID cards are compulsory.

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

1. Concept design with E-R


Model

2. Relational Model

Normalization
3.

Practicing DDL commands


4.

5. Practicing DML commands

6. Querying (using ANY, ALL,


IN…)

7. Queries using Aggregate


functions

8.
Triggers

9.
Procedures

10. Usage of Cursors

INTERNAL EXAMINER HOD EXTERNAL EXAMINER

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:

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

Database Management 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.

The company wants to computerize its operations in the following areas.


1) Reservation
2) Ticketing
3) Cancellation

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.

Cancellation and Modifications:


Cancellations are also directly handed at the booking office. Cancellation charges will be
charged. Wait listed tickets that do not get confirmed are fully refunded.

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:

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)

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

ER diagrams often use symbols to represent three different types of information.

1) Boxes are commonly used to represent entities.


Bus

2) Diamonds are normally used to represent relationships

Reading

3) Ovals are used to represent attributes.

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.

Generalization: Generalization is a special case of specialization.


The high level entity is called Super Class & low-level entity is called a Sub Class.
Aggregation: The drawback of ER diagrams is that can not show the relationship among
relationship.

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

PNR_NO Waiting list

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.

SQL> Select * from Reserve;

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.

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


of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can
form a relation state r of R. The constraint is for any two tuples 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.

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

 X is subset or equal to (or) XY = R.


 X is a super key.

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.

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.

EXPERIMENT- 4: Installation of MySql and practicing DDL Commands:

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.

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 number(4) primary key, ename char(10));
2. Modifying the structure of tables: Alter command is used to add the column to the already
created table.
a) add new columns
Syntax: Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));
Ex: alter table emp add(sal number(7,2));
3. Dropping a column from a table:
Syntax: Alter table <tablename> drop column <col>;
Ex: alter table emp drop column sal;

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)

SQL> Drop table bus;

Table Dropped.

SQL> Rename Bus to Bus1;

Table Renamed.

SQL> desc Bus1


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.

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)

SQL> Drop table Passenger;

Table Dropped.

SQL> Rename Passenger to Passenger1;

Table Renamed.

SQL> desc Passenger1

Name Null? Type


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

20
SQL> Truncate table passenger1;

Table Truncated.

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));
Table created.

SQL> desc Ticket

Name Null? Type


------------------------------------------------- ------------------- -------------------------
TICKET_No Not Null Number(9)
Journey_Date Date
Age Number(4)
Sex varchar2(10)
Source varchar2(10)
Arrival_Time varchar2(6)
Destination varchar2(10)

SQL> Alter table Ticket add (Dept_Time varchar(6));


Table Altered.

SQL> desc Ticket

Name Null? Type


------------------------------------------------- ------------------- -------------------------
TICKET_No Not Null Number(9)
Journey_Date Date
Age Number(4)
Sex varchar2(10)
Source varchar2(10)
Arrival_Time varchar2(6)
Destination varchar2(10)
Dept_Time varchar2(6)

SQL> Alter table Ticket modify (Ticket_No number(9));


Table Altered.

SQL> Alter table Ticket drop column Ticket_No;


Table Altered.

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)

SQL> Drop table Ticket;

Table Dropped.

SQL> Rename Ticket to Ticket1;

Table Renamed.

SQL> desc Ticket1


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)

SQL> Truncate table Ticket1;

Table Truncated.

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

Table Created.

22
SQL> desc Reserve

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 Reserve add (status char(2));


Table Altered.

SQL> desc Reserve


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 Reserve modify (PNR_No number(9));


Table Altered.

SQL> Alter table Reserve drop column PNR_No;


Table Altered.

SQL> desc Reserve


Name Null? Type
------------------------------------------------- ------------------- -------------------------
Journey_Date Date
No_Of_Seats Number(8)
Address varchar2(40)
Contact_No Number(10)
Status Char(2)

SQL> Drop table Reserve;

Table Dropped.

SQL> Rename Reserve to Reserve1;

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)

SQL> Truncate table Reserve1;

Table Truncated.

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

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

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.

Note: Detailed creation of tables is given at the end

25
EXPERIMENT- 5: Practicing DML commands:

DML Commands:-to manipulate data of a database objects


1) insert
2) update
3) delete
4) truncate

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.

a) remove all rows


Syntax:
delete from <tablename>;

b) removal of a specified row/s


Syntax:
delete from <tablename> where <condition>;

3. Updating the contents of a table.

a) updating all rows


Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;

b) updating seleted records.


Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>
where <condition>;

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.

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.

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

SQL> update bus set Destination=’Nizamabad’ where busno=’AP01’;

1 row updated.

SQL> Select * from Bus;

BusNo Source Destination Weekday


----------- ------------- ------------------ ----------------
AP01 Hyderabad Nizambad Sunday
AP02 Delhi Mumbai Monday
AP03 Chennai Srinagar Wednesday
AP04 Bangalore Hyderabad Sunday
AP05 Karimnagar Warangal Friday

SQL> update bus set weekday=null;

5 rows updated.

SQL> Select * from Bus;

BusNo Source Destination Weekday


----------- ------------- ------------------ ----------------
AP01 Hyderabad Nizambad
AP02 Delhi Mumbai
AP03 Chennai Srinagar
AP04 Bangalore Hyderabad
AP05 Karimnagar Warangal

27
SQL> delete from bus where Source='Chennai';

1 row deleted.

SQL> Select * from Bus;

BusNo Source Destination Weekday


----------- ------------- ------------------ ----------------
AP01 Hyderabad Nizambad
AP02 Delhi Mumbai
AP04 Bangalore Hyderabad
AP05 Karimnagar Warangal

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

28
SQL> update Passenger set Name=’Rajitha’ where pnr_no=’2000’;

1 row updated.

SQl> Select * from Passenger;

PNR_No Ticket_No Name Age Sex PPNO Category


------------ -------------- ---------------- -------- --------- ------------- --------------
1000 1 Anitha 35 F 10 A/C
2000 2 Rajitha 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

SQL> update Passenger set sex=null;

6 rows updated.

SQl> Select * from Passenger;

PNR_No Ticket_No Name Age Sex PPNO Category


------------ -------------- ---------------- -------- --------- ------------- --------------
1000 1 Anitha 35 10 A/C
2000 2 Rajitha 30 20 NONA/C
3000 3 Srilatha 22 30 A/C
4000 4 Chaitanya 25 40 A/C
5000 5 Saketh 28 50 NONA/C
6000 6 Anirudh 27 60 NONA/C

SQL> delete from Passenger where name='Anirudh';

1 row deleted.

SQl> Select * from Passenger;

PNR_No Ticket_No Name Age Sex PPNO Category


------------ -------------- ---------------- -------- --------- ------------- --------------
1000 1 Anitha 35 10 A/C
2000 2 Rajitha 30 20 NONA/C
3000 3 Srilatha 22 30 A/C
4000 4 Chaitanya 25 40 A/C
5000 5 Saketh 28 50 NONA/C

29
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

SQL> update Ticket set source=’Nizamabad’ where ticket_no=’1’;


1 row updated.

SQL> Select * from Ticket;

Ticket_No Journey_date Age Sex Source Arrival_time Destination Dep_Time


------------- ---------------- ------ ------ ----------- ----------------- -------------- --------------
1 01-jan-2010 35 F Nizamabad 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

SQL> update Ticket set sex=null;

5 rows updated.

30
SQL> Select * from Ticket;

Ticket_No Journey_date Age Sex Source Arrival_time Destination Dep_Time


------------- ---------------- ------ ------ ----------- ----------------- -------------- --------------
1 01-jan-2010 35 Nizamabad 9 Karimnagar 23
2 02-jan-2010 30 Delhi 5 Mumbai 18
3 03-jan-2010 22 Chennai 6 Srinagar 16
4 04-jan-2010 25 Bangalore 8 Hyderabad 14
5 05-jan-2010 28 Karimnagar 5 Warangal 13

SQL> delete from Ticket where source='Chennai';

1 row deleted.

SQL> Select * from Ticket;

Ticket_No Journey_date Age Sex Source Arrival_time Destination Dep_Time


------------- ---------------- ------ ------ ----------- ----------------- -------------- --------------
1 01-jan-2010 35 Nizamabad 9 Karimnagar 23
2 02-jan-2010 30 Delhi 5 Mumbai 18
4 04-jan-2010 25 Bangalore 8 Hyderabad 14
5 05-jan-2010 28 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.

31
SQL> Select * from Reserve;

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
SQL> update Reserve set Address=’Hyd’ where pnr_no=’2000’;
1 row updated.

SQL> Select * from Reserve;

PNR_No Journey_date No_of_seats Address Contact_No Status


------------ -------------------- ------------------ ------------- - ----------------- ----------
1000 1-feb-2010 1 Ramanthpur 0123456789 Y
2000 2-feb-2010 2 Hyd 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

SQL> update Reserve set status=null;

5 rows updated.

SQL> Select * from Reserve;

PNR_No Journey_date No_of_seats Address Contact_No Status


------------ -------------------- ------------------ ------------- - ----------------- ----------
1000 1-feb-2010 1 Ramanthpur 0123456789
2000 2-feb-2010 2 Hyd 1234567890
3000 3-feb-2010 3 Dilsukhnagar 1234567809
4000 4-feb-2010 4 Tarnaka 1234123412
5000 5-feb-2010 5 DDCOLONY 1234512345

SQL> delete from Reserve where journey_date='2-feb-2010';


1 row deleted.

SQL> Select * from Reserve;

PNR_No Journey_date No_of_seats Address Contact_No Status


------------ -------------------- ------------------ ------------- - ----------------- ----------
1000 1-feb-2010 1 Ramanthpur 0123456789
3000 3-feb-2010 3 Dilsukhnagar 1234567809
4000 4-feb-2010 4 Tarnaka 1234123412

32
5000 5-feb-2010 5 DDCOLONY 1234512345

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

SQL> update Cancellation set Address=’Karimnagar’ where pnr_no=’2000’;


1 row updated.

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 Karimnagar 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

SQL> update Cancellation set status=null;

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

SQL> delete from cancellation where No_of_seats=2';


1 row deleted.

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

Syntax: select select-list1 from <TN><alias name1>where(condition1 < comparison operator)


Any (select select-list2 from <TN><alias name2> where <condition>

All:

This operator also makes inner query to return multiple rows of which it selects the biggest value
& sends that value for comparison at the condition of outer query.

Syntax: select <select list> from <TN><alias name1>where<condition (op) All > (select<select
list>) from <TN><alias name2> where <conditionlist>

IN:

Syntax: select <select-list> from <TN><alias name>where<condition>IN (select<select-


list1>from <TN><alias name2> where <condition>

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.

Syntax: select <select-list> from <TN><alias name>where Exists (select * from<TN><alias


name> where <condition>

Not Exists:

This operator will return true for that condition which doesn’t get satisfy at inner query. If the
condition becomes true it becomes false at the Boolean value & those rows will be avoided at
retrieval.

Syntax: select <select-list> from <TN><alias name> where Not Exists(select * from<TN><alias
name> where <condition>

Union:

It joins the rows returned by 2 (or) more queries, by avoiding duplicates & arranging the rows in
ascending order.

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;

Types of data constrains.


a) not null constraint at column level.
Syntax:
<col><datatype>(size)not null
b) unique constraint
Syntax:
Unique constraint at column level.
<col><datatype>(size)unique;
c) unique constraint at table level:
Syntax:
Create table tablename(col=format,col=format,unique(<col1>,<col2>);
d) primary key constraint at column level
Syntax:<col><datatype>(size)primary key;

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

Practice the following queries

1) Display unique PNR_no of all passengers

SQL>select distinct(Pnr_no) from passenger;

PNR_NO
------
1000
2000
3000
4000
5000
2) Display all the names of male passengers

SQL> select name from passenger where sex='M';

NAME
---------------
chaitanya
saketh

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


SQL> select ticket_no,name from passenger;

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

SQL> select ticket_no from passenger where name like 'A%h';

TICKET_NO
----------
6

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

SQL> select name from passenger where age between 30 AND 45;

NAME
---------------
Anitha
Haritha

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

SQL> select name from passenger where name like 'A%';

NAME
---------------
Anitha
Anirudh

8) Display the sorted list of the passenger names.

SQL> select name from passenger order by name;

NAME
---------------
Anirudh
Anitha
Srilatha
chaitanya
haritha
saketh

38
9) Display the Bus numbers that travel on Sunday and Wednesday.

mysql> select BusNo from bus where Weekday='Sunday' or WeekDay='Wednesday';


+-------+
| BusNo |
+-------+
| AP01 |
| AP03 |
| AP04 |
+-------+
10) Display the details of Passengers who are travelling either in AC or NONAC.
|
mysql> select * from passenger where category IN('A/C','NONA/C');
--------+-----------+-----------+------+------+------+----------+
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 |
--------+-----------+-----------+------+------+------+----------+

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

2) Sum: It is used to retrieve the sum of unique values of a given column.


Syntax: select sum(column name)from <TN> <alias name>where<where condition>

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

4)Max: It is used to find the maximum value of a given number


Syntax: select Max (Column name) from <TN> (alias name);

5) Min: It is used to find the minimum value of a given number.


Syntax: select Min (column name) from<TN> (alias number)

Group by & having Clause:


Group By and having clause is used to group the related data into one & having is used to group
qualification.

Syntax: select select-list from from-list where condition 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”.

Syntax: create view <view name>as


select<col name>
from<Table name>
where col name= expression-list
group by<grouping creation>
having condition

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

2. Write a query to display different traveling options available in British Airways.

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

5. Find the distinct PNR numbers that are present.


sql> select distinct(PNR_NO) from passenger reserve;

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

7. Find the Total number of cancelled seats.

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

Eg: CREATE TRIGGER updcheck BEFORE UPDATE ON passenger


FOR EACH ROW
BEGIN
IF NEW.Ticket no> 60 then
Set new.Ticket no= Ticket no;
ELSE
SET New.Ticket no=0;
END IF;
END;

Triggers:

What are triggers?


A trigger is a PL/SQL block or a PL/SQL procedure associated with a table, view, schema, of the
database. It executes implicitly whenever a particular event takes place. It can either be:

1. Application trigger: Fires whenever an event occurs with a particular application.


2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.

When should we use triggers?


Triggers are to be used when we want to perform related actions and when we want to centralize
global operations. Create stored procedures and invoke them in a trigger, if the PL/SQL code is
very lengthy. The excessive use of triggers can result in complex interdependencies, which may
be difficult to maintain in large applications. Triggers should not be used where functionality
needed is already built into the Oracle server or when it is duplicating what is done by other
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.

Triggering user events:


o INSERT
o UPDATE
o DELETE

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:

CREATE [OR REPLACE] TRIGGER trigger_name


Timing
Event1 [OR event2 OR event3]
ON table_name
Trigger_body

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.

Eg: CREATE PROCEDURE myProc()


BEGIN
SELECT COUNT(Tickets) FROM Ticket WHERE age>=40;
End;

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.

We can pass parameters to procedures in three ways.


1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

A procedure may or may not return any value.

General Syntax to create a procedure is:

CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]


IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;

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.

1> CREATE OR REPLACE PROCEDURE employer_details


2> IS
3> CURSOR emp_cur IS
4> SELECT first_name, last_name, salary FROM emp_tbl;
5> emp_rec emp_cur%rowtype;
6> BEGIN
7> FOR emp_rec in sales_cur
8> LOOP
9> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
10> || ' ' ||emp_cur.salary);
11> END LOOP;
12>END;
13> /

How to execute a Stored Procedure?

There are two ways to execute a procedure.

1) From the SQL prompt.

EXECUTE [or EXEC] procedure_name;

2) Within another procedure – simply use the procedure name.

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.

CREATE PROCEDURE myProc (in_customer_id INT)


BEGIN
DECLARE v_id INT;
DECLARE v_name varchar(30);
DECLARE c1 CURSOR FOR SELECT stdid, stdfirstname FROM Students WHERE
stdId=in_customer_id;
OPEN c1;
FETCH c1 into v_id, v_name;
Close c1;
END;

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.

Controlling Explicit Cursors:

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;

Fetch data from a cursor:


FETCH cursor_name INTO [variable1, variable2,….]| record_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;

Attributes of an Explicit Cursor:

o %ISOPEN [is cursor open]


o %NOTFOUND [is row not found]
o %FOUND [is row found]
o %ROWCOUNT [rows returned so far]

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.

53. What is RAID Technology?


Ans: Redundant array of inexpensive (or independent) disks. The main goal of raid technology is to even
out the widely different rates of performance improvement of disks against those in memory and
microprocessor. Raid technology employs the technique of data striping to achieve higher transfer rates.
54. What is Hashing technique?
Ans: This is a primary file organization technique that provides very fast access to records on certain
search conditions. The search condition must be an equality condition on a single field, called hash field
of the file.
1. Internal hashing

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.

63. What are the properties of transaction?


Ans:
1. Atomicity
2. Consistency preservation
3. Isolation
4. Durability (permanence)
64. What are the basic data base operations?

53
Ans:
1. Write_item(x)
2. Read_item(x)

65. What are the disadvantages of not controlling concurrency?


Ans:
1. Lost update problem
2. Temporary update (Dirty read) problem
3. Incorrect summary problem
66. What are serial, non serial schedules?
Ans: A schedule S is serial if, for every transaction T participating in the schedule, all the operations of T
is executed consecutively in the schedule, otherwise, the schedule is called non-serial schedule.
67. What is result equivalent?
Ans: Two schedules are called result equivalent if they produce the same final state of the data base.
68. What are conflict equivalent schedules?
Ans: Two schedules are said to be conflict equivalent if the order of any two conflicting operations is the
same in both schedules.
69. What is a conflict serializable schedule?
Ans: A schedule is called conflict serializable if it is conflict equivalent to some serial schedule.
70. What is view serializable?
Ans: A schedule is said to be view serializable if it is view equivalent with some serial schedule.
71. What are the various methods of controlling concurrency?
Ans:
1. Locking
2. Time stamp
Locking data item to prevent multiple transactions from accessing the item concurrently.
A time stamp is a unique identifier for each transaction, generated by the system.
72. What is a lock?
Ans: A lock is a variable associated with a data item that describes the status of the item with respect to
the possible operations that can be applied to it.
73. What are various types of locking techniques?
Ans:
1. a binary lock
2. Shared/Exclusive lock
3. Two phase locking
74. What is a binary lock?
Ans: A binary lock can have two states or values:
1. locked (1)
2. Unlocked (0)
If locked it cannot be accessed by any other operations, else can be.
75. What is shared or exclusive lock?
Ans: It implements multiple-mode lock. Allowing multiple accesses for read operations but exclusive
access for write operation.
76. Explain two phase locking?
Ans: All the locking operations must precede the first unlock operation in the transaction .It does have
two phases:
1. expanding phase (Locks are issued)
2. Shrinking phase (Locks are released)
77. What is a deadlock?

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.

78. What are triggers?


Ans: Triggers are the PL/SQL blocks defining an action the database should take when some database
related event occurs. Triggers may be used to supplement declarative referential integrity, to enforce
complex business rules, or to audit changes to data.
79. What is a surrogate key?
Ans: A surrogate key is a system generated sequential number which acts as a primary key.
80. What are the disadvantages of FPS?
Ans:
- Data redundancy & inconsistency.
- Difficult in accessing data.
- Data isolation.
- Data integrity.
- Concurrent access is not possible.
- Security Problems.
81. What are the three levels of abstractions?
Ans:
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.
82. Define the "integrity rules"
Ans: 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.
83. What is Object Oriented model?
Ans: 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.
84. What is Relationship?
Ans: It is an association among two or more entities.
85. What is Relationship set?
Ans: The collection (or set) of similar relationships.
86. What is Relationship type?
Ans: Relationship type defines a set of associations or a relationship set among a given set of entity
types.
87. What is DML?
Ans: This language that enable user to access or manipulate data as organized by appropriate data
model.
88. What is DDL?
Ans: Data Definition language deals with the structure of the table.
89. What is VDL (View Definition Language)?
Ans:

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.

92. What is DDL Interpreter?


Ans: It interprets DDL statements and records them in tables containing metadata.
93. What is Record-at-a-time?
Ans: 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.
94. What is Set-at-a-time or Set-oriented?
Ans: 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.
95. What is Relational Algebra?
Ans: 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.
96. What is Relational Calculus?
Ans: It is an applied predicate calculus specifically tailored for relational databases proposed by E.F.
Codd.
97. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus
Ans: The tuple-oriented calculus uses 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.
98. What is normalization?
Ans: It is a process of analyzing 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.
99. What is functional dependency?
Ans: A functional dependency (FD) is a constraint between two sets of attributes in a relation from a
database.
100. What is Lossless join property?
Ans: It guarantees that the spurious tuple generation does not occur with respect to relation schemas
after decomposition.
101. What does SQL stand for?
Ans: Structured Query Language.
101. What is SQL?
Ans: SQL (Structured Query Language) is a standard language for accessing databases.
102. Name a few database systems.
Ans: MySQL, SQL Server, Access, Oracle, Sybase, DB2 etc..
103. Which SQL statement is used to extract data from a database?
Ans: select statement.
104. Which SQL statement is used to update data in a database?
Ans: Update
105. Which SQL statement is used to delete data from a database?
Ans: delete.
106. How do you create a table? Show with an example.

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.

157. What is a Fact?


Ans: In data warehousing a fact is a value or measurement, which represents a fact about the managed
entity or system.
158. What is data cleaning?
Ans: Data cleansing or data scrubbing is the act of detecting and correcting (or removing) corrupt or
inaccurate records from a record set, table, or database.
159. What is clustering?
Ans: Grouping of similar objects.
160. What is Data purging?
Ans: The process of cleaning junk data is termed as data purging. Purging data would mean getting rid of
unnecessary NULL values of columns
161. What are CUBES?
Ans: A data cube stores data in a summarized version which helps in a faster analysis of data. The data is
stored in such a way that it allows reporting easily
162. What are OLAP and OLTP?
Ans: OLTP: Online Transaction and Processing helps and manages applications based on transactions
involving high volume of data. Typical example of a transaction is commonly observed in Banks, Air
tickets etc. Because OLTP uses client server architecture, it supports transactions to run cross a network.
OLAP: Online analytical processing performs analysis of business data and provides the ability to
perform complex calculations on usually low volumes of data. OLAP helps the user gain an insight on the
data coming from different sources (multi dimensional).
163. What is a SNAPSHOT?
Ans: Snapshots are read-only copies of a master table located on a remote node which is periodically
refreshed to reflect changes made to the master table.
164. What are the different problems that “Data mining” can solve?
1. Data mining helps analysts in making faster business decisions which increases revenue with
lower costs.
2. Data mining helps to understand, explore and identify patterns of data.
3. Data mining automates process of finding predictive information in large databases.
4. Helps to identify previously hidden patterns.
165. What are the different stages of data mining?
Ans
Exploration: This stage involves preparation and collection of data. it also involves data cleaning,
transformation. Based on size of data, different tools to analyze the data may be required. This stage
helps to determine different variables of the data to determine their behavior.
Model building and validation: This stage involves choosing the best model based on their predictive
performance. The model is then applied on the different data sets and compared for best performance.
This stage is also called as pattern identification. This stage is a little complex because it involves
choosing the best pattern to allow easy predictions.
Deployment: Based on model selected in previous stage, it is applied to the data sets. This is to generate
predictions or estimates of the expected outcome.

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.

167. What is MODEL in Data mining world?


Ans: Models in Data mining help the different algorithms in decision making or pattern matching. The
second stage of data mining involves considering various models and choosing the best one based on
their predictive performance.
168. How does the data mining and data warehousing work together?
Ans: Data warehousing can be used for analyzing the business needs by storing data in a meaningful
form. Using Data mining, one can forecast the business needs. Data warehouse can act as a source of
this forecasting.
170. What is a Decision Tree Algorithm?
Ans: A decision tree is a tree in which every node is either a leaf node or a decision node. This tree takes
an input an object and outputs some decision. All Paths from root node to the leaf node are reached by
either using AND or OR or BOTH. The tree is constructed using the regularities of the data. The decision
tree is not affected by Automatic Data Preparation.
171. What is Time Series algorithm in data mining?
Ans: Time series algorithm can be used to predict continuous values of data. Once the algorithm is
skilled to predict a series of data, it can predict the outcome of other series. The algorithm generates a
model that can predict trends based only on the original dataset. New data can also be added that
automatically becomes a part of the trend analysis.
E.g. Performance one employee can influence or forecast the profit.
172. What is Sequence clustering algorithm?
Ans: Sequence clustering algorithm collects similar or related paths, sequences of data containing
events. The data represents a series of events or transitions between states in a dataset like a series of
web clicks. The algorithm will examine all probabilities of transitions and measure the differences, or
distances, between all the possible sequences in the data set. This helps it to determine which sequence
can be the best for input for clustering.
173. Explain how to mine an OLAP cube.
Ans: A data mining extension can be used to slice the data the source cube in the order as discovered by data
mining. When a cube is mined the case table is a dimension.
174. What is an index?
Ans: Indexes help us to find data faster. It can be created on a single column or a combination of
columns. A table index helps to arrange the values of one or more columns in a specific order.
Micro Processors
175. What is a Microprocessor?
Ans: Microprocessor is a program-controlled device, which fetches the instructions from memory,
decodes and executes the instructions. Most Micro Processors are single- chip devices.
176. What are the flags in 8085?
Ans: Accumulator register, Temporary register, Instruction register, Stack Pointer, Program Counter are
the various registers in 8085

182. What is meant by Maskable interrupts?

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

187. What does EU do?


Ans: Execution Unit receives program instruction codes and data from BIU, executes these instructions
and store the result in general registers.
188. What are SIM and RIM instructions?
Ans: SIM is Set Interrupt Mask. It is used to mask the hardware interrupts.
RIM is Read Interrupt Mask. Used to check whether the interrupt is Masked or not.
189. What is the difference between 8086 and 8088?
Ans: The BIU in 8088 is 8-bit data bus & 16- bit in 8086.Instruction queue is 4 byte long in 8088and 6
byte in 8086.
190. Give example for Non-Maskable interrupts?
Ans: Trap is known as Non-Maskable interrupts, which is used in emergency condition.
191. Give examples for 8 / 16 / 32 bit Microprocessor?
Ans: 8-bit Processor - 8085 / Z80 / 6800; 16-bit Processor - 8086 / 68000 / Z8000; 32-bit Processor -
80386 / 80486
192. What is meant by a bus?
Ans: A bus is a group of conducting lines that carriers data, address, & control signals.
193. Name 5 different addressing modes?
Ans: Immediate, Direct, Register, Register indirect, Implied addressing modes
194. What is the difference between primary & secondary storage device?
Ans: In primary storage device the storage capacity is limited. It has a volatile memory. In secondary
storage device the storage capacity is larger. It is a nonvolatile memory. Primary devices are: RAM /
ROM. Secondary devices are: Floppy disc / Hard disk.
195. What is Stack Pointer?
Ans: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of
the top of the stack.
196. In 8085 name the 16 bit registers?
Ans : Stack pointer and Program counter all have 16 bits.
197. What happens when HLT instruction is executed in processor?
Ans: The Micro Processor enters into Halt-State and the buses are tri-stated.
198. Which interrupt has the highest priority?
Ans: TRAP has the highest priority
199. What are Hardware interrupts?
Ans: TRAP, RST7.5, RST6.5, RST5.5, INTR
200. What is the difference between timer and counter?
Ans: A counter accumulates an unknown quantity of external events over a known interval of time.
A timer accumulates a series events of a known interval over an interval that is being measured.

62
63

You might also like