DBMS 5th Sem - LabManual
DBMS 5th Sem - LabManual
LABORATORY MANUAL
DATABASE MANAGEMENT SYSTEM LABORATORY
(18CSL58)
V SEMESTER
Prepared By:
APPROVED BY
Experiment distribution
o For laboratories having only one part: Students are allowed to pick one experiment from the
lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one experiment
from PART A and one experiment from PART B, with equal opportunity.
Change of experiment is allowed only once and marks allotted for procedure to be made zero
of the changed part only.
Marks Distribution (Courseed to change in accoradance with university regulations)
k) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 =
100 Marks
l) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
1.
DBMS Lab Manual 2022
INTRODUCTION TO SQL
SQL (Structured Query Language) is a nonprocedural language, you specify what you
want, not how to get it. A block structured format of English key words is used in this Query
language. It has the following components.
DDL (Data Definition Language)- The SQL DDL provides command for defining
relation schemas, deleting relations and modifying relation schema.
View definition-The SQL DDL includes commands for defining views. Transaction
Control- SQL includes for specifying the beginning and ending of transactions.
Embedded SQL and Dynamic SQL- Embedded and Dynamic SQL define how SQL
statements can be embedded with in general purpose programming languages, such as C, C++,
JAVA, COBOL, Pascal and Fortran.
Integrity-The SQL DDL includes commands for specifying integrity constraints that
the data stored in the database must specify. Updates that violate integrity constraints are
allowed.
• Char (n)- A fixed length character length string with user specified length .
• Varchar (n)- A variable character length string with user specified maximum length n.
• Int- An integer.
• Small integer- A small integer.
• Numeric (p, d)-A Fixed point number with user defined precision.
• Real, double precision- Floating point and double precision floating point numbers with
machine dependent precision.
• Float (n)- A floating point number, with precision of at least n digits.
• Date- A calendar date containing a (four digit) year, month and day of the month.
• Time- The time of day, in hours, minutes and seconds Eg. Time’09:30:00’.
• Number- Number is used to store numbers (fixed or floating point).
DDL statement for creating a table
Syntax-
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
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:
Dept of ISE EWIT Page 5
DBMS Lab Manual 2022
Note: It is extremely important not to overlook specifying any selection and join conditions
in the WHERE-clause; otherwise, incorrect and very large relations mayresult
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.
Q1a: SELECT * FROM EMPLOYEE WHERE DNO=5
Retrieve all the attributes of an employee and attributes of DEPARTMENT he works in for
every employee of ‘Research’ department.
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
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 5: 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.
Q5: (SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith')
UNION
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 6: Retrieve the name and address of all employees who work for the 'Research'
department.
Q6: 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
Query 7: Retrieve the name of each employee who has a dependent with the same first
name as the employee.
Q7: 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 Q7, 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. For example, Q7 may be written as in Q7a
Note: In Q8, 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 9: Retrieve the social security numbers of all employees who work on project
number 1, 2, or 3.
Note: If a join condition is specified, tuples with NULL values for the join attributes are not included
in the result
AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVG
Query 11: Find the maximum salary, the minimum salary, and the average salary among all
employees.
Q11: SELECT MAX (SALARY), MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE
Note: Some SQL implementations may not allow more than one function in the SELECT -clause
Query 12: 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'
Queries 13 and 14: 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
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)
BY PNUMBER, PNAME
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 thanon
individual tuples)
Query 17: 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.
Q17: SELECT PNUMBER, PNAME, COUNT (*) FROM
PROJECT, WORKS_ON
WHERE PNUMBER=PNO GROUP
BY PNUMBER, PNAME
SUBSTRING COMPARISON
The LIKE comparison operator is used to compare partial strings. Two reserved charactersare
used: '%' (or '*' in some implementations) replaces an arbitrary number of characters, and '_' replaces a
single arbitrary character.
Query 18: Retrieve all employees whose address is in Houston, Texas. Here, the value of the
ADDRESS attribute must contain the substring 'Houston,TX‘ in it.
Q18: SELECT FNAME, LNAME
FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%'
Query 19: 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 arbitrarycharacter.
Q19: 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
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
Query 20: Show the effect of giving all employees who work on the 'ProductX' project a 10%
raise.
Q20: SELECT FNAME, LNAME, 1.1*SALARY FROM
EMPLOYEE, WORKS_ON, PROJECT WHERESSN=ESSN
AND PNO=PNUMBER AND PNAME='ProductX’
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.
Query 22: Retrieve the names of all employees who have two or more dependents.
Q22: SELECT LNAME, FNAME FROM
EMPLOYEE
WHERE (SELECT COUNT (*) FROM
DEPENDENT WHERE SSN=ESSN) ≥ 2);
Query 23: List the names of managers who have least one dependent.
Q23: SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN)
There are three SQL commands to modify the database: INSERT, DELETE, and
UPDATE. INSERT
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.
CREATE TABLE DEPTS_INFO
(DEPT_NAME VARCHAR (10),
NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER);
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');
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 newvalues
• Each command modifies tuples in the same relation
• Referential integrity should be enforced
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');
SQL TRIGGERS
• Objective: to monitor a database andtake initiate action when a condition occurs
• Triggers are nothing but the procedures/functions that involve actions and
fired/executed automatically whenever an event occurs such as an insert, delete, or
update operation or pressing a button or when mouse button is clicked
VIEWS IN SQL
• A view is a single virtual table that is derived from other tables. The other tables
•
•
•
•
LAB EXPERIMENTS
PART A: SQL PROGRAMMING
PROGRAM 1
1. Consider the following schema for a Library Database:
Solution:
Entity-Relationship Diagram
Author_Name
Book_id Title
Pub_Year M N
Has
Published-by
N No_of_copies Branch_id
Publisher_Name
M M N
1 Book_Copies In Library_Branch Branch_Name
Address
Publisher Address
Date_out N
Book_Lending
Phone
Card_No
Due_date
Card
Dept of ISE EWIT Page 16
DBMS Lab Manual N 2022
Schema Diagram
Table Creation
CREATE TABLE
BOOK_LENDING (DATE_OUT
DATE,
DUE_DATE DATE,
BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
BRANCH_ID REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON
DELETE CASCADE,
CARD_NO INTEGER,
PRIMARY KEY (BOOK_ID, BRANCH_ID, CARD_NO));
Table Descriptions
DESC PUBLISHER;
DESC BOOK;
DESC BOOK_AUTHORS;
DESC LIBRARY_BRANCH;
DESC BOOK_COPIES;
DESC BOOK_LENDING;
Queries:
1. Retrieve details of all books in the library – id, title, name of publisher, authors,
number of copies in each branch, etc.
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN ’01-JAN-2017’ AND ’01-JUL-2017’
GROUP BY CARD_NO
HAVING COUNT (*)>3;
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a
simple query.
5. Create a view of all books and its number of copies that are currently available in the
Library.
CREATE VIEW V_BOOKS AS
SELECT B.BOOK_ID, B.TITLE, C.NO_OF_COPIES
FROM BOOK B, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=C.BOOK_ID
AND C.BRANCH_ID=L.BRANCH_ID;
PROGRAM 2
Solution:
Entity-Relationship Diagram
Schema Diagram
Table Creation
Table Descriptions
Queries:
1. Count the customers with grades above Bangalore’s average.
2. Find the name and numbers of all salesmen who had more than one customer.
3. List all salesmen and indicate those who have and don’t have customers in their cities (Use UNION
operation.)
4. Create a view that finds the salesman who has the customer with the highest order of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must also be
deleted.
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table
orders and then execute the following:
Use ON DELETE SET NULL at the end of foreign key definitions while creating child table
customers and then executes the following:
PROGRAM 3
3. Consider the schema for Movie Database:
Schema Diagram
Table Creation
SELECT MOV_TITLE
FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME = ‘HITCHCOCK’);
2. Find the movie names where one or more actors acted in two or more movies.
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOIN operation).
OR
4. Find the title of movies and number of stars for each movie that has at least one
rating and find the highest number of stars that movie received. Sort the result by
movie title.
UPDATE RATING
SET REV_STARS=5
WHERE MOV_ID IN (SELECT MOV_ID FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME = ‘STEVEN
SPIELBERG’));
PROGRAM 4
4. Consider the schema for College Database:
Schema Diagram
Table Creation
DESC STUDENT;
Queries:
1. List all the student details studying in fourth semester ‘C’ section.
SELECT S.*, SS.SEM, SS.SEC
FROM STUDENT S, SEMSEC SS, CLASS C
WHERE S.USN = C.USN AND
SS.SSID = C.SSID AND
SS.SEM = 4 AND SS.SEC=’C’;
2. Compute the total number of male and female students in each semester and in each
section.
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for all students.
CREATE OR REPLACE PROCEDURE AVGMARKS
IS
CURSOR C_IAMARKS IS
SELECT GREATEST(TEST1,TEST2) AS A, GREATEST(TEST1,TEST3) AS B,
GREATEST(TEST3,TEST2) AS C
FROM IAMARKS
WHERE FINALIA IS NULL
FOR UPDATE;
C_A NUMBER;
C_B NUMBER;
C_C NUMBER;
C_SM NUMBER;
C_AV NUMBER;
BEGIN
OPEN C_IAMARKS;
LOOP
FETCH C_IAMARKS INTO C_A, C_B, C_C;
EXIT WHEN C_IAMARKS%NOTFOUND;
--DBMS_OUTPUT.PUT_LINE(C_A || ' ' || C_B || ' ' || C_C);
IF (C_A != C_B) THEN
C_SM:=C_A+C_B;
ELSE
C_SM:=C_A+C_C;
END IF;
C_AV:=C_SM/2;
--DBMS_OUTPUT.PUT_LINE('SUM = '||C_SM);
--DBMS_OUTPUT.PUT_LINE('AVERAGE = '||C_AV);
UPDATE IAMARKS SET FINALIA=C_AV WHERE CURRENT OF C_IAMARKS;
END LOOP;
CLOSE C_IAMARKS;
END;
/
Note: Before execution of PL/SQL procedure, IAMARKS table contents are:
Below SQL code is to invoke the PL/SQL stored procedure from the command line:
BEGIN
AVGMARKS;
END;
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, SUBJECT SUB
WHERE S.USN = IA.USN AND
SS.SSID = IA.SSID ANDSUB.SUBCODE
= IA.SUBCODE AND SUB.SEM = 8;
PROGRAM 5
5. Consider the schema for Company Database:
Entity-Relationship Diagram
SSN Controlled_by
Name N 1
DNO
Salary
DName
1 N
Employee Manages
Address
Department
MgrStartDate
1
Sex 1 N
M Dlocation
Supervisee
Supervisor
Supervision Works_on Controls
N
Hours
Project PName
PNO PLocation
Schema Diagram
Table Creation
NOTE: Once DEPARTMENT and EMPLOYEE tables are created we must alter department
table to add foreign constraint MGRSSN using sql command
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSECE01’,’JOHN’,’SCOTT’,’BANGALORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE01’,’JAMES’,’SMITH’,’BANGALORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE02’,’HEARN’,’BAKER’,’BANGALORE’,’M’, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE03’,’EDWARD’,’SCOTT’,’MYSORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE04’,’PAVAN’,’HEGDE’,’MANGALORE’,’M’, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE05’,’GIRISH’,’MALYA’,’MYSORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE06’,’NEHA’,’SN’,’BANGALORE’,’F’, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSACC01’,’AHANA’,’K’,’MANGALORE’,’F’, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSACC02’,’SANTHOSH’,’KUMAR’,’MANGALORE’,’M’, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSISE01’,’VEENA’,’M’,’MYSORE’,’M’, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSIT01’,’NAGESH’,’HR’,’BANGALORE’,’M’, 500000);
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘Scott’, either as a worker or as a manager of the department that controls the
project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise.
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department
4. Retrieve the name of each employee who works on all the projects Controlled by
department number 5 (use NOT EXISTS operator).
5. For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than Rs. 6, 00,000.