0% found this document useful (0 votes)
27 views

Final DBMSLab Manual

Uploaded by

Prasad Dhumale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Final DBMSLab Manual

Uploaded by

Prasad Dhumale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Course Title Database Management System Lab Course Type HC

Course Code B22EF0405 Credits 1 Class IV Semester

LTP Contact Work Total Number of


Credits Hours Load Assessment in
Classes
Lecture - - - Weightage
Per Semester
Tutorial - - - Theory Practical CIE SEE
Course
Structure Practical 1 2 2
Total 1 2 2 - 28 25% 25%

COURSE OVERVIEW:

This course introduces the core principles and techniques required in the design and Implementation of
database systems. This introductory application-oriented course covers the relational database systems
RDBMS - the predominant system for business scientific and Engineering applications at present. It includes
Entity-Relational model, Normalization, Relationa lmodel, Relational algebra, and data access queries as well
as an introduction to SQL. It also covers essential DBMS concepts such as: Transaction Processing,
Concurrency Control and Recovery. It also provides students with theoretical knowledge and practical
skillsin the use of databases and database management systems in information technology applications.

COURSE OBJECTIVE (S):

Students will have the ability to:


1. Keep on a level with of current developments to continue their own professional Development.
2. To engage themselves in lifelong learning of Database management systems, Theories and
technologies this enables them to purse higher studies.
3. To interact professionally with colleagues or clients located abroad and the ability to overcome
challenges that arises from geographic distance, cultural differences, and multiple languages in
the context of computing.
4. Develop team spirit, effective work habits, and professional attitude in written and oral forms,
towards the development of database applications.

COURSE OUTCOMES (COs)


After the completion of the course, the student will be able to:

CO# Course Outcomes POs PSOs

CO1 Apply the basic concepts of Database Systems and Applications. 1 to 5,9,10,12 1,3

Use the basics of MySQL and construct queries using MySQL in 1 to 5,


CO2 9,10,12 1,3
database creation and interaction.
Design a commercial relational database system (Oracle, MySQL) by 1 to 5,9,10,12
CO3 2,3
writing MySQL using thesystem.
Analyze and Select storage and recovery techniques of database 1 to 5,9,10,12
CO4 1,2
system.
CO5 Construct the physical and logical database designs, database 1 to 5, 1,2
modeling, relational, hierarchical, and network models. 9,10,12
CO6 Relate conceptual model to relational model and formulate relational 1 to 5, 2,3
algebra queries. 9,10,12

BLOOM’S LEVEL OF THE COURSE OUTCOMES


Bloom’s Level
Remember Understand Apply Analyze Evaluate Create
CO#
(L1) (L2) (L3) (L4) (L5) (L6)
CO1 √
CO2 √
CO3 √

CO4 √
CO5 √
CO6 √

COURSE ARTICULATION MATRIX

PO10

PO11

PO12

PSO1

PSO2

PSO3
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9
CO#/
Pos
2 3 3 3
CO1 3 3 2 2 2 2
2 3 3 3
CO2 3 3 2 3 1 2

2 3 3 3 3
CO3 3 3 2 3 3 2
2 3 3 3
CO4 3 3 2 3 1 2
3 3 3 3
CO5 3 2 3 3 3 3
3 3 3 3
CO6 3 3 2 3 3 3
Note: 1-Low, 2-Medium, 3-High
PART-A: MySQL Programming
1. Design, develop, and implement the specified queries for the following problems using Oracle,
MySQL,SQL Server, or any other DBMS under LINUX/Windows environment.
2. Create Schema and insert at least 5 records for each table.
3. Add appropriate database constraints.

PART-B: Mini Project

1. Use Java, C#, PHP, Python, or any other similar front-end tool.
2. All applications must be demonstrated on desktop/laptop as a stand-alone or web based application
(Mobile apps on Android/IOS are not permitted.)

SL.NO. Title of the Experiment


PART-A
1 Implementation of DDL, DML, DCL and TCL commands of SQL with suitable examples.

2 Study & Implementation of different types of constraints with suitable examples.


3 Implementation of different types of function, operators, Joins with suitable examples.
4 Study and Implementation of

• Group By & having clause


• Order by clause
• Indexing
• Views
• Sub queries
5 Identifying entities, attributes, keys and relationshipsbetween entities, cardinalities,
generalization, specialization etc. using Conceptual Designing (Ex:- ER Diagrams).

6 Consider the following schema for a Flight Database and draw an ER Diagram.

FLIGHT(Flight no: integer, Flight from: string, Flight to: string, distance: integer, departs:
time, arrives: time, price: real)
AIRCRAFT (aid: integer, aname:string, cruisingrange:integer)
CERTIFIED (eid:integer, aid:integer)
EMPLOYEES (eid:integer, ename:string, salary: integer)

Write SQL queries to


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

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

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

4. For all aircrafts with cruising range over 1000 kms, find the name of the aircraft and the
average salary of all pilots certified for this aircraft.
5. Find the names of pilots certified for some Boeing aircraft.

6. Find the aid's of all aircraft whose cruising range is greater than the minimum
distancefrom the routes from Bangalore to Delhi.

7 Consider the schema for College Database and draw and ER Diagram.
STUDENT (USN, SName, Address, Phone, Gender)
SEMSEC (SSID, Sem, Sec)
CLASS (USN, SSID)
SUBJECT (Subcode, Title, Sem, Credits)
IAMARKS (USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)

Write SQL queries to


1. List all the student details studying in fourth semester ‘C’ Section.
2. Compute the total number of male and female students in each semester and in each
section.
3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in allsubjects.
4. Calculate the FinalIA (average of best two test marks) and update the
Corresponding table for allstudents.
5. Categorize students based on the followingcriterion:
If FinalIA = 17 to 20 then CAT =‘Outstanding’
If FinalIA = 12 to 16 then CAT = ‘Average’
If FinalIA< 12 then CAT = ‘Weak’
Give these details only for 8th semester A, B, and C section students.
PART-B(Mini Project)
For any problem selected
• Make sure that the application should have five or more tables
• Indicative areas include; health care,
Laboratory Outcomes: The student should be able to:
• Create, Update and query on the database.
• Demonstrate the working of different concepts of DBMS
• Implement, analyze and evaluate the project developed for an application with the
front end compatibility.
DBMS LAB IV SEMESTER
INDEX
PART-A

SL. Contents Page. no


No
Implementation of DDL, DML, DCL and TCL commands of SQL with suitable 5-13
1 examples.

14-15
2 Study & Implementation of different types of constraints with suitable examples.

Implementation of different types of function, operators, Joins with suitable 16-23


3
examples.
24-26
Study and Implementation of:
4 • Group By & having clause, Order by clause
• Indexing Views Sub queries

Identifying entities, attributes, keys and relationships between entities, 27-28


5 cardinalities, generalization, specialization etc. using Conceptual Designing (Ex:-
ER Diagrams).
29-37

Consider the following schema for a Flight Database and draw an ER Diagram.
FLIGHT(Flight no: integer, Flight from: string, Flight to: string, distance: integer,
departs: time, arrives: time, price: real)
AIRCRAFT (aid: integer, aname:string, cruisingrange:integer) CERTIFIED
(eid:integer, aid:integer)
EMPLOYEES (eid:integer, ename:string, salary: integer)
Write SQL queries to
1. Find the names of aircraft such that all pilots certified to operate them have
salaries more than Rs 80,000.
6
2. For each pilot who is certified for more than three aircrafts, find the eid and the
maximum cruising range of the aircraft for which he/she is certified.
3. Find the names of all pilots whose salary is less than the price of the cheapest
route from Bangalore to Frankfurt.
4. For all aircrafts with cruising range over 1000 kms, find the name of the aircraft
and the average salary of all pilots certified for this aircraft
5. Find the names of pilots certified for some Boeing aircraft.
6. Find the aid's of all aircraft whose cruising range is greater than the minimum
distancefrom the routes from Bangalore to Delhi

1|P a g e
DBMS LAB IV SEMESTER
37-50

Consider the schema for College Database and draw and ER Diagram.
STUDENT (USN, SName, Address, Phone, Gender) SEMSEC (SSID, Sem, Sec)
CLASS (USN, SSID) SUBJECT (Subcode, Title, Sem, Credits) IAMARKS
(USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)

Write SQL queries to


1. List all the student details studying in fourth semester ‘C’ Section. 2. Compute
the total number of male and female students in each semester and in each section.
7 3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in allsubjects.
4. Calculate the FinalIA (average of best two test marks) and update the
Corresponding table for allstudents.

5. Categorize students based on the followingcriterion: If FinalIA = 17 to 20 then


CAT =‘Outstanding’ If FinalIA = 12 to 16 then CAT = ‘Average’ If FinalIA< 12
then CAT = ‘Weak’

Give these details only for 8th semester A, B, and C section students.

PART-B(Mini Project)
51
For any problem selected
 Make sure that the application should have five or more tables
 Indicative areas include; health care, Laboratory Outcomes:
 The student should be able to: Create, Update and query on the
database
 Demonstrate the working of different concepts of DBMS
 Implement, analyze and evaluate the project developed for an
application with the front end compatibility.

2|P a g e
DBMS LAB IV SEMESTER

1.Lab Requirements

Following are the required hardware and software for this lab, which is available in the
laboratory.

 Hardware: Desktop system having i5 Processor, 4 GB RAM and 500 GB Hard Disk
with Windows 10 Operating System.

 Software:

MySQL

Installation of MySQL

1. Open the MySQL website on a browser


2. Select the Downloads option.
3. Select MySQL Installer for Windows.
4. Choose the desired installer and click on download.
5. After the download, open the installer.
6. It will ask for permission; when it does, click Yes.
7. Click on Next.

Note: At the end of instructions, users have the option to fix their passwords and it is
mandatory.

Login to MySQL with your passwords.

CREATING DATABASE
 CREATE DATABASE <DATABASE NAME>;
 USE <DATABASE NAME>;

3|P a g e
DBMS LAB IV SEMESTER

2. Guidelines to Students

 Equipment in the lab for the use of student community. Students need to maintain
a proper decorum in the computer lab. Students must use the equipment with
care. Any damage is caused is punishable.

 Students are required to carry their observation / programs book with completed
exercises while entering the lab.

 Students are supposed to occupy the machines allotted to them and are not
supposed to talk or make noise in the lab. The allocation is put up on the lab
notice board.

 Lab can be used in free time / lunch hours by the students who need to use the
systems should take prior permission from the lab in-charge.

 Lab records need to be submitted on or before date of submission.

 Students are not supposed to use flash drives.

4|P a g e
DBMS LAB IV SEMESTER

INTRODUCTION TO SQL

SQL commands are like instructions to a table. It is used to interact with the database with
some operations. It is also used to perform specific tasks, functions, and queries of data. SQL
can perform various tasks like creating a table, adding data to tables, dropping the table,
modifying the table, set permission for users.

Experiment-1

Implementation of DDL, DML, DCL and TCL commands of SQL with


suitable examples.

These SQL commands are mainly categorized into five categories:-


1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language

DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can be used to
define the database schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in the database.

DDL is a set of SQL commands used to create, modify, and delete database structures but
not data. These commands are normally not used by a general user, who should be accessing
the database via an application.

List of DDL commands:


CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.

DATA DEFINITION, CONSTRAINTS, AND SCHEMA CHANGES


Used to CREATE, ALTER, and DROP the descriptions of the database tables (relations)

5|P a g e
DBMS LAB IV SEMESTER
Data Definition in SQL
CREATE, ALTER and DROP
table…………………………………….……relation
row……………………………………..…….tuple
column………………………………….……attribute
DATA TYPES
 Numeric: NUMBER, NUMBER(s,p), INTEGER, INT, FLOAT, DECIMAL

 Character: CHAR(n), VARCHAR(n), VARCHAR2(n), CHAR VARYING(n)

 Bit String: BLOB, CLOB

 Boolean: true, false, and null
 
Date and Time: DATE (YYYY-MM-DD) TIME (HH:MM:SS)

 Timestamp: DATE + TIME

 USER Defined types

Consider the COMPANY DATABASE, We need to create a database schema design based on
the following (simplified) requirements of the COMPANY Database: The company is
organized into DEPARTMENTs. Each department has a name, number and an employee who
manages the department. We keep track of the start date of the department manager. A
department may have several locations.  Each department controls a number of PROJECTs.
Each project has a unique name, unique number and is located at a single location.

The database will store each EMPLOYEE’s social security number, address, salary, sex, and
birthdate. Each employee works for one department but may work on several projects. The DB
will keep track of the number of hours per week that an employee currently works on each
project.  It is required to keep track of the direct supervisor of each employee. Each employee
may have a number of DEPENDENTs. For each dependent, the DB keeps a record of name,
sex, birthdate, and relationship to the employee.

6|P a g e
DBMS LAB IV SEMESTER

COMPANY DATABASE SCHEMA

7|P a g e
DBMS LAB IV SEMESTER

CREATE SCHEMA
Specifies a new database schema by giving it a name

Ex: CREATE SCHEMA COMPANY AUTHORIZATION Jsmith;

CREATE TABLE
 Specifies a new base relation by giving it a name, and specifying each of its attributes
and their data types

Syntax of CREATE Command:

CREATE TABLE <table name> ( <Attribute A1> <Data Type D1> [<
Constarints>], <Attribute A2> <Data Type D2> [< Constarints>],

…….

<Attribute An> <Data Type Dn> [< Constarints>],
[<integrity-constraint1>, <integrity-constraint k> ] );
- A constraint NOT NULL may be specified on an
attribute A constraint NOT NULL may be specified on
an attribute
Ex: CREATE TABLE DEPARTMENT (
DNAME VARCHAR (10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR (9), MGRSTARTDATE CHAR (9) );
 Specifying the unique, primary key attributes, secondary keys, and referential integrity
constraints (foreign keys).

Ex: CREATE TABLE DEPT (
DNAME VARCHAR(10) NOT
NULL,

DNUMBER INTEGER NOT
NULL, MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9),

PRIMARY KEY
(DNUMBER), UNIQUE
(DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP(SSN));

8|P a g e
DBMS LAB IV SEMESTER
 We can specify RESTRICT, CASCADE, SET NULL or SET DEFAULT on referential
integrity constraints (foreign keys)

Ex: CREATE TABLE DEPT (
DNAME VARCHAR(10) NOT
NULL,
DNUMBER INTEGER NOT NULL,

MGRSSN CHAR(9), MGRSTARTDATE CHAR(9),

PRIMARY KEY
(DNUMBER), UNIQUE
(DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP

ON DELETE SET DEFAULT ON UPDATE CASCADE);

DROP TABLE
 Used to remove a relation (base table) and its definition.

 The relation can no longer be used in queries, updates, or any other commands since its
description no longer exists

Example: DROP TABLE DEPENDENT;

ALTER TABLE:
 Used to add an attribute to/from one of the base relations drop constraint -- The new
attribute will have NULLs in all the tuples of the relation right after the command is
executed; hence, the NOT NULL constraint is not allowed for such an attribute.


Example: ALTER TABLE EMPLOYEE ADD JOB VARCHAR (12);

 The database users must still enter a value for the new attribute JOB for each
EMPLOYEE tuple. This can be done using the UPDATE command.

DROP A COLUMN (AN ATTRIBUTE)

 ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE;


All constraints and views that reference the column are dropped automatically, along with
the column. 
 ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS RESTRICT; 
Successful if no views or constraints reference the column.
9|P a g e
DBMS LAB IV SEMESTER
 ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN DROP DEFAULT;

 ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT



―333445555‖;

DML(Data Manipulation Language)

The SQL commands that deal with the manipulation of data present in the database belong to
DML or Data Manipulation Language and this includes most of the SQL statements. It is the
component of the SQL statement that controls access to data and to the database. Basically,
DCL statements are grouped with DML statements.
List of DML commands:-
INSERT: It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE: It is used to delete records from a database table.
There are three SQL commands to modify the database: INSERT, DELETE, and UPDATE.

INSERT

 In its simplest form, it is used to add one or more tuples to a relation



 Attribute values should be listed in the same order as the attributes were specified in
the CREATE TABLE command
Example:
INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC-
52', '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 )
 An alternate form of INSERT specifies explicitly the attribute names that correspond to
the values in the new tuple. Attributes with NULL values can be left out
Example: Insert a tuple for a new EMPLOYEE for whom we only know the FNAME,
LNAME, and SSN attributes.
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)VALUES ('Richard', 'Marini',
'653298653')
Important Note: Only the constraints specified in the DDL commands are automatically
enforced by the DBMS when updates are applied to the database. Another variation of
INSERT allows insertion of multiple tuples resulting from a query into a relation
Example: Suppose we want to create a temporary table that has the name, number of
employees, and total salaries for each department. A table DEPTS_INFO is created first, and is
loaded with the summary information retrieved from the database by the query.

10 | P a g e
DBMS LAB IV SEMESTER

CREATE TABLE DEPTS_INFO


(DEPT_NAME VARCHAR (10),
NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER);

INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) SELECT


DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE
DNUMBER=DNO GROUP BY DNAME ;

Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in either the
DEPARTMENT or the EMPLOYEE relations after issuing the above. We have to create a
view (see later) to keep such a table up to date.

DELETE
 Removes tuples from a relation. Includes a WHERE-clause to select the tuples to be
deleted

 Referential integrity should be enforced

 Tuples are deleted from only one table at a time (unless CASCADE is specified on a
referential integrity constraint)

 A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the
table then becomes an empty table

 The number of tuples deleted depends on the number of tuples in the relation that
satisfy the WHERE-clause
Examples:
1: DELETE FROM EMPLOYEE WHERE LNAME='Brown‘;
2: DELETE FROM EMPLOYEE WHERE SSN='123456789‘;
3: DELETE FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT WHERE DNAME='Research');

4: DELETE FROM EMPLOYEE;

UPDATE
 Used to modify attribute values of one or more selected tuples

 A WHERE-clause selects the tuples to be modified

 An additional SET-clause specifies the attributes to be modified and their new values

 Each command modifies tuples in the same relation

 Referential integrity should be enforced

11 | P a g e
DBMS LAB IV SEMESTER

Example1: Change the location and controlling department number of project number 10 to
'Bellaire' and 5, respectively.
UPDATE PROJECT
SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10;

Example2: Give all employees in the 'Research' department a 10% raise in salary.

UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT

WHERE DNAME='Research');

DCL(Data Control language)


You can GRANT and REVOKE privileges on various database objects in MySQL. You can
then view the privileges assigned to a user using the SHOW GRANTS command

Grant Privileges on Table

You can grant users various privileges to tables. These permissions can be any combination of
SELECT, INSERT, UPDATE, DELETE, INDEX, CREATE, ALTER, DROP, GRANT
OPTION or ALL.

Syntax
The syntax for granting privileges on a table in MySQL is:

GRANT privileges ON object TO user;


REVOKE privileges ON object FROM user;

DQL (Data Query Language)

DQL statements are used for performing queries on the data within schema objects. The
purpose of the DQL Command is to get some schema relation based on the query passed to
it. We can define DQL as follows it is a component of SQL statement that allows getting data
from the database and imposing order upon it. It includes the SELECT statement. This
command allows getting the data out of the database to perform operations with it. When a
SELECT is fired against a table or tables the result is compiled into a further temporary table,
which is displayed or perhaps received by the program i.e. a front-end.
List of DQL:
12 | P a g e
DBMS LAB IV SEMESTER
SELECT: It is used to retrieve data from the database

BASIC QUERIES IN SQL


 SQL has one basic statement for retrieving information from a database; the SLELECT
statement

 Basic form of the SQL SELECT statement is called a mapping of a SELECT-FROM-
WHERE block
;

SELECT <attribute list> FROM <table list> WHERE <condition>

 <attribute list> is a list of attribute names whose values are to be retrieved by the query

 <table list > is a list of the relation names required to process the query

 <condition> is a conditional (Boolean) expression that identifies the tuples to be
retrieved by the query

Example :- SELECT * FROM EMPLOYEE WHERE SSN='123456789 ;

TCL (Transaction Control Language)


Transactions group a set of tasks into a single execution unit. Each transaction begins with a
specific task and ends when all the tasks in the group are successfully completed. If any of
the tasks fail, the transaction fails. Therefore, a transaction has only two results: success or
failure. You can explore more about transactions . Hence, the following TCL commands are
used to control the execution of a transaction:

BEGIN: Opens a Transaction.

COMMIT: Commits a Transaction.

Syntax:
COMMIT;
ROLLBACK: Rollbacks a transaction in case of any error occurs.

Syntax:
ROLLBACK;
SAVEPOINT: Sets a save point within a transaction.

Syntax:
SAVEPOINT SAVEPOINT_NAME;

13 | P a g e
DBMS LAB IV SEMESTER

Experiment-2
Study & Implementation of different types of constraints with suitable
examples

MySQL Constraints

SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the
data action, the action is aborted. Constraints can be column level or table level. Column level
constraints apply to a column, and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly

Consider the example: Company database to illustrate the use of constraints while creating
table.

14 | P a g e
DBMS LAB IV SEMESTER

15 | P a g e
DBMS LAB IV SEMESTER

Experiment -3
Implementation of different types of function, operators, Joins with suitable
examples.

All subsequent examples uses COMPANY database as shown below:

SIMPLE SQL QUERIES

Example of a simple query on one relation


Query 1: Retrieve the birth date and address of the employee whose name is 'John B.
Smith'.
SELECT BDATE, ADDRESS FROM EMPLOYEE

WHERE FNAME='John' AND MINIT='B‘ AND LNAME='Smith‘


Similar to a SELECT-PROJECT pair of relational algebra operations: The SELECT-
clause specifies the projection attributes and the WHERE-clause specifies the selection
condition However, the result of the query may contain duplicate tuples

Example of a simple query on two relations

Query 2: Retrieve the name and address of all employees who work for the 'Research'
department.
SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE
DNAME='Research' AND DNUMBER=DNO

Similar to a SELECT-PROJECT-JOIN sequence of relational algebra operations


(DNAME='Research') is a selection condition (corresponds to a SELECT operation in
relational algebra) (DNUMBER=DNO) is a join condition (corresponds to a JOIN operation in
relational algebra)

Example of a simple query on three relations


Query 3: For every project located in 'Stafford', list the project number, the controlling
department number, and the department manager's last name, address, and birth date.

16 | P a g e
DBMS LAB IV SEMESTER
SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROM PROJECT,
DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford'

In Q2, there are two join conditions The join condition DNUM=DNUMBER relates a project
to its controlling department The join condition MGRSSN=SSN relates the controlling
department to the employee who manages that department

AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVG
1. Find the maximum salary, the minimum salary, and the average salary among all
employees.
SELECT MAX (SALARY), MIN (SALARY), AVG (SALARY)
FROM EMPLOYEE
Note: Some SQL implementations may not allow more than one function in the SELECT-
clause

2. Find the maximum salary, the minimum salary, and the average salary among
employees who work for the 'Research' department.
Q12: SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY)
FROM
EMPLOYEE, DEPARTMENT WHERE DNO=DNUMBER AND DNAME='Research'
3. Retrieve the total number of employees in the company (Q13), and the number of
employees in the 'Research' department (Q14).
Q13: SELECT COUNT (*) FROM EMPLOYEE
Q14: SELECT COUNT (*) FROM EMPLOYEE, DEPARTMENT

WHERE DNO=DNUMBER AND DNAME='Research‘

ALIASES, * AND DISTINCT, EMPTY WHERE-CLAUSE


 In SQL, we can use the same name for two (or more) attributes as long as the attributes
are in different relations

 A query that refers to two or more attributes with the same name must qualify the
attribute name with the relation name by prefixing the relation name to the attribute
name Example: EMPLOYEE.LNAME, DEPARTMENT.DNAME

 Some queries need to refer to the same relation twice. In this case, aliases are given to
the relation name

17 | P a g e
DBMS LAB IV SEMESTER
Example
Query 1: For each employee, retrieve the employee's name, and the name of his or her
immediate supervisor.

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S


WHERE E.SUPERSSN=S.SSN
In Q1, the alternate relation names E and S are called aliases or tuple variables for the
EMPLOYEE relation We can think of E and S as two different copies of EMPLOYEE; E
represents employees in role of supervisees and S represents employees in role of supervisors
Aliasing can also be used in any SQL query for convenience. Can also use the AS
keyword to specify aliases

SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E,


EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN

UNSPECIFIED WHERE-clause
A missing WHERE-clause indicates no condition; hence, all tuples of the relations in the
FROM-clause are selected. This is equivalent to the condition WHERE TRUE Example:

Query 1: Retrieve the SSN values for all


employees.
SELECT SSN FROM EMPLOYEE;
If more than one relation is specified in the FROM-clause and there is no join condition, then
the
CARTESIAN PRODUCT of tuples is selected
Example:
SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT

Note: It is extremely important not to overlook specifying any selection and join conditions in
the WHERE-clause; otherwise, incorrect and very large relations may result

USE OF *
To retrieve all the attribute values of the selected tuples, a * is used, which stands for all the
attributes
Examples:
Retrieve all the attribute values of EMPLOYEES who work in department 5.
SELECT * FROM EMPLOYEE WHERE DNO=5

18 | P a g e
DBMS LAB IV SEMESTER
Retrieve all the attributes of an employee and attributes of DEPARTMENT he works in
for every employee of ‘Research’ department.

SELECT * FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND


DNO=DNUMBER

USE OF DISTINCT
SQL does not treat a relation as a set; duplicate tuples can appear. To eliminate
duplicate tuples in a query result, the keyword DISTINCT is used
Example: the result of Q1c may have duplicate SALARY values whereas Q1d does not have
any duplicate values

Q1c: SELECT SALARY FROM EMPLOYEE Q1d: SELECT DISTINCT


SALARY FROM EMPLOYEE

SET OPERATIONS
SQL has directly incorporated some set operations such as union operation (UNION),
set difference (MINUS) and intersection (INTERSECT) operations. The resulting relations of
these set operations are sets of tuples; duplicate tuples are eliminated from the result. The set
operations apply only to union compatible relations; the two relations must have the same
attributes and the attributes must appear in the same order
Query 1: Make a list of all project numbers for projects that involve an employee whose
last name is 'Smith' as a worker or as a manager of the department that controls the
project.
(SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE
DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION

(SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE


PNUMBER=PNO AND ESSN=SSN AND NAME='Smith')
ARITHMETIC OPERATIONS

The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction,
multiplication, and division, respectively) can be applied to numeric values in an SQL query
result
Show the effect of giving all employees who work on the 'ProductX' project a
10% raise.
Q20: SELECT FNAME, LNAME, 1.1*SALARY
19 | P a g e
DBMS LAB IV SEMESTER
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN
AND PNO=PNUMBER AND PNAME='ProductX‘

NESTING OF QUERIES

A complete SELECT query, called a nested query, can be specified within the
WHERE-clause of another query, called the outer query. Many of the previous queries can be
specified in an alternative form using nesting
Query 1: Retrieve the name and address of all employees who work for the 'Research'
department.

SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE WHERE DNO IN (SELECT


DNUMBER FROM DEPARTMENT WHERE DNAME='Research' )
Note: The nested query selects the number of the 'Research' department. The outer query
selects an EMPLOYEE tuple if its DNO value is in the result of either nested query. The
comparison operator IN compares a value v with a set (or multi-set) of values V, and evaluates
to TRUE if v is one of the elements in V

In general, we can have several levels of nested queries. A reference to an unqualified


attribute refers to the relation declared in the innermost nested query. In this example, the
nested query is not correlated with the outer query

CORRELATED NESTED QUERIES


If a condition in the WHERE-clause of a nested query references an attribute of a
relation declared in the outer query, the two queries are said to be correlated. The result of a
correlated nested query is different for each tuple (or combination of tuples) of the relation(s)
the outer query
Retrieve the name of each employee who has a dependent with the same first name as the
employee.
SELECT E.FNAME, E.LNAME FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT
ESSN FROM DEPENDENT WHERE ESSN=E.SSN AND
E.FNAME=DEPENDENT_NAME)
In , the nested query has a different result in the outer query. A query written with nested
SELECT... FROM… WHERE... blocks and using the = or IN comparison operators can
always be expressed as a single block query.

20 | P a g e
DBMS LAB IV SEMESTER
SELECT E.FNAME, E.LNAME FROM EMPLOYEE E, DEPENDENT D WHERE
E.SSN=D.ESSN AND E.FNAME=D.DEPENDENT_NAME

THE EXISTS FUNCTION


EXISTS is used to check whether the result of a correlated nested query is empty
(contains no tuples) or not. We can formulate Query in an alternative form that uses EXIST.
SELECT FNAME, LNAME FROM EMPLOYEE
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN
AND FNAME=DEPENDENT_NAME)

Query 1: Retrieve the names of employees who have no dependents.


SELECT FNAME, LNAME FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT * FROM DEPENDENT WHERE SSN=ESSN)

Note: In the correlated nested query retrieves all DEPENDENT tuples related to an
EMPLOYEE tuple. If none exist, the EMPLOYEE tuple is selected

EXPLICIT SETS
It is also possible to use an explicit (enumerated) set of values in the WHERE-clause
rather than a nested query
Query 2: Retrieve the social security numbers of all employees who work on project
number 1, 2, or 3.

SELECT DISTINCT ESSN FROM WORKS_ON WHERE PNO IN (1, 2, 3)

NULLS IN SQL QUERIES


SQL allows queries that check if a value is NULL (missing or undefined or not
applicable). SQL uses IS or IS NOT to compare NULLs because it considers each NULL
value distinct from other NULL values, so equality comparison is not appropriate.
Query 3: Retrieve the names of all employees who do not have supervisors.
SELECT FNAME, LNAME FROM EMPLOYEE
WHERE SUPERSSN IS NULL

Note: If a join condition is specified, tuples with NULL values for the join attributes are not
included in the result

SUBSTRING COMPARISON

21 | P a g e
DBMS LAB IV SEMESTER
The LIKE comparison operator is used to compare partial strings. Two reserved
characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of
characters, and '_' replaces a single arbitrary character.

Query 1:Retrieve all employees whose address is in Houston, Texas. Here, the value of the
ADDRESS attribute must contain the substring 'Houston,TX‘ in it.
SELECT FNAME, LNAME
FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%'

Query 2: Retrieve all employees who were born during the 1950s.
Here, '5' must be the 8th character of the string (according to our format for date), so
the BDATE value is '_______5_', with each underscore as a place holder for a single arbitrary
character.
SELECT FNAME, LNAME
FROM EMPLOYEE WHERE BDATE LIKE '_______5_‘
Note: The LIKE operator allows us to get around the fact that each value is considered atomic
and indivisible. Hence, in SQL, character string attribute values are not atomic

JOINS

The concept of a joined table (or joined relation) was incorporated into SQL to permit users to
specify a table resulting from a join operation in the FROM clause of a query. This construct
may be easier to comprehend than mixing together all the select and join conditions in the
WHERE clause. For example, consider query Q1, which retrieves the name and address of
every employee who works for the ‘Research’ department. It may be easier to specify the join
of the EMPLOYEE and DEPARTMENT relations in the WHERE clause, and then to select the
desired tuples and attributes.

SELECT Fname, Lname, Address FROM (EMPLOYEE JOIN DEPARTMENT ON Dno =


Dnumber) WHERE Dname = ‘Research’;

Natural Join

If the names of the join attributes are not the same in the base relations, it is possible to rename
the attributes so that they match, and then to apply NATURAL JOIN. In this case, the AS

22 | P a g e
DBMS LAB IV SEMESTER
construct can be used to rename a relation and all its attributes in the FROM clause. This is
illustrated above where the DEPARTMENT relation is renamed as DEPT and its attributes are
renamed as Dname, Dno (to match the name of the desired join attribute Dno in the
EMPLOYEE table), Mssn, and Msdate. The implied join condition for this NATURAL JOIN
is EMPLOYEE.Dno = DEPT.Dno, because this is the only pair of attributes with the same
name after renaming:

SELECT Fname, Lname, Address FROM (EMPLOYEE NATURAL JOIN (DEPARTMENT


AS DEPT (Dname, Dno, Mssn, Msdate))) WHERE Dname = ‘Research’;

Left outer join

The default type of join in a joined table is called an inner join, where a tuple is included in the
result only if a matching tuple exists in the other relation.

If the user requires that all employees be included, a different type of join called OUTER JOIN
must be used explicitly (see Section 8.4.4 for the definition of OUTER JOIN in relational
algebra). There are several variations of OUTER JOIN, as we shall see.

SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name FROM (EMPLOYEE


AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.Super_ssn = S.Ssn);

23 | P a g e
DBMS LAB IV SEMESTER

Experiment -4
Study and Implementation of: Group By & having clause, Order by clause ,
Indexing, Views , Sub queries

GROUPING
 In many cases, we want to apply the aggregate functions to subgroups of tuples in a
relation

 Each subgroup of tuples consists of the set of tuples that have the same value for the
grouping attribute(s)

 The function is applied to each subgroup independently

 SQL has a GROUP BY-clause for specifying the grouping attributes, which must also
appear in the SELECT-clause
Query 1: For each department, retrieve the department number, the number
of employees in the department, and their average salary.
SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE GROUP BY DNO
 In Q1, the EMPLOYEE tuples are divided into groups. Each group having the same
value for the grouping attribute DNO

 The COUNT and AVG functions are applied to each such group of tuples separately

 The SELECT-clause includes only the grouping attribute and the functions to be
applied on each group of tuples

 A join condition can be used in conjunction with grouping
Query 2: For each project, retrieve the project number, project name, and the number of
employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
24 | P a g e
DBMS LAB IV SEMESTER
THE HAVING-CLAUSE
Sometimes we want to retrieve the values of these functions for only those groups that
satisfy certain conditions. The HAVING-clause is used for specifying a selection condition on
groups (rather than on individual tuples)
Query 3: For each project on which more than two employees work, retrieve the project
number, project name, and the number of employees who work on that project.
SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON WHERE
PNUMBER=PNO GROUP BY PNUMBER,
PNAME HAVING COUNT (*) > 2
ORDER BY

The ORDER BY clause is used to sort the tuples in a query result based on the values
of some attribute(s)
Query 21: Retrieve a list of employees and the projects each works in, ordered by the
employee's department, and within each department ordered alphabetically by employee
last name.
Q21: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO
AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME
The default order is in ascending order of values. We can specify the keyword DESC if
we want a descending order; the keyword ASC can be used to explicitly specify ascending
order, even though it is the default
Ex: ORDER BY DNAME DESC, LNAME ASC, FNAME ASC

SUB QUERIES:

Query1: Retrieve the names of all employees who have two or more dependents.
SELECT LNAME, FNAME FROM
EMPLOYEE
WHERE (SELECT COUNT (*) FROM DEPENDENT
WHERE SSN=ESSN) ≥ 2);
Query 2: List the names of managers who have least one dependent.

25 | P a g e
DBMS LAB IV SEMESTER
SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN)

AND EXISTS ( SELECT * FROM DEPARTMENT WHERE SSN=MGRSSN );

VIEWS

A view in SQL terminology is a single table that is derived from other tables.6 These other
tables can be base tables or previously defined views. A view does not necessarily exist in
physical form; it is considered to be a virtual table, in contrast to base tables, whose tuples are
always physically stored in the database. This limits the possible update operations that can be
applied to views, but it does not provide any limitations on querying a view

In SQL, the command to specify a view is CREATE VIEW. The view is given a (virtual) table
name (or view name), a list of attribute names, and a query to specify the contents of the view.

CREATE VIEW WORKS_ON1 AS SELECT Fname, Lname, Pname, Hours FROM


EMPLOYEE, PROJECT, WORKS_ON WHERE Ssn = Essn AND Pno = Pnumber;

CREATE VIEW DEPT_INFO(Dept_name, No_of_emps, Total_sal) AS SELECT Dname,


COUNT (*), SUM (Salary) FROM DEPARTMENT, EMPLOYEE WHERE Dnumber = Dno
GROUP BY Dname;

INDEXING
An index is a schema object. It is used by the server to speed up the retrieval of rows by using
a pointer. It can reduce disk I/O(input/output) by using a rapid path access method to locate
data quickly.
An index helps to speed up select queries and where clauses, but it slows down data input,
with the update and the insert statements. Indexes can be created or dropped with no effect on
the data. In this article, we will see how to create, delete, and use the INDEX in the
database.

Creating an Index

Syntax:-

CREATE INDEX index


ON TABLE column;

Removing an Index
Remove an index from the data dictionary by using the DROP INDEX command.

26 | P a g e
DBMS LAB IV SEMESTER
Syntax

DROP INDEX index;

To drop an index, you must be the owner of the index or have the DROP ANY
INDEX privilege.

Experiment-5
Identifying entities, attributes, keys and relationships between entities,
cardinalities, generalization, specialization etc. using Conceptual Designing
(Ex:- ER Diagrams).

Consider Company schema ER diagram


ER model has three main concepts:
Entities (and their entity types and entity sets)
Attributes (simple, composite, multivalued)
Relationships (and their relationship types and relationship sets)

Entities and Attributes:


27 | P a g e
DBMS LAB IV SEMESTER
Entity is a basic concept for the ER model.
Entities are specific things or objects in the mini-world that are represented in the database.
For example the EMPLOYEE John Smith, the Research DEPARTMENT, the ProductX
PROJECT

Attributes are properties used to describe an entity.


For example an EMPLOYEE entity may have the attributes Name, SSN, Address, Sex,
BirthDate A specific entity will have a value for each of its attributes.

For example a specific employee entity may have Name='John Smith', SSN='123456789',
Address ='731, Fondren, Houston, TX', Sex='M', BirthDate='09-JAN-55‘ .Each attribute has a
value set (or data type) associated with it – e.g. integer, string, date, enumerated type, …

A relationship relates two or more distinct entities with a specific meaning.  For example,
EMPLOYEE John Smith works on the ProductX PROJECT, or EMPLOYEE Franklin Wong
manages the Research DEPARTMENT.

Relationships of the same type are grouped or typed into a relationship type.

For example, the WORKS_ON relationship type in which EMPLOYEEs and PROJECTs
participate, or the MANAGES relationship type in which EMPLOYEEs and DEPARTMENTs
participate.

The degree of a relationship type is the number of participating entity types.  Both
MANAGES and WORKS_ON are binary relationships.

Listed below with their participating entity types:


WORKS_FOR (between EMPLOYEE, DEPARTMENT)
MANAGES (also between EMPLOYEE, DEPARTMENT)
CONTROLS (between DEPARTMENT, PROJECT)
WORKS_ON (between EMPLOYEE, PROJECT)
SUPERVISION (between EMPLOYEE (as subordinate), EMPLOYEE (as supervisor))
DEPENDENTS_OF (between EMPLOYEE, DEPENDENT)

Cardinality Ratio (specifies maximum participation)  One-to-one (1:1)  One-to-many (1:N)


or Many-to-one (N:1)
Many-to-many (M:N)  Existence Dependency Constraint (specifies minimum participation)
(also called participation constraint)
zero (optional participation, not existence-dependent)
one or more (mandatory participation, existence-dependent)

Cardinality ratio (of a binary relationship): 1:1, 1:N, N:1, or M:N


28 | P a g e
DBMS LAB IV SEMESTER
Shown by placing appropriate numbers on the relationship edges.
Participation constraint (on each participating entity type): total (called existence dependency)
or partial.

Experiment 6

Consider the following schema for a Flight Database and draw an ER


Diagram.
FLIGHT(Flight no: integer, Flight from: string, Flight to: string, distance:
integer, departs: time, arrives: time, price: real)
AIRCRAFT (aid: integer, aname:string, cruisingrange:integer)
CERTIFIED (eid:integer, aid:integer)
EMPLOYEES (eid:integer, ename:string, salary: integer)

Write SQL queries to


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

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

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

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

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

6. Find the aid's of all aircraft whose cruising range is greater than the
minimum distance from the routes from Bangalore to Delhi

TABLE CREATION

mysql> CREATE TABLE flight (no INT (11), from VARCHAR(20), too VARCHAR(20),
distance INT(11), departs VARCHAR (20), arrives VARCHAR(20), price double,
PRIMARY KEY (no) );

29 | P a g e
DBMS LAB IV SEMESTER

mysql> CREATE TABLE aircraft(aid INT, aname VARCHAR(20),> cruisingrange INT,


PRIMARY KEY (aid) );

mysql> CREATE TABLE employees( eid INT(20), ename VARCHAR(20), salary INT (20),
PRIMARY KEY (eid) );

30 | P a g e
DBMS LAB IV SEMESTER

mysql> CREATE TABLE certified(eid INT(20), aid INT(10), PRIMARY KEY (eid,aid),
FOREIGN KEY (eid) REFERENCES employees (eid),FOREIGN KEY (aid) REFERENCES
aircraft (aid) );

INSERT INTO FLIGHT VALUES


(1,’BANGALORE’,’MANGALORE’,360,’10:45:00’,’12:00:00’,10000);
INSERT INTO FLIGHT VALUES
(2,’BANGALORE’,’DELHI’,5000,’12:15:00’,’04:30:00’,25000);
31 | P a g e
DBMS LAB IV SEMESTER
INSERT INTO FLIGHT VALUES
(3,’BANGALORE’,’MUMBAI’,3500,’02:15:00’,’05:25:00’,30000);
INSERT INTO FLIGHT VALUES
(4,’DELHI’,’MUMBAI’,4500,’10:15:00’,’12:05:00’,35000);
INSERT INTO FLIGHT VALUES
(5,’DELHI’,’FRANKFURT’,18000,’07:15:00’,’05:30:00’,90000);
INSERT INTO FLIGHT VALUES
(6,’BANGALORE’,’FRANFURT’,19500,’10:00:00’,’07:45:00’,95000);
INSERT INTO FLIGHT VALUES
(7,’BANGALORE’,’FRANKURT’,17000,’12:00:00’,’06:30:00’,99000);

INSERT INTO AIRCRAFT VALUES (123,’AIRBUS’,1000);


INSERT INTO AIRCRAFT VALUES (302,’BOEING’,5000);
INSERT INTO AIRCRAFT VALUES (306,’JET01’,5000);
INSERT INTO AIRCRAFT VALUES (378,’AIRBUS380’,8000);
INSERT INTO AIRCRAFT VALUES (456,’AIRCRAFT’,500);
INSERT INTO AIRCRAFT VALUES (789,’AIRCRAFT02’,800);
INSERT INTO AIRCRAFT VALUES (951,’AIRCRAFT03’,1000);

32 | P a g e
DBMS LAB IV SEMESTER
INSERT INTO employees VALUES (1,'Ajay',30000);
INSERT INTO employees VALUES (2,'Ajith',85000);
INSERT INTO employees VALUES (3,'Arnab',50000);
INSERT INTO employees VALUES(4,'Harry',45000);
INSERT INTO employees VALUES(5,'Ron',90000);
INSERT INTO employees VALUES (6,'Josh',75000);
INSERT INTO employees VALUES (7,'Ram',100000);

INSERT INTO certified VALUES (1,123);


INSERT INTO certified VALUES (2,123);
INSERT INTO certified VALUES (1,302);
INSERT INTO certified VALUES (5,302);
INSERT INTO certified VALUES (7,302);
INSERT INTO certified VALUES (1,306);
INSERT INTO certified VALUES (2,306);
INSERT INTO certified VALUES (1,378);
INSERT INTO certified VALUES (2,378);
INSERT INTO certified VALUES (4,378);
INSERT INTO certified VALUES (6,456);
INSERT INTO certified VALUES (3,456);
INSERT INTO certified VALUES (5,789);
INSERT INTO certified VALUES (6,789);
INSERT INTO certified VALUES (3,951);
INSERT INTO certified VALUES (1,951);
INSERT INTO certified VALUES (1,789);

33 | P a g e
DBMS LAB IV SEMESTER

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

SELECT DISTINCT a.aname FROM aircraft a,certified c,employees e WHERE a.aid=c.aid


AND c.eid=e.eid AND NOT EXISTS (SELECT * FROM employees e1 WHERE
e1.eid=e.eid AND e1.salary>80000);

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

34 | P a g e
DBMS LAB IV SEMESTER
SELECT c.eid, MAX(cruisingrange) from certified c, aircraft a where c.aid = a.aid group by
c.eid having count(*)>3;

3.Find the names of all 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
flight f where f.frm = ‘Bangalore’ AND f.too = ‘Frankfurt’);

4.For all aircrafts with cruisingrange over 1000 kms,find the name of the aircraft
and the average salary of all pilots certified for this aircraft.

35 | P a g e
DBMS LAB IV SEMESTER
Select a.aid, a.aname, AVG(e.salary) 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;

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

SELECT distinct e. ename from employees e, aircraft a, certified c where e.eid = c.eid AND
c.aid = a.aid AND a. aname = “Boeing”;

6.Find the aid's of all aircraft whose crusing range is grater than the minimum
distance from Bangalore to Delhi.

36 | P a g e
DBMS LAB IV SEMESTER
Select aid from aircraft where cruisingrange > (Select min(distance) from flight where frm=
“Bangalore” and too= “Delhi”);

37 | P a g e
DBMS LAB IV SEMESTER

Experiment 7

Consider the schema for College Database and draw and ER Diagram.
STUDENT (USN, SName, Address, Phone, Gender) SEMSEC (SSID, Sem,
Sec)
CLASS (USN, SSID) SUBJECT (Subcode, Title, Sem, Credits) IAMARKS
(USN, Subcode, SSID, Test1, Test2, Test3, FinalIA)

Write SQL queries to


1. List all the student details studying in fourth semester ‘C’ Section. 2.
Compute the total number of male and female students in each semester and
in each section.
3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in allsubjects.
4. Calculate the FinalIA (average of best two test marks) and update the
Corresponding table for allstudents.

5. Categorize students based on the followingcriterion: If FinalIA = 17 to 20


then CAT =‘Outstanding’ If FinalIA = 12 to 16 then CAT = ‘Average’ If
FinalIA< 12 then CAT = ‘Weak’

Give these details only for 8th semester A, B, and C section students.

CREATION OF COLLEGE DATABASE:


1.CREATE DATABASE COLLEGE;

2,SHOW DATABASES;

38 | P a g e
DBMS LAB IV SEMESTER

3. USE COLLEGE;

CREATION OF TABLES IN COLLEGE DATABASE:


1. Create Table for STUDENT
CREATE TABLE STUDENT(USN CHAR(10),SNAME VARCHAR(20),ADDRESS
VARCHAR(25), PHONE INT(10),GENDER CHAR,CONSTRAINT A PRIMARY
KEY(USN));

Table created

2. Create Table for SEMSEC


CREATE TABLE SEMSEC(SSID CHAR(2),SEM INT(1),SEC CHAR,CONSTRAINT B PRIMARY
KEY(SSID),CONSTRAINT C CHECK(SEM BETWEEN 1 AND 8));
Table created

39 | P a g e
DBMS LAB IV SEMESTER
3. Create Table for CLASS
CREATE TABLE CLASS(USN CHAR(10),SSID CHAR(2),CONSTRAINT D PRIMARY
KEY(USN,SSID),CONSTRAINT E FOREIGN KEY(USN) REFERENCES STUDENT(USN)
ON DELETE CASCADE,CONSTRAINT F FOREIGN KEY(SSID) REFERENCES
SEMSEC(SSID) ON DELETE CASCADE);
Table created

4. Create Table for SUBJECT


CREATE TABLE SUBJECT(SUBCODE VARCHAR(7),TITLE VARCHAR(20),SEM
INT(1),
CREDITS INT(1),CONSTRAINT G PRIMARY KEY(SUBCODE));
Table created

5. Create Table for IAMARKS


CREATE TABLE IAMARKS(USN CHAR(10),SUBCODE VARCHAR(7),SSID CHAR(2),
TEST1 INT(2),TEST2 INT(2),TEST3 INT(2),FINALIA INT(2), CONSTRAINT H
PRIMARY KEY(USN,SUBCODE,SSID), CONSTRAINT I FOREIGN KEY(USN)
REFERENCES STUDENT(USN) ON DELETE CASCADE,CONSTRAINT J FOREIGN
KEY(SSID) REFERENCES SEMSEC(SSID) ON DELETE CASCADE,CONSTRAINT K
FOREIGN KEY(SUBCODE) REFERENCES SUBJECT(SUBCODE) ON DELETE
CASCADE);
Table created

Insertion Commands for COLLEGE Database:

40 | P a g e
DBMS LAB IV SEMESTER

1.Insert Values into Table-1

Insert Values into STUDENT


Insert Command

INSERT INTO STUDENT (USN,SNAME,ADDRESS,PHONE,GENDER) VALUES


('1MV17CS001','AASHISH','BANGALORE',1020304050,'M'),
('1MV17CS060','NAELA','MYSORE',1122334455,'F'),
('1MV17CS130','MILIND','JAMMU',506070809,'M'),
('1MV16CS001','ABHIJITH','PUNE',998877655,'M'),
('1MV16CS060','NIKITHA','HYDERABAD',900706050,'F'),
('1MV16CS130','SANJANA','GUWAHATTI',124567890,'F'),
('1MV15CS001','ANSHUMAN','PANAJI',111223334,'M'),
('1MV15CS060','AMRUTHA','BANGALORE',102003004,'F'),
('1MV15CS130','BHUVANESH','JAIPUR',900007006,'M'),
('1MV14CS001','DEVAYANI','BANGALORE',1020030,'F'),
('1MV14CS060','DAVID','KOCHI',90080070,'M'),
('1MV14CS130','AISHWARYA','MUMBAI',100020000,'F');

Command to select all 12 rows of STUDENT


SELECT * FROM STUDENT;

2. Insert Values into Table-2

Insert Values into SEMSEC


Insert Command
INSERT INTO SEMSEC (SSID,SEM,&SEC) values
('2A',2,'A'),('2B',2,'B'),('2C',2,'C'),('4A',4,'A'),('4B',4,'B'),('4C',4,'C'),
('6A',6,'A'),('6B',6,'B'),('6C',6,'C'),('8A',8,'A'),('8B',8,'B'),('8C',8,'C');

row-12 created

Command to select all 12 rows of SEMSEC


SELECT * FROM SEMSEC;
41 | P a g e
DBMS LAB IV SEMESTER

3. Insert Values into Table-3

INSERT INTO CLASS(USN,SSID) VALUES


('1MV17CS001','2A'),('1MV17CS060','2B'),('1MV17CS130','2C'),('1MV16CS001','4A'),('1MV
16CS060','4B'),('1MV16CS130','4C'),('1MV15CS001','6A'),('1MV15CS060','6B'),('1MV15CS1
30','6C'),('1MV14CS001','8A'),('1MV14CS060','8B'),('1MV14CS130','8C');
row-12 created

Command to select all 12 rows of CLASS

SELECT * FROM CLASS;

4. Insert Values into Table-4

Insert Values into SUBJECT


Insert Command

42 | P a g e
DBMS LAB IV SEMESTER
mysql> INSERT INTO SUBJECT(SUBCODE,TITLE,SEM,CREDITS) VALUES
('15CS21','M2',2,4),('15PCD23','PCD',2,4),('15CS42','SE',4,4),('15CS44','MP',4,4),('15CS64','C
G',6,4),('15CS62','USP',6,4),('10CS81','SA',8,4),('10CS842','ST',8,3);
row-8 created

Command to select all 8 rows of SUBJECT

SELECT * FROM SUBJECT;

5. Insert Values into Table-5

Insert Values into IAMARKS


Insert Command

INSERT INTO IAMARKS(USN,SUBCODE,SSID,TEST1,TEST2,TEST3)VALUES


('1MV17CS001','15CS21','2A',15,14,13),
('1MV17CS060','15PCD23','2B',15,15,14),
('1MV17CS130','15CS21','2C',11,12,13),
('1MV16CS001','15CS42','4A',19,19,18),
('1MV16CS060','15CS44','4B',5,8,5),
('1MV16CS130','15CS42','4C',20,20,20),
('1MV15CS001','15CS64','6A',12,12,12),
('1MV15CS060','15CS62','6B',18,19,20),
('1MV15CS130','15CS64','6C',8,12,11),
('1MV14CS001','10CS81','8A',3,11,12),
('1MV14CS060','10CS842','8B',0,0,7),
('1MV14CS130','10CS81','8C',0,0,20);
row-12 created

Command to select all 12 rows of IAMARKS

SELECT * FROM IAMARKS;

43 | P a g e
DBMS LAB IV SEMESTER

Queries for COLLEGE:

Querie-1

1] Make a list of all students details studying in 4th sem c-sec

Syntax:
SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER
FROM STUDENT S,CLASS C,SEMSEC SS WHERE S.USN=C.USN AND
SS.SSID=C.SSID AND SS.SEM=4 AND SS.SEC='C';

Output:

Querie-2
44 | P a g e
DBMS LAB IV SEMESTER

2] Compute the total no.of male and female students in each semester and in each sec

Syntax:
SELECT SS.SEM,SS.SEC,S.GENDER,COUNT(S.GENDER) FROM STUDENT
S,SEMSEC SS,CLASS C WHERE S.USN=C.USN AND SS.SSID=C.SSID GROUP BY
SS.SEM,SS.SEC,S.GENDER;

Output:

Querie-3

3]Create view of test1 marks of student 1MV15CS060 in all subjects

Syntax:
CREATE VIEW TEST1_MARKS AS SELECT USN,SUBCODE,TEST1 FROM IAMARKS
WHERE USN='1MV15CS060';

View created

Output:

45 | P a g e
DBMS LAB IV SEMESTER

Update Commands:

Syntax:
UPDATE IAMARKS SET TEST1=19,TEST2=18,TEST3=17 WHERE USN='1MV14CS001';

1 row updated

Syntax:
UPDATE IAMARKS SET TEST1=11,TEST2=0,TEST3=14 WHERE USN='1MV14CS060';

1 row updated

Syntax:
UPDATE IAMARKS SET TEST1=10,TEST2=0,TEST3=7 WHERE USN='1MV14CS130';

1 row updated

SELECT * FROM IAMARKS;

Output:

46 | P a g e
DBMS LAB IV SEMESTER

Querie-4

4] Calculate the final IA marks and update the corresponding table for all students

Syntax:
UPDATE IAMARKS SET Finalia=(GREATEST (Test1+Test2,Test2+Test3,
Test3+Test1)/2);

Output:

Querie-5

5] a)Categorise students based on the following criteria


47 | P a g e
DBMS LAB IV SEMESTER

If FINALIA=17 to 20 then CAT=’OUTSTANDING’

If FINALIA=12 to 16 then CAT=’AVERAGE’

If FINALIA=00 to 11 then CAT=’WEAK’

Give these details only for 8th semester A, B and C section students

b)UPDATE IAMARKS SET FINALIA=NULL;

a) SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER,
( CASE
WHEN IA.FINALIA BETWEEN 17 AND 20
THEN 'OUTSTANDING'
WHEN IA.FINALIA BETWEEN 12 AND 16
THEN 'AVERAGE'
ELSE 'WEAK'
END
) AS CAT
FROM STUDENT S,SEMSEC SS,IAMARKS IA
WHERE S.USN=IA.USN AND
SS.SSID=IA.SSID AND
SS.SEM=8;

Output:

5]b) UPDATE IAMARKS SET FINALIA=NULL;

48 | P a g e
DBMS LAB IV SEMESTER

Output:

49 | P a g e
DBMS LAB IV SEMESTER

Part B –Mini project

 For any problem selected


 Make sure that the application should have five or more tables
 Indicative areas include; health care, Laboratory Outcomes:
 The student should be able to: Create, Update and query on the
database
 Demonstrate the working of different concepts of DBMS
 Implement, analyze and evaluate the project developed for an
application with the front end compatibility.

For Example:

Sl. Part B Mini Project


No.
Develop a mini project for Hospital database Management system .

Design an ER diagram & schema diagram for Hospital database Management


system . Create at least five tables insert the data and illustrate different concepts of
DBMS.
In this project there are five entity classes:
 Doctor
 Nurse
 Patient
 Receptionist
 Room
Use Java, C#, PHP, Python, or any other similar front-end tool.

All applications must be demonstrated on desktop/laptop as a stand-alone or web


based application.

50 | P a g e

You might also like