DBMS Lab Manual
DBMS Lab Manual
DBMS Lab Manual
Name of the document DBMS Laboratory with Mini Project Lab Manual
This manual was designed in accordance to the new syllabus (CBCS) suggested
by V.T.U for the fifth semester CSE Branch, Database Management System
Lab(15CSL58).
The manual is designed to help students understand both the theoretical concepts
involved in the exercises as well as the steps needed to carry out the experiments.
It gives detailed insight into the usage of SQL and the flow of the logic involved.
The design of this manual was done with the help of teaching staff, thus giving rise
Academy of Technology for having allowed the undertaking of this manual as well
03 PEO,PSO,PO 3-5
05 Syllabus 8-12
06 Evaluation Process 13
08 Introduction 15-35
VISION
To achieve academic excellence and strengthen the skills to meet emerging challenges of
computer science and engineering.
MISSION
M1. To impart strong theoretical foundations in the field of Computer Science and
M2. To inculcate research and innovation spirit among students through interaction with
M3. Instill professional ethics and social values amongst students with concern for
environment.
PSO1: Design, Implement and test system software and application software
to meet the desired needs.
PSO2: Develop solutions in the area of communication networks, Database
systems and computing systems.
Course Details
Course Name:DBMS LABORATORY WITH MINI PROJECT
Course Code:15CSL58
Course Objectives
Upon completion of this course, students are expected to:
Course Outcomes
Upon successful completion of this course, students should be able to:
CO3 Implement, analyze and evaluate the project developed for an application. AP 4
CO. Course PO PO PO PO PO PO PO PO PO PO PO PO
PSO1 PSO2 PSO3
No. Outcomes 1 2 3 4 5 6 7 8 9 10 11 12
1 10CSL58.1 - - - - - - - - - - - - √ - -
2 10CSL58.2 - - - √ - - - - - - - - - - -
3 10CSL58.3 √ - √ - - - - - - - - - - √ -
10CSL58 √ - √ √ - - - - - - - - √ √ -
PART A
1. Design, develop, and implement the specified queries for the following problems
using Oracle, MySQL, MS SQL Server, or any other DBMS underLINUX/
Windows environment.
2. Create Schema and insert at least 5 records for each table. Add appropriate
DatabaseConstraints.
PART B
1. 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
(Mobile apps on Android/IOS are not permitted.)
Laboratory Experiments
BOOK_AUTHORS(Book_id, Author_Name)
1. Retrieve details of all books in the library – id, title, name of publisher,
authors, number of copies in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but
from Jan 2017 to Jun 2017.
3. Delete a book in BOOK table. Update the contents of other tables to reflect
this data manipulation operation.
5.Create a view of all books and its number of copies that are currently
available in the Library.
2. Find the name and numbers of all salesmen who had more than one
customer.
3. List all the salesman and indicate those who have and don’t have customers
intheir cities (Use UNION operation.)
4. Create a view that finds the salesman who has the customer with the
highestorder of a day.
RATING(Mov_id, Rev_Stars)
3. List all actors who acted in a movie before 2000 and also in a movie after
2015 (use JOIN operation).
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 10
Global Academy of Technology
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.
5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.
CLASS(USN, SSID)
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.
4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.
DLOCATION(DNo,DLoc)
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.
5. For each department that has more than five employees, retrieve
thedepartment number and the number of its employees who are
makingmorethan Rs. 6,00,000.
For any problem selected, write the ER Diagram, apply ER-mapping rules,
normalize the relations, and follow the application development process.
Make sure that the application should have five or more tables, at least one
trigger and one stored procedure, using suitable frontend tool.
Indicative areas include; health care, education, industry, transport, supply
chain, etc.
Introduction
Overview of SQL DDL, DML and DCL Commands.
Some examples:
Some examples:
Some examples:
DATA TYPES
CONSTRAINT:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none isspecified.
UNIQUE Constraint: Ensures that all values in a column are different.
CHECK Constraint: Makes sure that all values in a column satisfy certaincriteria.
Primary Key Constraint: Used to uniquely identify a row in the table.
Foreign Key Constraint: Used to ensure referential integrity of the data.Each constraint is
discussed in the following sections.
NOT NULL Constraint :-By default, a column can hold NULL. If you not want to allow
NULL value in a column, you will want to place a constraint on this column specifying that
NULL is now not an allowable value.
DEFAULT Constraint :- The DEFAULT constraint provides a default value to a column
when the INSERT INTO statement does not provide a specific value.
UNIQUE Constraint :-The UNIQUE constraint ensures that all values in a column are
distinct.
CHECK Constraint :-The CHECK constraint ensures that all values in a column satisfy
certain conditions. Once defined, the database will only insert a new row or update an
existing row if the new value satisfies the CHECK constraint. The CHECK constraint is used
to ensure data quality
Primary Key :-A primary key is used to uniquely identify each row in a table. It can either be
part of the actual record itself , or it can be an artificial field (one that has nothing to do with
the actual record).
A primary key can consist of one or more fields on a table. When multiple fields are used as
a primary key, they are called a composite key.
Primary keys can be specified either when the table is created (using CREATE TABLE) or
by changing the existing table structure (using ALTER TABLE).
Below are examples for specifying a primary key when creating a table:
CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Namevarchar(30),
First_Namevarchar(30));
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>(<AttributeA1><Data TypeD1>
[<Constraints>],<Attribute A2><Data Type D2> [<Constraints>],
…….
<Attribute An><Data Type Dn> [<Constraints>],
[<integrity-constraint1>, <integrity-constraint k> ] );
b. 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));
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.
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.
2. SQL - UPDATE
Syntax: UPDATE tablename SET column_name =value [WHERE condition]
Examples:
updateemp set sal=2000 where empno=70000;
1 row updated.
3. SQL - DELETE FROM
Syntax: DELETE FROM tablename WHERE condition
Examples:
Delete fromemp where empno=7369;
1 row deleted.
1. COMMIT
Save changes (transactional).
Syntax:
COMMIT [WORK] [COMMENT 'comment_text']
COMMIT [WORK] [FORCE 'force_text' [,int] ]
2. ROLLBACK
Undo work done (transactional).
Syntax:
ROLLBACK [WORK] [TO [SAVEPOINT]'savepoint_text_identifier'];
ROLLBACK [WORK] [FORCE 'force_text'];
FORCE - will manually rollback an in-doubt distributed transaction
INPUT:
rollback;
Rollback complete.
3. SAVEPOINT
Save changes to a point (transactional).
Syntax:
SAVEPOINT text_identifier
Example:
UPDATE employees
SET salary = 95000
WHERE last_name = 'Smith';
SAVEPOINT justsmith;
UPDATE employees
SET salary = 1000000;
SAVEPOINT everyone;
SELECT SUM(salary) FROM employees;
ROLLBACK TO SAVEPOINT justsmith;
COMMIT;
SQL has one basic statement for retrieving information from a database; the SLELECT
statement
This is not the same as the SELECT operation of the relational algebra
Important distinction between SQL and the formal relational model;
SQL allows a table (relation) to have two or more tuples that are identical in all their
attribute values
Hence, an SQL relation (table) is a multi-set (sometimes called a bag) of tuples; it is not a
set of tuples .
SQL relations can be constrained to be sets by using the CREATE UNIQUE INDEX
command, or by using the DISTINCT option
Basic form of the SQL SELECT statement is called a mapping of a SELECT-FROM-
WHERE block
<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
Basic SQL queries correspond to using the following operations of the relational algebra:
SELECT
PROJECT
JOIN
All subsequent examples uses COMPANY database as shown below:
Example of a simple query on one relation
descemp;
RESULT:
Name Null? Type
-------------------------------- ---- ---------------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)
Query 0: Retrieve the birth date and address of the employee whose name is 'John B.Smith'.
Q0: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
Q3: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S
WHERE E.SUPERSSN=S.SSN
In Q3, 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
Q3: 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:
Example:
Q5: SELECT SSN, DNAME
FROM EMPLOYEE, DEPARTMENT
Note: It is extremely important not to overlook specifying any selection and join
conditions intheWHERE-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.
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.
Q1b: 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:SELECTDISTINCTSALARY
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 5: Make a list of all project numbers for projects that involve an employee whose last
nameis 'Smith' as a worker or as a manager of the department that controls the project.
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
selectsan 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
Query 7: Retrieve the name of each employee who has a dependent with the same firstname 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
Q7a: SELECT E.FNAME, E.LNAME FROM EMPLOYEE E, DEPENDENT D WHERE
E.SSN=D.ESSN AND E.FNAME=D.DEPENDENT_NAME
Note: In Q8, the correlated nested query retrieves all DEPENDENT tuples related to an
EMPLOYEEtuple. If none exist, the EMPLOYEE tuple is selected
EXPLICIT SETS
Query 10: Retrieve the names of all employees who do not have supervisors.
AGGREGATE FUNCTIONS
Query 11: Find the maximum salary, the minimum salary, and the average salary among
allemployees.
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.
Queries 13 and 14: Retrieve the total number of employees in the company (Q13), and the
number of employees in the 'Research' department (Q14).
GROUPING
In Q15, 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 16: For each project, retrieve the project number, project name, and the number of
employees who work on that project.
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 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.
SUBSTRING COMPARISON
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 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.
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
arbitrary character.
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 a10% raise.
Query 21: Retrieve a list of employees and the projects each works in, ordered by theemployee's
department, and within each department ordered alphabetically by employeelast name.
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
Query 23: List the names of managers who have least one dependent.
Q23: SELECT FNAME, LNAME
FROM EMPLOYEEWHERE EXISTS (SELECT * FROM DEPENDENT
WHERE SSN=ESSN)AND EXISTS ( SELECT * FROM DEPARTMENT
WHERE SSN=MGRSSN );
Example:
Insert a tuple for a new EMPLOYEE for whom we only know the FNAME, LNAME and
SSNattributes.
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN)VALUES ('Richard', 'Marini',
'653298653')
Important Note: Only the constraints specified in the DDL commands are
automaticallyenforced 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.
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 33
Global Academy of Technology
Note: The DEPTS_INFO table may not be up-to-date if we change the tuples in either
theDEPARTMENT 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:
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 and take 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 could be
base tables or previously defined view.
Allows for limited update operations Since the table may not physically be stored
Allows full query operations
A convenience for expressing certain operations
A view does not necessarily exist in physical form, which limits the possible update
operations that can be applied to views.
LAB EXPERIMENTS
1. Retrieve details of all books in the library – id, title, name of publisher, authors,
number of copies in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan
2017 to Jun 2017
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.
Schema Diagram
Card
Card_no
Table Creation
PHONE INT,
(AUTHOR_NAME VARCHAR(20),
DUE_DATE DATE,
AUTHOR_NAME BOOK_ID
NAVATHE 1
NAVATHE 2
ULLMAN 3
CHARLES 4
GALVIN 5
2 2 12
5 2 13
7 3 14
1 5 10
3 4 11
INSERT INTO CARD VALUES (101);
CARDNO
101
102
103
104
105
INSERT INTO BOOK_LENDING VALUES (’01-JAN-17’,’01-JUN-17’, 1, 10, 101);
1.Retrieve details of all books in the library – id, title, name of publisher,
authors, number of copies in each branch, etc.
SELECT B.BOOK_ID, B.TITLE, B.PUBLISHER_NAME, A.AUTHOR_NAME,
C.NO_OF_COPIES, L.BRANCH_ID
FROM BOOK B, BOOK_AUTHORS A, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=A.BOOK_ID AND B.BOOK_ID=C.BOOK_ID
AND L.BRANCH_ID=C.BRANCH_ID;
NO_OF_C BRANCH_I
BOOK_ID TITLE PUBLISHER_NAME AUTHOR_NAME OPIES D
1. Get the particulars of borrowers who have borrowed more than 3 books, but from
Jan 2017 to Jun 2017
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN ’01-JAN-2017’ AND ’01-JUN-2017’
GROUP BY CARD_NO
HAVING COUNT (*)>3;
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 44
Global Academy of Technology
CARD_NO
101
2. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
DELETE FROM BOOK
WHERE BOOK_ID=3;
3. Partition the BOOK table based on year of publication. Demonstrate its working
with a simple query.
PUB_YEAR
Jan-17
Jun-16
Sep-16
Sep-15
May-16
4. Create a view of all books and its number of copies that are currently available in
the Library.
CREATE VIEW V_BOOKS AS
WHERE B.BOOK_ID=C.BOOK_ID
AND C.BRANCH_ID=L.BRANCH_ID;
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.
Schema Diagram
Table Creation
DESC SALESMAN
NAME VARCHAR(20)
CITY VARCHAR(20)
COMMISSION NUMBER(3)
DESC CUSTOMER1
CUST_NAME VARCHAR(20)
CITY VARCHAR(20)
GRADE NUMBER(3)
SALESMAN_ID NUMBER(4)
DESC ORDERS
PURCHASE_AMT NUMBER(10,2)
ORD_DATE DATE
CUSTOMER_ID NUMBER(4)
SALESMAN_ID NUMBER(4)
Queries:
2. Find the name and numbers of all salesmen who had more than one customer.
SALESMAN_ID NAME
------------------- -----------
1000 GEORGE
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.
CREATE VIEW ELITSALESMAN AS
SELECT B.ORD_DATE, A.SALESMAN_ID, A.NAME FROM SALESMAN A, ORDERS B
WHERE A.SALESMAN_ID = B.SALESMAN_ID
AND B.PURCHASE_AMT=(SELECT MAX (PURCHASE_AMT) FROM ORDERS C
WHERE C.ORD_DATE = B.ORD_DATE);
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:
3. List all actors who acted in a movie before 2000 and also in a movie after
2015 (use JOIN operation).
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.
5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.
Schema Diagram
Table Creation
DESC ACTOR
DESC DIRECTOR
DESC MOVIES
DESC MOVIE_CAST
DESC RATING
4 SRIDEVI F
1 MADHURI DIXIT F
2 AAMIR KHAN M
3 JUHI CHAWLA F
INSERT INTO MOVIES VALUES (501,’JAB HARRY MET SEJAL’, 2017, ‘HINDI’, 104);
INSERT INTO MOVIES VALUES (502,’RAJAKUMARA’, 2017, ‘KANNADA’, 103);
INSERT INTO MOVIES VALUES (503,’JOLLY LLB 2’, 2013, ‘HINDI’, 100);
INSERT INTO MOVIES VALUES (504,’TERMINATOR GENESYS, 2015, ‘ENGLISH’, 102);
INSERT INTO MOVIES VALUES (505,’JAWS, 1975, ‘ENGLISH’, 106);
INSERT INTO MOVIES VALUES (506,’BRIDGE OF SPIES’,2015,’ENGLISH’, 106);
INSERT INTO MOVIES VALUES (507,’VERTIGO, 1943, ‘ENGLISH’, 105);
INSERT INTO MOVIES VALUES (508,’SHADOW OF A DOUBT, 1943, ‘ENGLISH’, 105);
1 501 HEROINE
1 502 HEROINE
3 503 COMEDIAN
4 504 GUEST
4 501 HERO
MOV_ID REV_STARS
501 4
502 2
503 5
504 4
505 3
506 2
Queries:
1. List the titles of all movies directed by ‘Hitchcock’.
SELECT MOV_TITLE
FROM MOVIES
WHERE DIR_ID IN ( SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME='HITCHCOCK');
MOV_TITLE
----------------
VERTIGO
SHADOW OF A DOUBT
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_TITLEHAVING COUNT (*)>1
MOV_TITLE
--------------------
JAB HARRY MET SEGAL
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.
MOV_TITLE MAX(REV_STARS)
---------------------------------------------------------------------------------
BRIDGE OF SPIES 5
JAB HARRY MET SEJAL 4
JAWS 5
JOLLY LLB2 5
RAJAKUMARA 2
SHADOW OF A DOUBT 5
TERMINATOR GENESYS 4
VERTIGO 2
UPDATE RATING
SET REV_STARS=5
WHERE MOV_ID IN (SELECT MOV_ID FROM MOVIES WHERE DIR_ID IN
2 ROWS UPDATED
MOV_ID REV_STARS
501 4
502 2
503 5
504 4
505 5
506 5
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.
4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.
Schema Diagram
Table Creation
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS81','CSE8C', 15, 16, 18);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS82','CSE8C', 12, 19, 14);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS83','CSE8C', 19, 15, 20);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS84','CSE8C', 20, 16, 19);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1GA13CS091','10CS85','CSE8C', 15, 15, 12);
USN SEC
1GA13CS020 CSE8A
1GA13CS062 CSE8A
1GA13CS066 CSE8B
1GA13CS091 CSE8C
1GA14CS010 CSE7A
1GA14CS025 CSE7A
1GA14CS032 CSE7A
1GA15CS091 CSE4C
1GA14CS045 CSE3A
1GA14CS088 CSE3B
1GA14CS122 CSE3C
1GA15CS011 CSE4A
1GA15CS045 CSE4B
15CS32 ADE 3 4
15CS33 DSA 3 4
15CS34 CO 3 4
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.
CREATE VIEW
STU_TEST1_MARKS_VIEW AS
SELECT TEST1, SUBCODE
FROM IAMARKS
WHERE USN ='1GA15CS091';
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for all students.
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);
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,
(CASEWHEN 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 AND
SUB.SUBCODE = IA.SUBCODE AND
SUB.SEM = 8;
DLOCATION (DNo,DLoc)
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘KUMAR’, 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). 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.
Schema Diagram
Table Creation
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATECE01’,’MOHAN’,’KUMAR’,’BANGALORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE01’,’JAGAN’,’RAO’,’BANGALORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE02’,’HEMANTH’,’BHATT’,’BANGALORE’,’M’, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE03’,’ESHWAR’,’KUMAR’,’MYSORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE04’,’PAVAN’,’HEGDE’,’MANGALORE’,’M’, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE05’,’GIRISH’,’MALYA’,’MYSORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATCSE06’,’NEHA’,’SN’,’BANGALORE’,’F’, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATACC01’,’AHANA’,’K’,’MANGALORE’,’F’, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATACC02’,’SANTHOSH’,’KUMAR’,’MANGALORE’,’M’, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATISE01’,’VEENA’,’M’,’MYSORE’,’M’, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘GATIT01’,’NAGESH’,’HR’,’BANGALORE’,’M’, 500000);
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
UPDATE EMPLOYEE
SETSUPERSSN=NULL, DNO=’3’
WHERE SSN=’GATECE01’;
UPDATE EMPLOYEE
SETSUPERSSN=’GATCSE02’, DNO=’5’
WHERE SSN=’GATCSE01’;
UPDATE EMPLOYEE
SETSUPERSSN=’GATCSE03’, DNO=’5’
WHERE SSN=’GATCSE02’;
UPDATE EMPLOYEE
SETSUPERSSN=’GATCSE04’, DNO=’5’
WHERE SSN=’GATCSE03’;
UPDATE EMPLOYEE
SETDNO=’5’, SUPERSSN=’GATCSE05’
WHERE SSN=’GATCSE04’;
UPDATE EMPLOYEE
SETDNO=’5’, SUPERSSN=’GATCSE06’
WHERE SSN=’GATCSE05’;
UPDATE EMPLOYEE
SETDNO=’5’, SUPERSSN=NULL
WHERE SSN=’GATCSE06’;
UPDATE EMPLOYEE
SETDNO=’1’, SUPERSSN=’GATACC02’
WHERE SSN=’GATACC01’;
UPDATE EMPLOYEE
SETDNO=’1’, SUPERSSN=NULL
WHERE SSN=’GATACC02’;
UPDATE EMPLOYEE
SETDNO=’4’, SUPERSSN=NULL
WHERE SSN=’GATISE01’;
UPDATE EMPLOYEE
SETDNO=’2’, SUPERSSN=NULL
WHERE SSN=’GATIT01’;
4 GATCSE01 100
6 GATCSE01 101
8 GATCSE01 102
10 GATCSE02 100
3 GATCSE04 100
4 GATCSE05 101
5 GATCSE06 102
6 GATCSE03 102
7 GATECE01 103
5 GATACC01 104
6 GATACC02 105
4 GATISE01 106
10 GATIT01 107
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘KUMAR’, either as a worker or as a manager of the department that
controls the project.
PNO
------------------------------------------------------------------------------------------
100
101
102
103
104
105
106
107
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).
FNAME LNAME
------------------------------------
JGAN RAO
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.
DNO COUNT(*)
---------------------------------------
5 3
Viva Questions
1. What is SQL?
Structured Query Language
2. What is database?
A database is a logically coherent collection of data with some inherent meaning, representing
some aspect of real world and which is designed, built and populated with data for a specific
purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other words
it is general-purpose software that provides the users with the processes of defining, constructing
and manipulating the database for various applications.
5. Advantages of DBMS?
o Redundancy is controlled.
o Security Problems.
Logical level:The next higher level of abstraction, describes what data are stored in database and
o Referential Integrity:States that “Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
Physical Data Independence: Modification in physical level should not affect the logical level.
Logical Data Independence: Modification in logical level should affect the view level.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate
users from the effects of restructuring and growth in the database. Hence accounts for logical
data independence.
functional dependency if removal of any attribute A from X means that the dependency
does not hold any more.
InclusionDependency:
An Inclusion Dependency is a statement of the form that some columns of a relation are
contained in other columns. A foreign key constraint is an example of inclusion dependency.
52. What is durability in DBMS?
Once the DBMS informs the user that a transaction has successfully completed, its effects
should persist even if the system crashes before all its changes are reflected on disk. This
property is called durability.
53. What do you mean by atomicity and aggregation?
Atomicity:
Either all actions are carried out or none are. Users should not have to worry about the
effectof incomplete transactions. DBMS ensures this by undoing the actions of incomplete
transactions.
Aggregation:
A concept which is used to model a relationship between a collection of entities and
relationships. It is used when we need to express a relationship among relationships.
54. What is a Phantom Deadlock?
In distributed deadlock detection, the delay in propagating local information might cause the
deadlock detection algorithms to identify deadlocks that do not really exist. Such situations
are called phantom deadlocks and they lead to unnecessary aborts.
55. What is a checkpoint and when does it occur?
A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can
reduce the amount of work to be done during restart in the event of subsequent crashes.
56. What are the different phases of transaction?
Different phases are
lysis phase
Network schema uses a graph data structure to organize records example for such a
database management system is CTCG while a hierarchical schema uses a tree data
structure example for such a system is IMS.
60. What is a query?
A query with respect to DBMS relates to user commands that are used to interact with a
data base. The query language can be classified into data definition language and data
manipulation language.
61. What do you mean by Correlated subquery?
Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent
query. Depending on how the subquery is written, it can be executed once for the parent
query or it can be executed once for each row returned by the parent query. If the subquery
is executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent
subquery columns in its WHERE clause. Columns from the subquery cannot be referenced
anywhere else in the parent query. The following example demonstrates a non-correlated
subquery.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where
CUST.CNUM = ORDER.CNUM)
62. What are the primitive operations common to all record management systems?
Addition, deletion and modification.
63. Name the buffer in which all the commands that are typed in are stored
‘Edit’ Buffer
64. What are the unary operations in Relational Algebra?
PROJECTION and SELECTION.
65. Are the resulting relations of PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
66. What is RDBMS KERNEL?
Two important pieces of RDBMS architecture are the kernel, which is the software, and the
data dictionary, which consists of the system-level data structures used by the kernel to
manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed
specifically for controlling data access; its primary functions are storing, retrieving, and
securing data. An RDBMS maintains its own list of authorized users and their associated
privileges; manages memory caches and paging; controls locking for concurrent resource
usage; dispatches and schedules user requests; and manages space usage within its table-
space structures.
67. Name the sub-systems of a RDBMS
I/O, Security, Language Processing, Process Control, Storage Management, Logging and
Recovery, Distribution Control, Transaction Control, Memory Management, Lock
Management
68. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of the
database and maintained exclusively by the kernel.
69. What is the job of the information stored in data-dictionary?
The information in the data dictionary validates the existence of the objects, provides access
to them, and maps the actual physical storage location.