DBMS Lab Manual 7-2-2016

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 93

DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

B.M.S. EDUCATION TRUST


B.M.S.COLLEGE OF ENGINEERING,
BANGALORE-19
(Autonomous College under VTU)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

PROGRAM: BACHELOR OF ENGINEERING


SEMESTER: IV
SESSION: 2015-16
COURSE CODE:15CS4DCDBM
COURSE TITLE:DATABASE MANAGEMENT SYSTEM
CREDITS: 6
PREFACE
This laboratory manual is prepared by the Department of Computer Science and engineering for
Database Management Systems Laboratory (15CS4DCDBM). This lab manual can be used as
instructional book for students, staff and instructors to assist in performing and understanding the
experiments. In this manual, experiments as per syllabus are described.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

COURSE CONTENTS
UNIT-1
Introduction to Databases: Introduction, An Example, Characteristics of 11 Hrs.
Database approach, Advantages of using DBMS approach, When not to use a
DBMS.
Database System Concepts and Architecture: Data models, Schemas and
instances, Three schema architecture and data independence, Database languages
and interfaces, The database system environment.
SQL: SQL Data Definition and Data Types specifying basic constraints in SQL,
Basic retrieval queries in SQL, Insert, Delete and Update statements in SQL,
Additional features of SQL, More complex SQL Queries, Specifying Constraints
as Assertion and Trigger, Views (Virtual Tables) in SQL, Schema Change
Statement in SQL.
UNIT-2
Relational Data Model and Relational Database Constraints: Relational 11 Hrs.
Model Concepts, Relational Model Constraints and Relational Database Schemas,
Update Operations, Transactions and Dealing with Constraint Violations.
Relational Algebra: Unary Relational Operations, SELECT and PROJECT,
Relational Algebra Operations from Set Theory, Binary Relational Operations:
JOIN and DIVISION, Additional Relational Operations, Examples of Queries in
Relational Algebra.
Data Modeling using the Entity-Relationship(ER) model: Using High-Level
conceptual Data Models for Database Design, A sample Database Application,
Entity types, Entity Sets, Attributes and Keys, Relationship Types, Relationship
Sets, Roles and Structural Constraints, Weak Entity types, Refining the ER
Design, ER Diagrams, Naming Conventions and Design Issues, Relationship
Types of Degree Higher than Two, Database Design using ER-toRelational
Mapping.
UNIT-3
Database Design Theory and Normalization: Informal Design Guidelines for 9 Hrs.
Relation Schemas, Functional Dependencies, Normal Forms Based on Primary
Keys, General Definitions of Second and Third Normal Forms, Boyce-Codd
Normal Form, Multi-valued Dependencies and Fourth Normal Form, Join
Dependencies and Fifth Normal Form.
UNIT-4
Transaction Processing, Concurrency Control, and Recovery: Introduction to 8 Hrs.
Transaction Processing, Transaction and System Concepts, Desirable Properties
of Transactions,Characterizing Schedules Based on Recoverability,
Characterizing Schedules Based on Serializability, Two-Phase Locking
Techniques for Concurrency Control, Recovery Concepts, NO-UNDO/REDO
Recovery Techniques based on Deferred Update, Recovery Techniques Based on
Immediate Update, Shadow Paging, The ARIES Recovery
References:

Text Books:
1. Fundamental of Database Systems by RamezElmasri and Shamkant B Navathe, Sixth
Edition, Addison Wesley, 2011.
2. Database System Concepts, Sixth Edition,AbrahamSilberschatz, Henry F. Korth, S.
Sudarshan : Tata McGraw-Hill,2010

Reference Books:
1. An Introduction to Database Systems by C.J. Date, A.Kannan, S.Swamynathan, 8th
Edition, Pearson Education, 2006.
2.Database Systems: The Complete Book, Second Edition, Hector Garcia-Molina,Jeffrey
D.Ullman, Jennifer Widom , Pearson Education, 2001

E- Books:
1. Introduction to structured Query Language (SQL)
2. An Introduction to Relational Database Theory by Hugh Darwen
3. Database Management System by Raghu Ramakrishnan

MOOCs:
1. http://nptel.ac.in/courses/IIT-MADRAS/Intro_to_Database_Systems_Design
2.http://www.iitg.ernet.in/awekar/teaching/cs344fall11/
3. www.w3schools.com/sql/

PROGRAM OUTCOMES

PO1 Ability to apply the knowledge of Mathematics, Science and Engineering


Fundamentals with the domain knowledge of computer science to solve engineering
problems
PO2 Identify, formulate and analyze engineering problems using the knowledge of
mathematics, science and Engineering with the domain knowledge of computer
science to arrive at substantiated conclusions.
PO3 Ability to Design and develop computer based solutions for practical engineering
problems under realistic constraints.
PO4 Ability to design, conduct experiment, analyze, interpret data and arrive at valid
conclusions.
PO5 Ability to select and use modern tools and techniques for computing practice.
PO6 Ability to reason by assessing the societal, health, safety, legal, cultural issues and
exhibit responsibility relevant to professional engineering practice.
PO7 Ability to Understand the impact of Engineering solutions in societal and
Environmental aspects and exhibit sustainable development
PO8 Ability to apply ethical principles and commit to norms of professional engineering
practice
PO9 Ability to function effectively as an individual and as a team member or leader in
diverse teams and multidisciplinary settings
PO10 Ability to Communicate effectively, design good documentations and make clear
presentations
PO11 Ability to understand and apply the engineering, finance and management principles
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

to manage multidisciplinary projects


PO12 Ability to recognize the need and engage in lifelong learning for professional growth

COURSE OBJECTIVES

CO 1 Describe basic concepts of Database Management System


CO 2 Implement SQL queries using relational model concepts
CO 3 Formulate relational algebraic expressions using relational model concepts
CO 4 Design ER-Diagram for real world applications using database concepts
CO 5 Analyze and apply normalization concept for relational schema
CO 6 Analyze transaction processing and concurrency control techniques
CO 7 Design and develop a database project using suitable front-end.

CO-PO MAPPING

Course Code: Course Title: Database Management Systems


10CI5GCDBM
Course Outcomes PO1 PO2 PO3 PO4 PO5 PO6 PO PO PO PO PO PO
7 8 9 10 11 12
CO1. Describe basic
concepts of Database H
Management System
CO2. Implement SQL
queries using relational H
model concepts
CO3. Formulate
relational algebraic
expressions using H
relational model
concepts
CO4. Design ER-
Diagram for real world
applications using H
database concepts
CO5. Analyze and
apply normalization
concept for relational
H
schema
CO6: Analyze
transaction processing
and concurrency control
H
techniques
CO7: Design and M M M
develop a database
project using suitable
H H H
front-end.

Instructions to Students to be followed in each DBMS lab:


1. Each Student should write down the work carried out and the outputs in the observation book
and get it evaluated by the respective lab faculty in-charge.
2. Each Student should bring the lab record with the programs and output written for the
programs completed in their respective previous week and get it evaluated by the lab faculty in-
charge.
3. Each Student should write the SQL queries for at least ten practice questions given in the Part-
C of the lab manual

DBMS Lab List

DBMS lab manual is composed of three parts


Part A: Front-end development using Visual C#
Focus of Visual C# is only on learning to develop front-end i.e., form design using the toolbox.
Students will learn the basic coding to handle events. In the lab students have to execute the
following Visual C# lab programs.
Program 1: 1a. Adding two numbers 1b. Finding Largest of three numbers

Program 2: 2a.Student USN validation2b. Collect Student Information (USN, Name,


Department Name(Combo Box) and Semester (Radio Button) Using Form And Display it on
Message Box

3. Reading data from already existing database table and displaying it using form grid. Note:
Database table should contain Student name, USN, Department name and Semester.

4. Insert the new record into the existing database table by accepting the new record information
through form and Update any of the existing database record. Note: Database table should
contain Student name, USN, Department name and Semester.

5. Delete the existing record from the database table against USN by accepting it through the
form text box and Search the student database records.

Part B: Writing SQL Queries using Oracle for the following database systems
Sl no. Name
1 Insurance Database
2 Banking Enterprise Database
3 Supplier Database
4 Student Faculty Database
5 Airline Flight Database

Part C: Practice questions on writing SQL queries.

Part A:
Part A: Front-end development using Visual C#
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Focus of Visual C# is only on learning to develop front-end i.e., form design using the toolbox.
Students will learn the basic coding to handle events.
Program 1: 1a. Adding two numbers 1b. Finding Largest of three numbers

Introduction
Step1: To create project in Visual Studio 10
Open Visual Studio 2010 - > Click on NewProject - > Visual C# Windows Forms Application ->
Type project name & OK
Program 1:
1a: Adding two numbers
Drag drop required fields into the form - > Properties change the name of the controls (eg.
Textbox1 to Txt_Name)

Double click on Add button to open the code window and then type the code given below given
in the button_click function:
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lab_prog1
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid BTN_ADD_Click(object sender, EventArgs e)


{
int res = int.Parse(Txt_number1.Text) + int.Parse(Txt_number2.Text);
lbl_Result.Text = Convert.ToString(res);
}
}
}

Output:

Press F5 button or click on Run button to see the output

1b: Largest of three numbers


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lab_prog1
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid BTN_ADD_Click(object sender, EventArgs e)


{

if (int.Parse(Txt_number1.Text) >int.Parse(Txt_number2.Text) &&int.Parse(Txt_number1.Text)


>int.Parse(Txt_Number3.Text))
{
lbl_Result.Text = "Number 1 is greatest" + Txt_number1.Text;
}
elseif (int.Parse(Txt_number2.Text) >int.Parse(Txt_Number3.Text))
{
lbl_Result.Text = "Number 2 is greatest" + Txt_number2.Text;
}
else
{
lbl_Result.Text = "Number 3 is greatest" + Txt_Number3.Text;
}

}
}
}

Output:

Part B: Program 2
2a.Student USN validation

CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Lab_prog1
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid BTN_ADD_Click(object sender, EventArgs e)


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

{
Regex MY_EXP = newRegex("^1BM13CS\\d{3}$");
Match nmat = MY_EXP.Match(Txt_USN.Text);
if (nmat.Success)
{
lbl_Result.Text = "Valid USN";
}
else
{
lbl_Result.Text = "Invalid USN";
}

}
}
}

OUTPUT:
Part B: Program 2
2b. Collect Student Information (USN, Name, Department Name(Combo Box) and Semester
(Radio Button) Using Form And Display it on Message Box
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Lab_prog1
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid BTN_ADD_Click(object sender, EventArgs e)


{
String msg="";
if(rbtn_sem1.Checked == true )
msg = "Sem :1";
elseif(rbtn_sem2.Checked == true )
msg = "Sem: 2";
elseif(rbtn_sem3.Checked == true )
msg = "Sem: 3";
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

elseif(rbtn_sem4.Checked == true )
msg = "Sem: 4";

MessageBox.Show("USN: " + Txt_USN.Text + " " + "Dept: " + cmb_dept.Text + " " + msg);

}
}

Output:
Part B: Program 3
3. Reading data from already existing database table and displaying it using form grid. Note:
Database table should contain Student name, USN, Department name and Semester.

Steps to connect database:


Tools - > Connect database
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Server name : BMSCE user name:scott pass: tiger and then click on test connection to check
the connectivity once success click on OK

Left panel - > view the data connection and browse the tables…

Front –end form:


Add the DataGrid tool to form and button

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication3
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid Form1_Load(object sender, EventArgs e)


{

privatevoid button1_Click(object sender, EventArgs e)


{
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=BMSCE;User Id=scott;Password=tiger;";
string sql = "SELECT * FROM stud";
OleDbConnection connection = newOleDbConnection(connetionString);
OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql, connection);
DataSet ds = newDataSet();
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

connection.Open();
dataadapter.Fill(ds, "stud");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "stud";
}
}
}

Output:

Part B: Program 4
4. Insert the new record into the existing database table by accepting the new record information
through form and Update any of the existing database record. Note: Database table should
contain Student name, USN, Department name and Semester.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Data.OleDb;

namespace Lab_prog1
{
publicpartialclassFrm1 : Form
{
OleDbConnection connection;
OleDbDataAdapter dataadapter;
DataSet ds;

publicvoid ConnectString()
{
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=BMSCE;User Id=scott;Password=tiger;";
string sql = "SELECT * FROM stude_info";
OleDbConnection connection = newOleDbConnection(connetionString);
OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql, connection);
ds = newDataSet();
connection.Open();
dataadapter.Fill(ds, "stude_info");
connection.Close();
}

public Frm1()
{
InitializeComponent();
}
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

privatevoid BTN_ADD_Click(object sender, EventArgs e)


{
int sem=0;
if (rbtn_sem1.Checked == true)
sem = 1;
elseif (rbtn_sem2.Checked == true)
sem = 2;
elseif (rbtn_sem3.Checked == true)
sem = 3;
elseif (rbtn_sem4.Checked == true)
sem = 4;
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=BMSCE;User Id=scott;Password=tiger;";
string sql = "SELECT * FROM stude_info";
OleDbConnection connection = newOleDbConnection(connetionString);
OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql, connection);
ds = newDataSet();
connection.Open();
dataadapter.Fill(ds, "stude_info");

string sql1 = "Insert into stude_info VALUES ('" + Txt_USN.Text +"', '"+ Txt_name.Text +"', '"+cmb_dept.Text+"', '"+
sem +"' )";
dataadapter.InsertCommand = newOleDbCommand(sql1, connection);
dataadapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row(s) Inserted !! ");
dataadapter.Fill(ds, "stude_info");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "stude_info";
dataGridView1.Refresh();
connection.Close();
}

privatevoid Form1_Load(object sender, EventArgs e)


{
ConnectString();

dataGridView1.DataSource = ds;
dataGridView1.DataMember = "stude_info";

}
}

Output:
Part B: Program 5
5. Delete the existing record from the database table against USN by accepting it through the
form text box and Search the student database records.

SQL Queries
create table student (usn varchar(10),name varchar(30),dept varchar(5),sem integer));
insert into student values('1BM14CS001','Avinash','CSE',4);
insert into student values('1BM14CS002','Balaji','ISE',4);
insert into student values('1BM14CS003','Chandan','CSE',4);
commit;
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
publicpartialclassForm1 : Form
{
public Form1()
{
InitializeComponent();
}

privatevoid Display_Click_1(object sender, EventArgs e)


{
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=CSE;User
Id=scott;Password=tiger;";
OleDbConnection connection = newOleDbConnection(connetionString);
connection.Open();

string sql = "select * from student";


OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql, connection);
DataTable dt = newDataTable();

dataadapter.Fill(dt);

dataGridView1.DataSource = dt;

connection.Close();
}

privatevoid Search_Click(object sender, EventArgs e)


{
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=CSE;User
Id=scott;Password=tiger;";
OleDbConnection connection = newOleDbConnection(connetionString);
connection.Open();

string sql_search="select count(*) from student where usn='"+textBox1.Text+"'";


OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql_search, connection);
DataTable dt = newDataTable();
dataadapter.Fill(dt);

if (dt.Rows[0][0].ToString() == "1")
{
MessageBox.Show("Record Found");
}
else
{
MessageBox.Show("Record Not Found");
}

connection.Close();

privatevoid Delete_Click(object sender, EventArgs e)


{
string connetionString = "Provider=OraOLEDB.Oracle;Data Source=CSE;User
Id=scott;Password=tiger;";
OleDbConnection connection = newOleDbConnection(connetionString);
connection.Open();

string sql_search = "select count(*) from student where usn='" + textBox2.Text + "'";
OleDbDataAdapter dataadapter = newOleDbDataAdapter(sql_search, connection);

DataTable dt = newDataTable();
dataadapter.Fill(dt);

if (dt.Rows[0][0].ToString() != "1")
{
MessageBox.Show("Record Not Found");
}
else
{
string sql_delete ="delete from student where usn='"+textBox2.Text+"'";
OleDbCommand cmd = newOleDbCommand(sql_delete, connection);
cmd.ExecuteNonQuery();

MessageBox.Show("Record Deleted");
}

connection.Close();

}
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

}
}

Part B:
INTRODUCTION

Database Management System is assuming an increasingly important role in the developing


world. It is thus crucial that students be exposed to handling huge data in a realistic setting, in
order to connect theoretical material taught in lecture courses .

Get started with Oracle SQL:


1. Click on: Start->Oracle-ora -> Application Development -> SQL
Plus

2. Enter the following values:

User Name: scott (not case sensitive)


Password: tiger (not case sensitive)
Host String: Leave it blank

3. Click on OK

4. You should see


SQL> is called sql prompt, where the commands can be typed for
execution.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

PROGRAM 1: INSURANCE DATABASE

Consider the Insurance database given below. The data types are specified.

PERSON (driver_id: String, name: String, address: String)


CAR (reg_num: String, model: String, year: int)
ACCIDENT (report_num: int, accident_date: date, location: String)
OWNS (driver_id: String, reg_num: String)
PARTICIPATED (driver_id: String,reg_num: String, report_num: int, damage_amount: int)

i) Create the above tables by properly specifying the primary keys and the foreign keys.
ii)Enter at least five tuples for each relation.
iii)Demonstrate how you
a.Update the damage amount to 25000 for the car with a specific reg-num(example 'K
A053408') for which the accident report number was 12.
b.Add a new accident to the database.
iv)Find the total number of people who owned cars that involved in accidents in 2008.
v)Find the number of accidents in which cars belonging to a specific model (example )were
involved.

Schema diagram
Tables

QUERY 1: Create the above tables by properly specifying the primary keys and the foreign
keys.
SQL>create table person (driver_id varchar(10),
name varchar(20),
address varchar(30),
primary key(driver_id));
Table created.

SQL>desc person
Name Null? Type
------------------------ -------- ------------------------------
DRIVER_ID NOT NULLVARCHAR2(10)
NAME VARCHAR2(20)
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

ADDRESSVARCHAR2(30)

SQL>create table car(reg_num varchar(10),model varchar(10),year int,primary


key(reg_num));
Table created.

SQL>desc car
Name Null? Type
------------------------ -------- ----------------------------------
REG_NUM NOT NULLVARCHAR2(10)
MODEL VARCHAR2(10)
YEAR NUMBER(38)

SQL>create table accident(report_num int,accident_date date,location


varchar(20),primary key(report_num));

Table created.

SQL>desc accident
Name Null? Type
-------------------------- -------- ----------------------------
REPORT_NUM NOT NULL NUMBER(38)
ACCIDENT_DATE DATE
LOCATION VARCHAR2(20)

SQL>create table owns(driver_id varchar(10),reg_num varchar(10),


primary key(driver_id,reg_num),
foreign key(driver_id) referencesperson(driver_id),
foreign key(reg_num) references car(reg_num));

Table created.

SQL>desc owns
Name Null? Type
------------------------------- -------- --------------------------------
DRIVER_ID NOT NULL VARCHAR2(10)
REG_NUM NOT NULL VARCHAR2(10)

SQL>create table participated(driver_id varchar(10), reg_num varchar(10),


report_num int, damage_amount int,
primary key(driver_id,reg_num,report_num),
foreign key(driver_id) references person(driver_id),
foreign key(reg_num) references car(reg_num),
foreign key(report_num) references accident(report_num));
Table created.
SQL>desc participated
Name Null? Type
------------------------------- ---------------------------------------------
DRIVER_ID NOT NULL VARCHAR2(10)
REG_NUM NOT NULL VARCHAR2(10)
REPORT_NUM NOT NULL NUMBER(38)
DAMAGE_AMOUNT NUMBER(38)

QUERY 2: Enter at least five tuples for each relation

SQL> insert into person values('&driver_id','&name','&address');


Enter value for driver_id: A01
Enter value for name: Richard
Enter value for address: Srinivas Nagar
old 1: insert into person values('&driver_id','&name','&address')
new 1: insert into person values('A01','Richard','Srinivas Nagar')

1 row created.

SQL>/
Enter value for driver_id: A02
Enter value for name: Pradeep
Enter value for address: Rajajinagar
old 1: insert into person values('&driver_id','&name','&address')
new 1: insert into person values('A02','Pradeep','Rajajinagar')

1 row created.

SQL>commit;
Commit complete.

SQL> select * from person;


DRIVER_ID NAME ADDRESS
---------- -------------------- ------------------------------
A01 Richard Srinivas Nagar
A02 Pradeep Rajajinagar
A03 Smith Ashoknagar
A04 Venu N.R.Colony
A05 John Hanumanth Nagar

SQL> insert into car values('&reg_num','&model', &year);

Enter value for reg_num: KA052250


Enter value for model: Indica
Enter value for year: 1990
old 1: insert into car values('&reg_num','&model', &year)
new 1: insert into car values('KA052250','Indica', 1990)
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

1 row created.

SQL>/
Enter value for reg_num: KA031181
Enter value for model: Lancer
Enter value for year: 1957
old 1: insert into car values('&reg_num','&model',&year)
new 1: insert into car values('KA031181','Lancer', 1957)

1 row created.

SQL>commit;

Commit complete.

SQL> select * from car;

REG_NUM MODEL YEAR


--------------------------- ----------
KA052250 Indica 1990
KA031181 Lancer 1957
KA095477 Toyota 1998
KA053408 Honda 2008
KA041702 Audi 2005

SQL> insert into accident values(&report_num,'&accident_date','&location');

Enter value for report_num: 11


Enter value for accident_date: 01-JAN-03
Enter value for location: Mysore Road
old 1: insert into accident values(&report_num,'&accident_date','&location')
new 1: insert into accident values(111,'01-JAN-03','Mysore Road')

1 row created.

SQL>commit;

Commit complete.
SQL> select * from accident;

REPORT_NUM ACCIDENT_DATE LOCATION


-------------------- ------------ --------------------
11 01-JAN-03 Mysore Road
12 02-FEB-04 Southend Circle
13 21-JAN-03 Bulltemple Road
14 17-FEB-08 Mysore Road
15 04-MAR-05 Kanakpura Road

SQL> insert into owns values ('&driver_id','&reg_num');

Enter value for driver_id: A01


Enter value for reg_num: KA052250
old 1: insert into owns values('&driver_id','&reg_num')
new 1: insert into owns values('A01','KA052250')
1 row created.

SQL>commit;
Commit complete.

SQL> select * from owns;

DRIVER_ID REG_NUM
---------------- ----------
A01 KA052250
A02 KA053408
A04 KA031181
A03 KA095477
A05 KA041702
SQL> insert into participated values ('&driver_id','&reg_num',&report_num,
&damage_amount);

Enter value for driver_id: A01


Enter value for reg_num: KA052250
Enter value for report_num: 11
Enter value for damage_amount: 10000
old 1: insert into participated values ('&driver_id','&reg_num',&report_num,&damage_amount)
new 1: insert into participated values('A01','KA052250',11,10000)

1 row created.

SQL>/
Enter value for driver_id: A02
Enter value for reg_num: KA053408
Enter value for report_num: 12
Enter value for damage_amount: 50000
old 1: insert into participated values ('&driver_id','&reg_num', &report_num,&
damage_amount)
new 1: insert into participated values('A02','KA053408',12,50000)

1 row created.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

SQL>commit;
Commit complete.
SQL> select * from participated;

DRIVER_ID REG_NUM REPORT_NUM DAMAGE_AMOUNT


------------------------------- ---------- ------------------------------
A01 KA052250 11 10000
A02 KA053408 12 50000
A03 KA095477 13 25000
A04 KA031181 14 3000
A05 KA041702 15 5000

QUERY 3:
a) Update the damage amount to 25000 for the car with a specific reg_num (example 'K
A053408' ) for which the accident report number was 12.

SQL> update participated set damage_amount=25000 where reg_num='KA053408' and


report_num=12;

1 row updated.

SQL>commit;

Commit complete.

SQL>select * from participated;

DRIVER_ID REG_NUM REPORTNUM DAMAGE_AMOUNT


----------------- ---------- ---------- ----------
A01 KA052250 11 10000
A02 KA053408 12 25000
A03 KA095477 13 25000
A04 KA031181 14 3000
A05 KA041702 15 5000

b) Add a new accident to the database.

SQL>insert into accident values(16,'15-MAR-08','Domlur');


1 row created.

SQL>select * from accident;

REPORT_NUMACCIDENT_DATE LOCATION
------------------ ------------ --------------------
11 01-JAN-03 Mysore Road
12 02-FEB-04 Southend Circle
13 21-JAN-03 Bulltemple Road
14 17-FEB-08 Mysore Road
15 04-MAR-05 Kanakpura Road
16 15-MAR-08 Domlur

6 rows selected.

QUERY 4: Find the total number of people who owned cars that were involved in
accidents in 2008.

SQL>select count(distinct driver_id) CNT from participated a, accident b where


a.report_num=b.report_num and b.accident_date like '%08';

CNT
----------
1

QUERY 5: Find the number of accidents in which cars belonging to a specific model (example
'Lancer') were involved.

SQL> select count(report_num) CNT from car c,participated p where c.reg_num=p.reg_num and
model='Lancer';

CNT
----------
1

ADDITIONAL QUERIES:
1) LIST THE ENTIRE PARTICIPATED RELATION IN THE DESCENDING ORDER
OF DAMAGE AMOUNT.
SQL> SELECT * FROM PARTICIPATED ORDER BY DAMAGE_AMOUNTT DESC;

2) FIND THE AVERAGE DAMAGE AMOUNT


SQL> SELECT AVG(DAMAGE_AMOUNTT) FROM PARTICIPATED;

3) DELETE THE TUPLE WHOSE DAMAGE AMOUNT IS BELOW THE AVERAGE


DAMAGE AMOUNT
SQL> DELETE FROM PARTICIPATED WHERE
DAMAGE_AMOUNTT<(SELECT AVG (DAMAGE_AMOUNT) FROM PARTICIPATED);

4) LIST THE NAME OF DRIVERS WHOSE DAMAGE IS GREATER THAN THE


AVERAGE DAMAGE AMOUNT.
SQL> SELECT NAME FROM PERSON A, PARTICIPATED B WHERE A.DRIVER_ID = B.DRIVER_ID AND
DAMAGE_AMOUNT>(SELECT AVG(DAMAGE_AMOUNT) FROM PARTICIPATED);

5) FIND MAXIMUM DAMAGE AMOUNT.


SQL>SELECT MAX(DAMAGE_AMOUNT) FROM PARTICIPATED;
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

PROGRAM 2: BANKING ENTERPRISE


DATABASE
Consider the following database for a banking enterprise.

Branch (branch-name: String, branch-city: String, assets: real)


BankAccount(accno: int, branch-name: String, balance: real)
BankCustomer (customer-name: String, customer-street: String, customer-city: String)
Depositer(customer-name: String, accno: int)
Loan (loan-number: int, branch-name: String, amount: real)

i. Create the above tables by properly specifying the primary keys and the
foreign keys.
ii. Enter at least five tuples for each relation.
iii. Find all the customers who have at least two accounts at the Main branch (ex.
SBI_ResidencyRoad).
iv. Find all the customers who have an account at all the branches located in a
specific city (Ex. Delhi).
v. Demonstrate how you delete all account tuples at every branch located in
a specific city (Ex. Bombay).
INTRODUCTION: This database is developed for supporting banking facilities. Details of the
branch along with the accounts and loans handled by them are recorded. Also details of the
depositors of the corresponding branches are maintained.
Schema Diagram
Sample Table data

QUERY 1: Create the above tables by properly specifying the primary keys and the foreign
keys.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL
QUERY 2: Enter at least five tuples for each relation

Insert records for Loan


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Similarly insert records for BankAccount, Depositer and BankCustomer


SQL> commit;

Commit complete.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

QUERY 3: Find Find all the customers who have at least two deposits at
the same branch (Ex. ‘SBI_ResidencyRoad’).

QUERY 4: Find all the customers who have an account at all the
branches located in a specific city (Ex. Delhi).

QUERY 5: Demonstrate how you delete all account tuples at every branch located in a
specific city (Ex. Bomay).
ADDITIONAL QUERIES:
1. LIST THE ENTIRE LOAN RELATION IN THE DESCENDING ORDER OF
AMOUNT.
SQL> SELECT * FROM LOAN ORDER BY AMOUNT DESC;
2. FIND ALL CUSTOMERS HAVING A LAON, AN ACCOUNT OR BOTH AT THE
BANK
SQL> (SELECT CUSTOMER_NAME FROM DEPOSITOR ) UNION (SELECT CUSTOMER_NAME FROM
BORROWER);

3. CREATE A VIEW WHICH GIVES EACH BRANCH THE SUM OF THE AMOUNT
OF ALL THE LOANS AT THE BRANCH.
SQL> CREATE VIEW BRANCH_TOTAL_LOAN (BRANCH_NAME, TOTAL_LOAN) AS SELECT
BRANCH_NAME, SUM(AMOUNT) FROM LOAN GROUP BY BRANCH_NAME;
4. THE ANNUAL INTEREST PAYMENTS ARE MADE AND ALL BRANCHES ARE
TO BE INCREASED BY 5%.
SQL> UPDATE ACCOUNT SET BALANCE=BALANCE *1.05;

PROGRAM 3: SUPPLIER DATABASE


Consider the following schema:
SUPPLIERS(sid: integer, sname: string, address: string)
PARTS(pid: integer, pname: string, color: string)
CATALOG(sid: integer, pid: integer, cost: real)
The Catalog relation lists the prices charged for parts by Suppliers.
Write the following queries in SQL:
i) Find the pnames of parts for which there is some supplier.
ii) Find the snames of suppliers who supply every part.
iii) Find the snames of suppliers who supply every red part.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

iv) Find the pnames of parts supplied by Acme Widget Suppliers and by no one else.
v) Find the sids of suppliers who charge more for some part than the average cost of that
part (averaged over all the suppliers who supply that part).
vi) For each part, find the sname of the supplier who charges the most for that part.

Schema Diagram

Table Data

CREATION of Tables:
SQL> create table SUPPLIERS(sid number(5) primary key, sname varchar(20), city varchar(20));
Table created.

SQL> desc SUPPLIERS;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
SNAME VARCHAR2(20)
CITY VARCHAR2(20)

SQL> create table PARTS(pid number(5) primary key, pname varchar(20), color varchar(10));

Table created.

SQL> desc PARTS;


Name Null? Type
----------------------------------------- -------- ----------------------------
PID NOT NULL NUMBER(5)
PNAME VARCHAR2(20)
COLOR VARCHAR2(10)

SQL> create table CATALOG(sid number(5), pid number(5), foreign key(sid)


references SUPPLIERS(sid), foreign key(pid) references PARTS(pid), cost float(6),
primary key(sid, pid));

Table created.

SQL> desc CATALOG;


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL NUMBER(5)
PID NOT NULL NUMBER(5)
COST FLOAT(6)
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

INSERTION OF DATA:

SQL> insert into suppliers values(&sid, '&sname','&city');


Enter value for sid: 10001
Enter value for sname: Acme Widget
Enter value for address: Bangalore
old 1: insert into suppliers values(&sid, '&sname','&city')
new 1: insert into suppliers values(10001, 'Acme Widget','Bangalore')

1 row created.

SQL> /
Enter value for sid: 10002
Enter value for sname: Johns
Enter value for address: Kolkata
old 1: insert into suppliers values(&sid, '&sname','&city')
new 1: insert into suppliers values(10002, 'Johns','Kolkata')

1 row created.

SQL> /
Enter value for sid: 10003
Enter value for sname: Vimal
Enter value for address: Mumbai
old 1: insert into suppliers values(&sid, '&sname','&city')
new 1: insert into suppliers values(10003, 'Vimal','Mumbai')

1 row created.

SQL> /
Enter value for sid: 10004
Enter value for sname: Reliance
Enter value for address: Delhi
old 1: insert into suppliers values(&sid, '&sname','&city')
new 1: insert into suppliers values(10004, 'Reliance','Delhi')

1 row created.

SQL> /
Enter value for sid: 10005
Enter value for sname: Mahindra
Enter value for address: Mumbai
old 1: insert into suppliers values(&sid, '&sname','&city')
new 1: insert into suppliers values(10005, 'Mahindra','Mumbai')

1 row created.

SQL> select * from SUPPLIERS;

SID SNAME CITY


---------- -------------------- --------------------
10001 Acme Widget Bangalore
10002 Johns Kolkata
10003 Vimal Mumbai
10004 Reliance Delhi

SQL> commit;

Commit complete.

SQL> insert into PARTS values(&pid, '&pname','&color');


Enter value for pid: 20001
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Enter value for pname: Book


Enter value for color: Red
old 1: insert into PARTS values(&pid, '&pname','&color')
new 1: insert into PARTS values(20001, 'Book','Red')

1 row created.

SQL> /
Enter value for pid: 20002
Enter value for pname: Pen
Enter value for color: Red
old 1: insert into PARTS values(&pid, '&pname','&color')
new 1: insert into PARTS values(20002, 'Pen','Red')

1 row created.

SQL> /
Enter value for pid: 20003
Enter value for pname: Pencil
Enter value for color: Green
old 1: insert into PARTS values(&pid, '&pname','&color')
new 1: insert into PARTS values(20003, 'Pencil','Green')

1 row created.

SQL> /
Enter value for pid: 20004
Enter value for pname: Mobile
Enter value for color: Green
old 1: insert into PARTS values(&pid, '&pname','&color')
new 1: insert into PARTS values(20004, 'Mobile','Green')
1 row created.

SQL> /
Enter value for pid: 20005
Enter value for pname: Charger
Enter value for color: Black
old 1: insert into PARTS values(&pid, '&pname','&color')
new 1: insert into PARTS values(20005, 'Charger','Black')

1 row created.

SQL> select * from PARTS;

PID PNAME COLOR


---------- -------------------- ----------
20001 Book Red
20002 Pen Red
20003 Pencil Green
20004 Mobile Green
20005 Charger Black

SQL> commit;

Commit complete.

SQL> insert into CATALOG values(&sid, '&pid','&cost');


Enter value for sid: 10001
Enter value for pid: 20001
Enter value for cost: 10
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

old 1: insert into CATALOG values(&sid, '&pid','&cost')


new 1: insert into CATALOG values(10001, '20001','10')

1 row created.

SQL> /
Enter value for sid: 10001
Enter value for pid: 20002
Enter value for cost: 10
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10001, '20002','10')

1 row created.

SQL> /
Enter value for sid: 10001
Enter value for pid: 20003
Enter value for cost: 30
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10001, '20003','30')

1 row created.

SQL> /
Enter value for sid: 10001
Enter value for pid: 20004
Enter value for cost: 10
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10001, '20004','10')

1 row created.
SQL> /
Enter value for sid: 10001
Enter value for pid: 20005
Enter value for cost: 10
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10001, '20005','10')

1 row created.

SQL> /
Enter value for sid: 10002
Enter value for pid: 20001
Enter value for cost: 10
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10002, '20001','10')

1 row created.

SQL> /
Enter value for sid: 10002
Enter value for pid: 20002
Enter value for cost: 20
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10002, '20002','20')

1 row created.

SQL> /
Enter value for sid: 10003
Enter value for pid: 20003
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Enter value for cost: 30


old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10003, '20003','30')

1 row created.

SQL> /
Enter value for sid: 10004
Enter value for pid: 20003
Enter value for cost: 40
old 1: insert into CATALOG values(&sid, '&pid','&cost')
new 1: insert into CATALOG values(10004, '20003','40')

1 row created.

SQL> select * from CATALOG;

SID PID COST


---------- ---------- ----------
10001 20001 10
10001 20002 10
10001 20003 30
10001 20004 10
10001 20005 10
10002 20001 10
10002 20002 20
10003 20003 30
10004 20003 40

9 rows selected.
i) Find the pnames of parts for which there is some supplier.

SQL> SELECT DISTINCT P.pname


2 FROM Parts P, Catalog C
3 WHERE P.pid = C.pid;

PNAME
--------------------
Book
Charger
Mobile
Pen
Pencil

ii) Find the snames of suppliers who supply every part.

SQL> SELECT S.sname


2 FROM Suppliers S
3 WHERE NOT EXISTS ((SELECT P.pid FROM Parts P)
4 MINUS (SELECT C.pid FROM Catalog C
5 WHERE C.sid = S.sid));

SNAME
--------------------
Acme Widget

iii) Find the snames of suppliers who supply every red part.

SQL>SELECT S.sname
FROM Suppliers S
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

WHERE NOT EXISTS (( SELECT P.pid


FROM Parts P
WHERE P.color = ‘Red’ )
MINUS
( SELECT C.pid
FROM Catalog C, Parts P
WHERE C.sid = S.sid AND
C.pid = P.pid AND P.color = ‘Red’ ));
SNAME
--------------------
Acme Widget
Johns

iv) Find the pnames of parts supplied by Acme Widget Suppliers and by no one else.

PNAME
--------------------
Mobile
Charger

v) Find the sids of suppliers who charge more for some part than the average cost of
that part (averaged over all the suppliers who supply that part).

SQL> SELECT DISTINCT C.sid FROM Catalog C


2 WHERE C.cost > ( SELECT AVG (C1.cost)
3 FROM Catalog C1
4 WHERE C1.pid = C.pid );
SID
----------
10002
10004
vi) For each part, find the sname of the supplier who charges the most for that part.

SQL>SELECT P.pid, S.sname


FROM Parts P, Suppliers S, Catalog C
WHERE C.pid = P.pid
AND C.sid = S.sid
AND C.cost = (SELECT MAX (C1.cost)
FROM Catalog C1
WHERE C1.pid = P.pid);

PID SNAME
---------- --------------------
20001 Acme Widget
20004 Acme Widget
20005 Acme Widget
20001 Johns
20002 Johns
20003 Reliance

6 rows selected.

PROGRAM 4: STUDENT FACULTY DATABASE

Consider the following database for student enrollment for course :


STUDENT(snum: integer, sname: string, major: string, lvl: string, age: integer)
CLASS(cname: string, meets at: time, room: string, fid: integer)
ENROLLED(snum: integer, cname: string)
FACULTY(fid: integer, fname: string, deptid: integer)
The meaning of these relations is straightforward; for example, Enrolled has one record
per student-class pair such that the student is enrolled in the class. Level(lvl) is a two
character code with 4 different values (example: Junior: JR etc)
Write the following queries in SQL. No duplicates should be printed in any of the answers.
i. Find the names of all Juniors (level = JR) who are enrolled in a class taught by
ii. Find the names of all classes that either meet in room R128 or have five or more
Students enrolled.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

iii. Find the names of all students who are enrolled in two classes that meet at the same
time.
iv. Find the names of faculty members who teach in every room in which some class is
taught.
v. Find the names of faculty members for whom the combined enrollment of the courses
that they teach is less than five.
vi. Find the names of students who are not enrolled in any class.
vii. For each age value that appears in Students, find the level value that appears most
often. For example, if there are more FR level students aged 18 than SR, JR, or SO
students aged 18, you should print the pair (18, FR).

SQL> CREATE TABLE student(


2 snum INT,
3 sname VARCHAR(10),
4 major VARCHAR(2),
5 lvl VARCHAR(2),
6 age INT, primary key(snum));

Table created.

SQL> desc student;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNUM NOT NULL NUMBER(38)
SNAME VARCHAR2(10)
MAJOR VARCHAR2(2)
LVL VARCHAR2(2)
AGE NUMBER(38)

SQL> CREATE TABLE faculty(


2 fid INT,fname VARCHAR(20),
3 deptid INT,
4 PRIMARY KEY(fid));

Table created.

SQL> desc faculty;


Name Null? Type
----------------------------------------- -------- ----------------------------
FID NOT NULL NUMBER(38)
FNAME VARCHAR2(20)
DEPTID NUMBER(38)

SQL> CREATE TABLE class(


2 cname VARCHAR(20),
3 metts_at TIMESTAMP,
4 room VARCHAR(10),
5 fid INT,
6 PRIMARY KEY(cname),
7 FOREIGN KEY(fid) REFERENCES faculty(fid));

Table created.

SQL> DESC class;


Name Null? Type
----------------------------------------- -------- ----------------------------
CNAME NOT NULL VARCHAR2(20)
METTS_AT TIMESTAMP(6)
ROOM VARCHAR2(10)
FID NUMBER(38)

SQL> CREATE TABLE enrolled(


2 snum INT,
3 cname VARCHAR(20),
4 PRIMARY KEY(snum,cname),
5 FOREIGN KEY(snum) REFERENCES student(snum),
6 FOREIGN KEY(cname) REFERENCES class(cname));

Table created.

SQL> desc enrolled;


Name Null? Type
----------------------------------------- -------- ----------------------------
SNUM NOT NULL NUMBER(38)
CNAME NOT NULL VARCHAR2(20)

SQL> commit;

Commit complete.

INSERTION OF VALUES:

SQL> INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age);


Enter value for snum: 1
Enter value for sname: jhon
Enter value for major: CS
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

Enter value for lvl: Sr


Enter value for age: 19
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(1, 'jhon', 'CS', 'Sr', 19)

1 row created.

SQL> /
Enter value for snum: 2
Enter value for sname: Smith
Enter value for major: CS
Enter value for lvl: Jr
Enter value for age: 20
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(2, 'Smith', 'CS', 'Jr', 20)

1 row created.

SQL> /
Enter value for snum: 3
Enter value for sname: Jacob
Enter value for major: CV
Enter value for lvl: Sr
Enter value for age: 20
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(3 , 'Jacob', 'CV', 'Sr', 20)

1 row created.

SQL> /
Enter value for snum: 4
Enter value for sname: Tom
Enter value for major: CS
Enter value for lvl: Jr
Enter value for age: 20
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(4, 'Tom ', 'CS', 'Jr', 20)

1 row created.

SQL> /
Enter value for snum: 5
Enter value for sname: Rahul
Enter value for major: CS
Enter value for lvl: Jr
Enter value for age: 20
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(5, 'Rahul', 'CS', 'Jr', 20)

1 row created.

SQL> /
Enter value for snum: 6
Enter value for sname: Rita
Enter value for major: CS
Enter value for lvl: Sr
Enter value for age: 21
old 1: INSERT INTO STUDENT VALUES(&snum, '&sname', '&major', '&lvl', &age)
new 1: INSERT INTO STUDENT VALUES(6, 'Rita', 'CS', 'Sr', 21)

1 row created.

SQL> select * from student;

SNUM SNAME MA LV AGE


---------- ---------- -- -- ----------
1 jhon CS Sr 19
2 Smith CS Jr 20
3 Jacob CV Sr 20
4 Tom CS Jr 20
5 Rahul CS Jr 20
6 Rita CS Sr 21

6 rows selected.

SQL> INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID);


Enter value for fid: 11
Enter value for fname: Harish
Enter value for deptid: 1000
old 1: INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID)
new 1: INSERT INTO FACULTY VALUES(11, 'Harish', 1000)

1 row created.

SQL> /
Enter value for fid: 12
Enter value for fname: MV
Enter value for deptid: 1000
old 1: INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID)
new 1: INSERT INTO FACULTY VALUES(12, 'MV', 1000)

1 row created.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

SQL> /
Enter value for fid: 13
Enter value for fname: Mira
Enter value for deptid: 1001
old 1: INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID)
new 1: INSERT INTO FACULTY VALUES(13 , 'Mira', 1001)

1 row created.

SQL> /
Enter value for fid: 14
Enter value for fname: Shiva
Enter value for deptid: 1002
old 1: INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID)
new 1: INSERT INTO FACULTY VALUES(14, 'Shiva', 1002)

1 row created.

SQL> /
Enter value for fid: 15
Enter value for fname: Nupur
Enter value for deptid: 1000
old 1: INSERT INTO FACULTY VALUES(&FID, '&FNAME', &DEPTID)
new 1: INSERT INTO FACULTY VALUES(15, 'Nupur', 1000)

1 row created.

SQL> commit;

Commit complete.

SQL> select * from faculty;

FID FNAME DEPTID


---------- -------------------- ----------
11 Harish 1000
12 MV 1000
13 Mira 1001
14 Shiva 1002
15 Nupur 1000

SQL> commit;

Commit complete.
SQL> alter session set nls_timestamp_format = 'RR/MM/DD HH24:MI:SSXFF';

Session altered.

SQL> alter session set nls_date_language ='ENGLISH';

Session altered.

SQL> insert into class values('&cname', '&meets_at', '&room', &fid);


Enter value for cname: class1
Enter value for meets_at: 12/11/15 10:15:16
Enter value for room: R1
Enter value for fid: 14
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class1', '12/11/15 10:15:16', 'R1', 14)

1 row created.

Enter value for cname: class10


Enter value for meets_at: 12/11/15 10:15:16
Enter value for room: R128
Enter value for fid: 14
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class10', '12/11/15 10:15:16', 'R128', 14)

1 row created.

SQL> /
Enter value for cname: class2
Enter value for meets_at: 12/11/15 10:15:20
Enter value for room: R2
Enter value for fid: 12
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class2', '12/11/15 10:15:20', 'R2', 12)

1 row created.

SQL> insert into class values('&cname', '&meets_at', '&room', &fid);


Enter value for cname: class3
Enter value for meets_at: 12/11/15 10:15:25
Enter value for room: R3
Enter value for fid: 11
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class3', '12/11/15 10:15:25', 'R3', 12)
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

1 row created.

SQL> /
Enter value for cname: class4
Enter value for meets_at: 12/11/15 20:15:20
Enter value for room: R4
Enter value for fid: 14
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class4', '12/11/15 20:15:20', 'R4', 14)

1 row created.

SQL> /
Enter value for cname: class5
Enter value for meets_at: 12/11/15 20:15:20
Enter value for room: R3
Enter value for fid: 15
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class5', '12/11/15 20:15:20', 'R3', 15)

1 row created.

SQL> /
Enter value for cname: class6
Enter value for meets_at: 12/11/15 13:20:20
Enter value for room: R2
Enter value for fid: 14
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class6', '12/11/15 13:20:20', 'R2', 14)

1 row created.

SQL> /
Enter value for cname: class7
Enter value for meets_at: 12/11/15 10:10:10
Enter value for room: R3
Enter value for fid: 14
old 1: insert into class values('&cname', '&meets_at', '&room', &fid)
new 1: insert into class values('class7', '12/11/15 10:10:10', 'R3', 14)

1 row created.

SQL> select * from class;

CNAME
--------------------
METTS_AT
---------------------------------------------------------------------------
ROOM FID
---------- ----------
class1
12/11/15 10:15:16.000000
R1 14

class10
12/11/15 10:15:16.000000
R128 14

CNAME
--------------------
METTS_AT
---------------------------------------------------------------------------
ROOM FID
---------- ----------

class2
12/11/15 10:15:20.000000
R2 12

class3
12/11/15 10:15:25.000000

CNAME
--------------------
METTS_AT
---------------------------------------------------------------------------
ROOM FID
---------- ----------
R3 11

class4
12/11/15 20:15:20.000000
R4 14

class5

CNAME
--------------------
METTS_AT
---------------------------------------------------------------------------
ROOM FID
---------- ----------
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

12/11/15 20:15:20.000000
R3 15

class6
12/11/15 13:20:20.000000
R2 14

CNAME
--------------------
METTS_AT
---------------------------------------------------------------------------
ROOM FID
---------- ----------
class7
12/11/15 10:10:10.000000
R3 14

8 rows selected.

SQL> commit;

Commit complete.

SQL> insert into enrolled values(&snum, '&cname');


Enter value for snum: 1
Enter value for cname: class1
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(1, 'class1')

1 row created.

SQL> /
Enter value for snum: 2
Enter value for cname: class1
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(2, 'class1')

1 row created.

SQL> /
Enter value for snum: 3
Enter value for cname: class3
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(3, 'class3')
1 row created.

SQL> /
Enter value for snum: 4
Enter value for cname: class3
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(4, 'class3')

1 row created.

SQL> /
Enter value for snum: 5
Enter value for cname: class4
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(5, 'class4')

1 row created.

SQL> /
Enter value for snum: 1
Enter value for cname: class5
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(1, 'class5')

1 row created.

SQL> /
Enter value for snum: 2
Enter value for cname: class5
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(2, 'class5')

1 row created.

SQL> /
Enter value for snum: 3
Enter value for cname: class5
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(3, 'class5')

1 row created.

SQL> /
Enter value for snum: 4
Enter value for cname: class5
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

old 1: insert into enrolled values(&snum, '&cname')


new 1: insert into enrolled values(4, 'class5')

1 row created.

SQL> /
Enter value for snum: 5
Enter value for cname: class5
old 1: insert into enrolled values(&snum, '&cname')
new 1: insert into enrolled values(5, 'class5')

1 row created.

SQL> select * from enrolled;

SNUM CNAME
---------- --------------------
1 class1
2 class1
3 class3
4 class3
5 class4
1 class5
2 class5
3 class5
4 class5
5 class5

10 rows selected.

viii. Find the names of all Juniors (level(lvl) = Jr) who are enrolled in a class taught
by Harish.

SELECT DISTINCT S.Sname


FROM Student S, Class C, Enrolled E, Faculty F
WHERE S.snum = E.snum AND E.cname = C.cname AND C.fid = F.fid AND
F.fname = ‘Harish’ AND S.lvl = ‘Jr’;

SNAME
----------
Tom

ix. Find the names of all classes that either meet in room R128 or have five or more
Students enrolled.

SQL>SELECT C.cname
FROM Class C
WHERE C.room = ‘R128’
OR C.cname IN (SELECT E.cname
FROM Enrolled E
GROUP BY E.cname
HAVING COUNT (*) >= 5);

CNAME
--------------------
class10
class5
x. Find the names of all students who are enrolled in two classes that meet at the same
time.
SQL>SELECT DISTINCT S.sname
FROM Student S
WHERE S.snum IN (SELECT E1.snum
FROM Enrolled E1, Enrolled E2, Class C1, Class C2
WHERE E1.snum = E2.snum AND E1.cname <> E2.cname
AND E1.cname = C1.cname
AND E2.cname = C2.cname AND C1.meets_at = C2.meets_at);
SNAME
----------
Rahul
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

xi. Find the names of faculty members who teach in every room in which some class
is taught.

SELECT DISTINCT F.fname


FROM Faculty F
WHERE NOT EXISTS ((SELECT C.roomFROM Class C )
MINUS
(SELECTC1.room
FROM Class C1
WHERE C1.fid = F.fid ));

FNAME
--------------------
Shiva

xii. Find the names of faculty members for whom the combined enrollment of the
courses that they teach is less than five.
SQL>SELECT DISTINCT F.fname
FROM Faculty F
WHERE 5 > (SELECT COUNT (E.snum)
FROM Class C, Enrolled E
WHERE C.cname = E.cname
AND C.fid = F.fid)

FNAME
--------------------
Harish
MV
Mira
Shiva

xiii. Find the names of students who are not enrolled in any class.

SELECT DISTINCT S.sname


FROM Student S
WHERE S.snum NOT IN (SELECT E.snum
FROM Enrolled E );

SNAME

----------

Rita

xiv. For each age value that appears in Students, find the level value that appears
most often. For example, if there are more FR level students aged 18 than SR,
JR, or SO students aged 18, you should print the pair (18, FR).

SELECT S.age, S.lvl


FROM Student S
GROUP BY S.age, S.lvl
HAVING S.lvl IN (SELECT S1.lvl FROM Student S1
WHERE S1.age = S.age
GROUP BY S1.lvl, S1.age
HAVING COUNT (*) >= ALL (SELECT COUNT (*)
FROM Student S2
WHERE s1.age = S2.age
GROUP BY S2.lvl, S2.age));

AGE LV

---------- --

19 Sr

20 Jr

21 Sr
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

PROGRAM 5: AIRLINE FLIGHT DATABASE

Consider the following database that keeps track of airline flight information:
FLIGHTS(flno: integer, from: string, to: string, distance: integer, departs: time, arrives:
time, price: integer)
AIRCRAFT(aid: integer, aname: string, cruisingrange: integer)
CERTIFIED(eid: integer, aid: integer)
EMPLOYEES(eid: integer, ename: string, salary: integer)
Note that the Employees relation describes pilots and other kinds of employees as well;
Every pilot is certified for some aircraft, and only pilots are certified to fly.
Write each of the following queries in SQL.
i. Find the names of aircraft such that all pilots certified to operate them have salaries
more than Rs.80,000.
ii. For each pilot who is certified for more than three aircrafts, find the eid and the
maximum cruisingrange of the aircraft for which she or he is certified.
iii. Find the names of pilots whose salary is less than the price of the cheapest route from
Bengaluru to Frankfurt.
iv. For all aircraft with cruisingrange over 1000 Kms, find the name of the aircraft and
the average salary of all pilots certified for this aircraft.
v. Find the names of pilots certified for some Boeing aircraft.
vi. Find the aids of all aircraft that can be used on routes from Bengaluru to New Delhi.
vii. A customer wants to travel from Madison to New York with no more than two
changes of flight. List the choice of departure times from Madison if the customer
wants to arrive in New York by 6 p.m.

CREATION OF TABLES:

SQL> CREATE TABLE FLIGHTS


2 (FLNO INTEGER PRIMARY KEY,
3 FFROM VARCHAR(15) NOT NULL,
4 TTO VARCHAR(15) NOT NULL,
5 DISTANCE INTEGER,
6 DEPARTS TIMESTAMP,
7 ARRIVES TIMESTAMP,
8 PRICE NUMBER(10,2));

Table created.

SQL> DESC FLIGHTS;


Name Null? Type
----------------------------------------- -------- ----------------------------
FLNO NOT NULL NUMBER(38)
FFROM NOT NULL VARCHAR2(15)
TTO NOT NULL VARCHAR2(15)
DISTANCE NUMBER(38)
DEPARTS TIMESTAMP(6)
ARRIVES TIMESTAMP(6)
PRICE NUMBER(10,2)

SQL> CREATE TABLE AIRCRAFT


2 (AID INTEGER PRIMARY KEY,
3 ANAME VARCHAR(10),
4 CRUISINGRANGE INTEGER);

Table created.

SQL> DESC AIRCRAFT;


Name Null? Type
----------------------------------------- -------- ----------------------------
AID NOT NULL NUMBER(38)
ANAME VARCHAR2(10)
CRUISINGRANGE NUMBER(38)

SQL> CREATE TABLE EMPLOYEES


2 (EID INTEGER PRIMARY KEY,
3 ENAME VARCHAR(15),
4 SALARY NUMBER(10,2));

Table created.

SQL> DESC EMPLOYEES;


Name Null? Type
----------------------------------------- -------- ----------------------------
EID NOT NULL NUMBER(38)
ENAME VARCHAR2(15)
SALARY NUMBER(10,2)

SQL> CREATE TABLE CERTIFIED


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

2 (EID INTEGER NOT NULL,


3 AID INTEGER NOT NULL,
4 PRIMARY KEY (EID, AID),
5 FOREIGN KEY (EID) REFERENCES EMPLOYEES (EID),
6 FOREIGN KEY (AID) REFERENCES AIRCRAFT (AID));

Table created.

SQL> DESC CERTIFIED;


Name Null? Type
----------------------------------------- -------- ----------------------------
EID NOT NULL NUMBER(38)
AID NOT NULL NUMBER(38)

SQL> COMMIT;

Commit complete.

INSERTION OF VALUES:

INSERT IN TO AIRCRAFT VALUES::

SQL> insert into aircraft values(101,'747',3000);

1 row created.

SQL> insert into aircraft values(102,'Boeing',900);

1 row created.

SQL> insert into aircraft values(103,'647',800);

1 row created.

SQL> insert into aircraft values(104,'Dreamliner',10000);

1 row created.

SQL> insert into aircraft values(105,'Boeing',3500);

1 row created.

SQL> insert into aircraft values(106,'707',1500);

1 row created.
SQL> insert into aircraft values(107,'Dream', 120000);
1 row created.

INSERT INTO EMPLOYEES TABLE:

SQL> insert into employees values(701,'A',50000);

1 row created.

SQL> insert into employees values(702,'B',100000);

1 row created.

SQL> insert into employees values(703,'C',150000);

1 row created.

SQL> insert into employees values(704,'D',90000);

1 row created.

SQL> insert into employees values(705,'E',40000);

1 row created.

SQL> insert into employees values(706,'F',60000);

1 row created.

SQL> insert into employees values(707,'G',90000);

1 row created.

INSERT INTO CERTIFIED TABLE:

SQL> insert into certified values(701,101);

1 row created.

SQL> insert into certified values(701,102);

1 row created.

SQL> insert into certified values(701,106);


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

1 row created.

SQL> insert into certified values(701,105);

1 row created.

SQL> insert into certified values(702,104);

1 row created.

SQL> insert into certified values(703,104);

1 row created.

SQL> insert into certified values(704,104);

1 row created.

SQL> insert into certified values(702,107);

1 row created.

SQL> insert into certified values(703,107);

1 row created.

SQL> insert into certified values(704,107);

1 row created.

SQL> insert into certified values(702,101);

1 row created.

SQL> insert into certified values(703,105);

1 row created.

SQL> insert into certified values(704,105);

1 row created.

SQL> insert into certified values(705,103);

1 row created.
SQL> alter session set nls_timestamp_format = 'RR/MM/DD HH24:MI:SSXFF';

Session altered.

SQL> alter session set nls_date_language ='ENGLISH';

Session altered.

INSERT INTO FLIGHTS Table:

SQL> insert into flights values(101,'Bangalore','Delhi',2500,TIMESTAMP '2005-05-13


07:15:31',TIMESTAMP '2005-05-13 17:15:31',5000);

1 row created.

SQL> insert into flights values(102,'Bangalore','Lucknow',3000,TIMESTAMP '2005-05-13


07:15:31',TIMESTAMP '2005-05-13 11:15:31',6000);

1 row created.

SQL> insert into flights values(103,'Lucknow','Delhi',500,TIMESTAMP '2005-05-13


12:15:31',TIMESTAMP ' 2005-05-13 17:15:31',3000);

1 row created.

SQL> insert into flights values(107,'Bangalore','Frankfurt',8000,TIMESTAMP '2005-05-


13 07:15:31',TIMESTAMP '2005-05-13 22:15:31',60000);

1 row created.

SQL> insert into flights values(104,'Bangalore','Frankfurt',8500,TIMESTAMP '2005-05-


13 07:15:31',TIMESTAMP '2005-05-13 23:15:31',75000);

1 row created.

SQL> insert into flights values(105,'Kolkata','Delhi',3400,TIMESTAMP '2005-05-13


07:15:31',TIMESTAMP '2005-05-13 09:15:31',7000);

1 row created.

SQL> select * from Flights;

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
101 Bangalore Delhi 2500
13-MAY-05 07.15.31.000000 AM
13-MAY-05 07.15.31.000000 AM
5000

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
102 Bangalore Lucknow 3000
13-MAY-05 07.15.
FLNO FFROM TTO DISTANCE
---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
101 Bangalore Delhi 2500
05/05/13 07:15:31.000000
05/05/13 17:15:31.000000
5000

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
102 Bangalore Lucknow 3000
05/05/13 07:15:31.000000
05/05/13 11:15:31.000000
6000

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
103 Lucknow Delhi 500
05/05/13 12:15:31.000000
05/05/13 17:15:31.000000
3000

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
107 Bangalore Frankfurt 8000
05/05/13 07:15:31.000000
05/05/13 22:15:31.000000
60000

FLNO FFROM TTO DISTANCE


---------- --------------- --------------- ----------
DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
104 Bangalore Frankfurt 8500
05/05/13 07:15:31.000000
05/05/13 23:15:31.000000
75000

FLNO FFROM TTO DISTANCE


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

---------- --------------- --------------- ----------


DEPARTS
---------------------------------------------------------------------------
ARRIVES
---------------------------------------------------------------------------
PRICE
----------
105 Kolkata Delhi 3400
05/05/13 07:15:31.000000
05/05/13 09:15:31.000000
7000

6 rows selected.

SQL> select * from Aircraft;

AID ANAME CRUISINGRANGE


---------- ---------- -------------
101 747 3000
102 Boeing 900
103 647 800
104 Dreamliner 10000
105 Boeing 3500
106 707 1500
107 Dream 120000

7 rows selected.

SQL> select * from Certified;

EID AID
---------- ----------
701 101
701 102
701 106
701 105
702 104
703 104
704 104
702 107
703 107
704 107
702 101

EID AID
---------- ----------
703 105
704 105
705 103

14 rows selected.

SQL> select * from Employees;

EID ENAME SALARY


---------- --------------- ----------
701 A 50000
702 B 100000
703 C 150000
704 D 90000
705 E 40000
706 F 60000
707 G 90000

7 rows selected.

viii. Find the names of aircraft such that all pilots certified to operate them have
salaries more than Rs.80,000.

SQL>SELECT DISTINCT A.aname


FROM Aircraft A
WHERE A.Aid IN (SELECT C.aid
FROM Certified C, Employees E
WHERE C.eid = E.eid AND
NOT EXISTS ( SELECT *
FROM Employees E1
WHERE E1.eid = E.eid AND E1.salary <80000 ));

ANAME
----------
747
Boeing
Dream
Dreamliner

ix. For each pilot who is certified for more than three aircrafts, find the eid and the
maximum cruising range of the aircraft for which she or he is certified.

SQL>SELECT C.eid, MAX (A.cruisingrange)


FROM Certified C, Aircraft A
WHERE C.aid = A.aid
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

GROUP BY C.eid
HAVING COUNT (*) > 3;

EID MAX(A.CRUISINGRANGE)
---------- --------------------
701 3500

x. Find the names of pilots whose salary is less than the price of the cheapest route
from Bangalore to Frankfurt.

SELECT DISTINCT E.ename


FROM Employees E
WHERE E.salary <( SELECT MIN(F.price)
FROM Flights F
WHERE F.ffrom = ‘Bangalore’ AND F.tto = ‘Frankfurt’ );

ENAME
---------------
A
E

xi. For all aircraft with cruising range over 1000 Kms, find the name of the aircraft
and the average salary of all pilots certified for this aircraft.

SELECT Temp.name, Temp.AvgSalary


FROM ( SELECT A.aid, A.aname AS name, AVG (E.salary) AS AvgSalary
FROM Aircraft A, Certified C, Employees E
WHERE A.aid = C.aid AND C.eid = E.eid AND A.cruisingrange > 1000
GROUP BY A.aid, A.aname ) Temp;

NAME AVGSALARY
---------- ----------
747 75000
Dreamliner 113333.333
Boeing 96666.6667
707 50000
Dream 113333.333

xii. Find the names of pilots certified for some Boeing aircraft.

SELECT DISTINCT E.ename


FROM Employees E, Certified C, Aircraft A
WHERE E.eid = C.eid AND C.aid = A.aid AND A.aname LIKE ‘Boeing%’;
ENAME
---------------
A
C
D

xiii. Find the aids of all aircraft that can be used on routes from Bangalore to
Frankfurt.

SELECT A.aid
FROM Aircraft A
WHERE A.cruisingrange >( SELECT MIN (F.distance)
FROM Flights F
WHERE F.ffrom = ‘Bangalore’ AND F.tto = ‘Frankfurt’ );

AID
----------
104
107

xiv. A customer wants to travel from Bangalore to Delhi with no more than two
changes of flight. List the choice of departure times from Bangalore if the
customer wants to arrive in Delhi by 6 p.m.

SELECT F.departs
FROM Flights F
WHERE F.flno IN ( ( SELECT F0.flno
FROM Flights F0
WHERE F0.ffrom = ‘Bangalore’ AND F0.tto = ‘Delhi’
AND extract(hour from F0.arrives) < 18 )
UNION
( SELECT F0.flno
FROM Flights F0, Flights F1
WHERE F0.ffrom = ‘Bangalore’ AND F0.tto <> ‘Delhi’
AND F0.tto = F1.ffrom AND F1.tto = ‘Delhi’
AND F1.departs > F0.arrives
AND extract(hour from F1.arrives) < 18)
UNION
( SELECT F0.flno
FROM Flights F0, Flights F1, Flights F2
WHERE F0.ffrom = ‘Bangalore’
AND F0.tto = F1.ffrom
AND F1.tto = F2.ffrom
AND F2.tto = ‘Delhi’
AND F0.tto <> ‘Delhi’
AND F1.tto <> ‘Delhi’
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

AND F1.departs > F0.arrives


AND F2.departs > F1.arrives
AND extract(hour from F2.arrives) < 18));

DEPARTS
---------------------------------------------------------------------------
05/05/13 07:15:31.000000
05/05/13 07:15:31.000000

xv. Print the name and salary of every non-pilot whose salary is more than the
average salary for pilots.

SELECT E.ename, E.salary


FROM Employees E
WHERE E.eid NOT IN ( SELECT DISTINCT C.eid
FROM Certified C )
AND E.salary >( SELECT AVG (E1.salary)
FROM Employees E1
WHERE E1.eid IN
( SELECT DISTINCT C1.eid
FROM Certified C1 ) );

ENAME SALARY
--------------- ----------
G 90000
rt C: Practise Questions
SQL-QUERIES

Emp table data


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-Dec-80 800 20
7499 ALLEN SALESMAN 7698 20-Feb-81 1600 300 30
7521 WARD SALESMAN 7698 22-Feb-81 1250 500 30
7566 JONES MANAGER 7839 02-Apr-81 2975 20
7654 MARTIN SALESMAN 7698 28-Sep-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-May-81 2850 30
7782 CLARK MANAGER 7839 09-Jun-81 2450 10
7788 SCOTT ANALYST 7566 09-Dec-82 3000 20
7839 KING PRESIDENT 17-Nov-81 5000 10
7844 TURNER SALESMAN 7698 08-Sep-81 1500 0 30
7876 ADAMS CLERK 7788 12-Jan-83 1100 20
7900 JAMES CLERK 7698 03-Dec-81 950 30
7902 FORD ANALYST 7566 03-Dec-81 3000 20
7934 MILLER CLERK 7782 23-Jan-82 1300 10

Dept table data

DEPTNO DNAME LOC


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

1. Display all the information of the EMP table?


2. Display unique Jobs from EMP table?
3. List the emps in the asc order of their Salaries?
4. List the details of the emps in asc order of the Dptnos and desc of Jobs?
5. Display all the unique job groups in the descending order?
6. Display all the details of all ‘Mgrs’
7. List the emps who joined before 1981.
8. List the Empno, Ename, Sal, Daily sal of all emps in the asc order of Annsal.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

9. Display the Empno, Ename, job, Hiredate, Exp of all Mgrs


10. List the Empno, Ename, Sal, Exp of all emps working for Mgr 7369.
11. Display all the details of the emps whose Comm. Is more than their Sal.
12. List the emps in the asc order of Designations of those joined after the second half of
1981.

13. List the emps along with their Exp and Daily Sal is more than Rs.100.
14. List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.
15. List the emps who joined on 1-MAY-81,3-DEC-81,17-DEC-81,19-JAN-80 in asc order
of seniority.

16. List the emp who are working for the Deptno 10 or20.
17. List the emps who are joined in the year 81.
18. List the emps who are joined in the month of Aug 1980.
19. List the emps Who Annual sal ranging from 22000 and 45000.
20. List the Enames those are having five characters in their Names.
21. List the Enames those are starting with ‘S’ and with five characters.
22. List the emps those are having four chars and third character must be ‘r’.
23. List the Five character names starting with ‘S’ and ending with ‘H’.
24. List the emps who joined in January.
25. List the emps who joined in the month of which second character is ‘a’.
26. List the emps whose Sal is four digit number ending with Zero.
27. List the emps whose names having a character set ‘ll’ together.

28. List the emps those who joined in 80’s.

29. List the emps who does not belong to Deptno 20.
30. List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.
31. List all the emps who joined before or after 1981.
32. List the emps whose Empno not starting with digit78.
33. List the emps who are working under ‘MGR’.

34. List the emps who joined in any year but not belongs to the month of March.
35. List all the Clerks of Deptno 20.
36. List the emps of Deptno 30 or 10 joined in the year 1981.
37. Display the details of SMITH.
38. Display the location of SMITH.
39. List the total information of EMP table along with DNAME and Loc of all the emps
Working Under ‘ACCOUNTING’ & ‘RESEARCH’ in the asc Deptno.

40. List the Empno, Ename, Sal, Dname of all the ‘MGRS’ and ‘ANALYST’ working in
New York, Dallas with an exp more than 7 years without receiving the Comm asc order of Loc.
41. Display the Empno, Ename, Sal, Dname, Loc, Deptno, Job of all emps working at
CJICAGO or working for ACCOUNTING dept with Ann Sal>28000, but the Sal should not
be=3000 or 2800 who doesn’t belongs to the Mgr and whose no is having a digit ‘7’ or ‘8’ in 3rd
position in the asc order of Deptno and desc order of job.

42. Display the total information of the emps along with Grades in the asc order.

43. List all the Grade2 and Grade 3 emps.


44. Display all Grade 4,5 Analyst and Mgr.

45. List the Empno, Ename, Sal, Dname, Grade, Exp, and Ann Sal of emps working for
Dept10 or20.

46. List all the information of emp with Loc and the Grade of all the emps belong to the
Grade range from 2 to 4 working at the Dept those are not starting with char set ‘OP’ and not
ending with ‘S’ with the designation having a char ‘a’ any where joined in the year 1981 but not
in the month of Mar or Sep and Sal not end with ‘00’ in the asc order of Grades

47. List the details of the Depts along with Empno, Ename or without the emps
48. List the details of the emps whose Salaries more than the employee BLAKE.
49. List the emps whose Jobs are same as ALLEN.
50. List the emps who are senior to King.

51. List the Emps who are senior to their own MGRS.
52. List the Emps of Deptno 20 whose Jobs are same as Deptno10.

53. List the Emps whose Sal is same as FORD or SMITH in desc order of Sal.
54. List the emps Whose Jobs are same as MILLER or Sal is more than ALLEN.
55. List the Emps whose Sal is > the total remuneration of the SALESMAN.
56. List the emps who are senior to BLAKE working at CHICAGO & BOSTON.
57. List the Emps of Grade 3,4 belongs to the dept ACCOUNTING and RESEARCH whose
Sal is more than ALLEN and exp more than SMITH in the asc order of EXP.

58. List the emps whose jobs same as SMITH or ALLEN.

59. Write a Query to display the details of emps whose Sal is same as of

60. Any jobs of deptno 10 those that are not found in deptno 20.

61. List of emps of emp1 who are not found in emp2.


62. Find the highest sal of EMP table.
63. Find details of highest paid employee.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

64. Find the highest paid employee of sales department.


65. List the most recently hired emp of grade3 belongs to location CHICAGO.

66. List the employees who are senior to most recently hired employee working under king.

67. List the details of the employee belongs to newyork with grade 3 to 5 except
‘PRESIDENT’ whose sal> the highest paid employee of Chicago in a group where there is
manager and salesman not working under king

68. List the details of the senior employee belongs to 1981.

69. List the employees who joined in 1981 with the job same as the most senior person of the
year 1981.

70. List the most senior empl working under the king and grade is more than 3.

71. Find the total sal given to the MGR.

72. Find the total annual sal to distribute job wise in the year 81.

73. Display total sal employee belonging to grade 3.

74. Display the average salaries of all the clerks.

75. List the employeein dept 20 whose sal is >the average sal 0f dept 10 emps.

76. Display the number of employee for each job group deptno wise.

77. List the manage rno and the number of employees working for those mgrs in the
ascending Mgrno.

78. List the department,details where at least two emps are working

79. Display the Grade, Number of emps, and max sal of each grade.

80. Display dname, grade, No. of emps where at least two emps are clerks.

81. List the details of the department where maximum number of emps are working.

82. Display the emps whose manager name is jones.


83. List the employees whose salary is more than 3000 after giving 20% increment.

84. List the emps with dept names.

85. List the emps who are not working in sales dept.

86. List the emps name ,dept, sal and comm. For those whose salary is between 2000 and
5000 while loc is Chicago.
87. List the emps whose sal is greater than his managers salary

88. List the grade, EMP name for the deptno 10 or deptno 30 but sal grade is not 4 while they
joined the company before ’31-dec-82’.

89. List the name ,job, dname, location for those who are working as MGRS.

90. List the emps whose mgr name is jones and also list their manager name.

91. List the name and salary of ford if his salary is equal to hisal of his grade.

92. Lit the name, job, dname ,sal, grade dept wise

93. List the emp name, job, sal, grade and dname except clerks and sort on the basis of
highest sal.

94. List the emps name, job who are with out manager.

95. List the names of the emps who are getting the highest sal dept wise.

96. List the emps whose sal is equal to the average of max and minimum

97. List the no. of emps in each department where the no. is more than 3.

98. List the names of depts. Where atleast 3 are working in that department.

99. List the managers whose sal is more than his employess avg salary.
100. List the name,salary,comm. For those employees whose net pay is greater than or equal
to any other employee salary of the company.
101. List the emp whose sal<his manager but more than any other manager.

102. List the employee names and his average salary department wise.

103. Find out least 5 earners of the company.

104. Find out emps whose salaries greater than salaries of their managers.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

105. List the managers who are not working under the president.

106. List the records from emp whose deptno isnot in dept.

107. List the Name , Salary, Comm and Net Pay is more than any other employee.

108. List the Enames who are retiring after 31-Dec-89 the max Job period is 20Y.

109. List those Emps whose Salary is odd value.


110. List the emp’s whose Salary contain 3 digits.

111. List the emps who joined in the month of DEC.


112. List the emps whose names contains ‘A’.
113. List the emps whose Deptno is available in his Salary.

114. List the emps whose first 2 chars from Hiredate=last 2 characters of Salary.
115. List the emps Whose 10% of Salary is equal to year of joining.

116. List first 50% of chars of Ename in Lower Case and remaining are upper Case.

117. List the Dname whose No. of Emps is =to number of chars in the Dname.

118. List the emps those who joined in company before 15th of the month.

119. List the Dname, no of chars of which is = no. of emp’s in any other Dept.

120. List the emps who are working as Managers.

121. List THE Name of dept where highest no.of emps are working.

122. Count the No.of emps who are working as ‘Managers’(using set option).

123. List the emps who joined in the company on the same date.

124. List the details of the emps whose Grade is equal to one tenth of Sales Dept.

125. List the name of the dept where more than average no. of emps are working.

126. List the Managers name who is having max no.of emps working under him.

127. List the Ename and Sal is increased by 15% and expressed as no.of Dollars.

128. Produce the output of EMP table ‘EMP_AND_JOB’ for Ename and Job.

129. Produce the following output from EMP.


EMPLOYEE
SMITH (clerk)
ALLEN (Salesman)

130) List the emps with Hire date in format June 4, 1988.
131) Print a list of emp’s Listing ‘just salary’ if Salary is more than 1500, on target if Salary is
1500 and ‘Below 1500’ if Salary is less than 1500.

132) Write a query which return the day of the week for any date entered in format ‘DD-MM-
YY’.

133) Write a query to calculate the length of service of any employee with the company, use
DEFINE to avoid repetitive typing of functions.
134) Give a string of format ‘NN/NN’, verify that the first and last two characters are numbers
and that the middle character is’/’. Print the expression ‘YES’ if valid, ‘NO’ if not valid. Use the
following values to test your solution. ‘12/34’,’01/1a’, ‘99/98’.

135) Emps hired on or before 15th of any month are paid on the last Friday of that month those
hired after 15th are paid on the first Friday of the following month. Print a list of emps their hire
date and the first pay date. Sort on hire date.

136) Count the no. of characters with out considering spaces for each name.
137) Find out the emps who are getting decimal value in their Sal without using like operator.
138) List those emps whose Salary contains first four digit of their Deptno.
139) List those Managers who are getting less than his emps Salary.
140) Print the details of all the emps who are sub-ordinates to Blake.
141) List the emps who are working as Managers using co-related sub-query.
142) List the emps whose Mgr name is ‘Jones’ and also with his Manager name.
143) Define a variable representing the expression used to calculate on emps total annual
remuneration use the variable in a statement, which finds all emps who can earn 30000 a year or
more.

144) Find out how may Managers are their in the company.
145) Find Average salary and Average total remuneration for each Job type. Remember
Salesman earn commission.secommm

146) Check whether all the emps numbers are indeed unique.
147) List the emps who are drawing less than 1000 Sort the output by Salary.

148) List the employee Name, Job, Annual Salary, deptno, Dept name and grade who earn
36000 a year or who are not CLERKS.

149) Find out the Job that was filled in the first half of 1983 and same job that was filled
during the same period of 1984.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

150) Find out the emps who joined in the company before their Managers.

151) List all the emps by name and number along with their Manager’s name and number.
Also List KING who has no ‘Manager’.

152) Find all the emps who earn the minimum Salary for each job wise in ascending order.

153) Find out all the emps who earn highest salary in each job type. Sort in descending salary
order.
154) Find out the most recently hired emps in each Dept order by Hiredate.
155) List the employee name,Salary and Deptno for each employee who earns a salary greater
than the average for their department order by Deptno.

156) List the Deptno where there are no emps.


157) List the No.of emp’s and Avg salary within each department for each job.
158) Find the maximum average salary drawn for each job except for ‘President’.
159) Find the name and Job of the emps who earn Max salary and Commission.
160) List the Name, Job and Salary of the emps who are not belonging to the department 10
but who have the same job and Salary as the emps of dept 10.

161) List the Deptno, Name, Job, Salary and Sal+Comm of the SALESMAN who are earning
maximum salary and commission in descending order.
162) List the Deptno, Name, Job, Salary and Sal+Comm of the emps who earn the second
highest earnings (sal + comm.).

163) List the Deptno and their average salaries for dept with the average salary less than the
averages for all department

164) List out the Names and Salaries of the emps along with their manager names and salaries
for those emps who earn more salary than their Manager.
165) List out the Name, Job, Salary of the emps in the department with the highest average
salary.

166) List the empno,sal,comm. Of emps.

167) List the details of the emps in the ascending order of the sal.

168) List the dept in the ascending order of the job and the desc order of the emps print
empno, ename.

169) Display the unique dept of the emps.


170) Display the unique dept with jobs.
171) Display the details of the blake.

172) List all the clerks.

173) list all the employees joined on 1st may 81.

174) List the empno,ename,sal,deptno of the dept 10 emps in the ascending order of salary.

175) List the emps whose salaries are less than 3500.

176) List the empno,ename,sal of all the emp joined before 1 apr 81.

177) List the emp whose annual sal is <25000 in the asc order of the salaries.

178) List the empno,ename,annsal,dailysal of all the salesmen in the asc ann sal

179) List the empno,ename,hiredate,current date & exp in the ascending order of the exp.

180) List the emps whose exp is more than 10 years.

181) List the empno,ename,sal,TA30%,DA 40%,HRA 50%,GROSS,LIC,PF,net,deduction,net


allow and net sal in the ascending order of the net salary.

182) List the emps who are working as managers.

183) List the emps who are either clerks or managers.

184) List the emps who have joined on the following dates 1 may 81,17 nov 81,30 dec 81

185) List the emps who have joined in the year 1981.

186) List the emps whose annual sal ranging from 23000 to 40000.

187) List the emps working under the mgrs 7369,7890,7654,7900.

188) List the emps who joined in the second half of 82.

189) List all the 4char emps.

190) List the emp names starting with ‘M’ with 5 chars.
DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

191) List the emps end with ‘H’ all together 5 chars.

192) List names start with ‘M’.

193) List the emps who joined in the year 81.

194) List the emps whose sal is ending with 00.

195) List the emp who joined in the month of JAN.

196) Who joined in the month having char ‘a’.

197) Who joined in the month having second char ‘a’

198) List the emps whose salary is 4 digit number.

199) List the emp who joined in 80’s.

200) List the emp who are clerks who have exp more than 8ys.

201) List the mgrs of dept 10 or 20.

202) List the emps joined in jan with salary ranging from 1500 to 4000.

203) List the unique jobs of dept 20 and 30 in desc order.

204) List the emps along with exp of those working under the mgr whose number is starting
with 7 but should not have a 9 joined before 1983.
205) List the emps who are working as either mgr or analyst with the salary ranging from 2000
to 5000 and with out comm.

206) List the empno,ename,sal,job of the emps with /ann sal <34000 but receiving some
comm. Which should not be>sal and desg should be sales man working for dept 30.

207) List the emps who are working for dept 10 or 20 with desgs as clerk or analyst with a sal
is either 3 or 4 digits with an exp>8ys but does not belong to mons of mar,apr,sep and working
for mgrs &no is not ending with 88 and 56.

208) List the empno,ename,sal,job,deptno&exp of all the emps belongs to dept 10 or 20 with
an exp 6 to 10 y working under the same mgr with out comm. With a job not ending irrespective
of the position with comm.>200 with exp>=7y and sal<2500 but not belongs to the month sep or
nov working under the mgr whose no is not having digits either 9 or 0 in the asc dept& desc dept

209) List the details of the emps working at Chicago.


210) List the empno,ename,deptno,loc of all the emps.

211) List the empno,ename,loc,dname of all the depts.,10 and 20.

212) List the empno, ename, sal, loc of the emps working at Chicago dallas with an exp>6ys.

213) List the emps along with loc of those who belongs to dallas ,newyork with sal ranging
from 2000 to 5000 joined in 81.
214) List the empno,ename,sal,grade of all emps.

215) List the grade 2 and 3 emp of Chicago.

216) List the emps with loc and grade of accounting dept or the locs dallas or Chicago with the
grades 3 to 5 &exp >6y

217) List the grades 3 emps of research and operations depts..joined after 1987 and whose
names should not be either miller or allen.

218) List the emps whose job is same as smith.

219) List the emps who are senior to miller.

220) List the emps whose job is same as either allen or sal>allen.

221) List the emps who are senior to their own manager.

222) List the emps whose sal greater than blakes sal.

223) List the dept 10 emps whose sal>allen sal.

224) List the mgrs who are senior to king and who are junior to smith.

225) List the empno,ename,loc,sal,dname,loc of the all the emps belonging to king dept.
226) List the emps whose salgrade are greater than the grade of miller.

227) List the emps who are belonging dallas or Chicago with the grade same as adamsor exp
more than smith.

228) List the emps whose sal is same as ford or blake.

229) List the emps whose sal is same as any one of the following.

230) Sal of any clerk of emp1 table.


DATABASE MANAGEMENT SYSTEM LABORATORY MANUAL

231) Any emp of emp2 joined before 82.

232) The total remuneration (sal+comm.) of all sales person of Sales dept belonging to emp3
table.

233) Any Grade 4 emps Sal of emp 4 table.

234) Any emp Sal of emp5 table.


235) List the highest paid emp.

236) List the details of most recently hired emp of dept 30.

237) List the highest paid emp of Chicago joined before the most recently hired emp of grade
2.

238) List the highest paid emp working under king.

You might also like