DBMS Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 103

GLOBAL ACADEMY OF TECHNOLOGY

Rajarajeshwari Nagar, Bengaluru – 560 098.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DBMS LABORATORY WITH MINI PROJECT


(V Sem – 15CSL58)
(Syllabus Scheme: 2015-2016)
Version: 1
Academic Year: 2017-2018
w.e.f 7th August, 2017

Prepared by: Approved by:


Dr. Kavitha K S Dr. Kavitha C
Prof. Veena V P H.O.D., CSE Dept
Prof. Sindhu P Menon
Document Log

Name of the document DBMS Laboratory with Mini Project Lab Manual

Syllabus Scheme 2015-2016

Current version number and date V 1 / 07.08.2017

Subject code 15CSL58

Editorial Committee Database Management System Lab faculties

Approved by Dr. Kavitha C, HOD, Dept of CSE


Dr. Kavitha K S,
Lab faculty Prof. Veena V P,
Prof. Sindhu P Menon .
Computer Programmer Mr.Parashivamurthy.C
PREFACE

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

to a proper amalgamation of both the teacher and the students’ viewpoints.


ACKNOWLEDGEMENT
We would like to express our sincere gratitude to the management of Global

Academy of Technology for having allowed the undertaking of this manual as well

as their encouragement in the development of the solutions for the lab.

We are grateful to our beloved Dr. RanaPratap Reddy N, Principal, Dr.Kavitha C,

HOD, Department of Computer Science & Engineering and staff members of

Computer Science Department for extending their support and encouragement to

write the manual and for lending all kinds of resources.


TABLE OF CONTENTS

SL No. DESCRIPTION PAGE NO.

01 Vision and Mission of Institution 1

02 Vision and Mission of Department 2

03 PEO,PSO,PO 3-5

04 Course Details 6-7

05 Syllabus 8-12

06 Evaluation Process 13

07 Steps to log in to the isqlplus 14

08 Introduction 15-35

09 PART-A: SQL Programming

9.1 A. Library Database 36-46

9.2 B.Order Database 47-53

9.3 C.Movie Database 54-63

9.4 D.College Database 64-76

9.5 E.Company Database 77-85

10 Viva Questions 86-98


Global Academy of Technology

Vision of the Institute


Become a premier institution imparting quality education in engineering and
management to meet the changing needs of society.

Mission of the Institute


M1: Create environment conducive for continuous learning through quality
teaching and learning processes supported by modern infrastructure.
M2: Promote Research and Innovation through collaboration with industries.
M3: Inculcate ethical values and environmental consciousness through holistic
education programs.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 1


Global Academy of Technology

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

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

Engineering accompanied with extensive practical training.

M2. To inculcate research and innovation spirit among students through interaction with

industry and projects that address societal issues.

M3. Instill professional ethics and social values amongst students with concern for

environment.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 2


Global Academy of Technology

Program Educational Objectives [PEOs]


CSE graduates will be able to:

PEO1: Succeed in engineering/management positions with professional Ethics.


PEO2: Engage in improving professional knowledge throughCertificate/post -
graduate programs in engineering or management.
PEO3: Establish themselves as entrepreneurs and contribute to the society.

Program Specific Outcomes (PSO)

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 3


Global Academy of Technology

Program Outcomes (POs)

Engineering Graduates will be able to:


1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 4
Global Academy of Technology

10. Communication: Communicate effectively on complex engineering activities with


the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as
a member and leader in a team, to manage projects and in multidisciplinary
environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of
technological change.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 5


Global Academy of Technology

Course Details
Course Name:DBMS LABORATORY WITH MINI PROJECT

Course Code:15CSL58

Course Objectives
Upon completion of this course, students are expected to:

1. Foundation knowledge in database concepts, technology and practice to


groom students into well-informed database application developers.
2. Strong practice in SQL programming through a variety of database problems.
3. Develop database applications using front-end tools and back-end DBMS.

Course Outcomes
Upon successful completion of this course, students should be able to:

Subject code: 15CSL58 Subject Name:Database Management System Lab Manual

Cos COURSE OUTCOME CL No. of sessions

CO1 Create, Update and query on the database. AP 14

CO2 Demonstrate the working of different concepts of DBMS . AP 14

CO3 Implement, analyze and evaluate the project developed for an application. AP 4

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 6


Global Academy of Technology

Course outcome mapping with program outcome

CO’s Course Outcome POs &PSOs CL Class Sessions

15CSL58.1 Create, Update and query on the database. PO3, PSO1 AP 14

15CSL58.2 Demonstrate the working of different concepts of DBMS. PO4 AP 14

15CSL58.3 Implement, analyze and evaluate the project


PO3, PO1, PSO2 AP 4
developed for an application.

Course – PO/PSO Mapping Strength


14 of 14 (100%) sessions are devoted to PO1

14 of 14 (100%) sessions are devoted to PO3

14 of 14 (100%) sessions are devoted to PO4

14 of 14 (100%) sessions are devoted to PSO1

14 of 14 (100%) sessions are devoted to PSO2

Mapping Strength of CO’s and PO’s

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

Course – POs/PSO Mapping

Course PO PO PO PO PO PO PO PO PO PO PO PO PSO1 PSO2 PSO3


1 2 3 4 5 6 7 8 9 10 11 12

10CSL58 √ - √ √ - - - - - - - - √ √ -

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 7


Global Academy of Technology

DBMS LABORATORY WITH MINI PROJECT

Subject Code: 15CSL58 IA Marks: 20

No. of Practical Hrs. / Week: 01I + 02P Exam Hours: 03

Total No. of Practical Hrs: 40 Exam Marks: 80

PART A

PART-A: SQL Programming (Max. Exam Marks. 50)

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

PART-B: Mini Project (Max. Exam Marks. 30)

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 8


Global Academy of Technology

Laboratory Experiments

Part A: SQL Programming

1 Consider the following schema for a Library Database:

BOOK(Book_id, Title, Publisher_Name, Pub_Year)

BOOK_AUTHORS(Book_id, Author_Name)

PUBLISHER(Name, Address, Phone)

BOOK_COPIES(Book_id, Branch_id, No-of_Copies)

BOOK_LENDING(Book_id, Branch_id, Card_No, Date_Out, Due_Date)

LIBRARY_BRANCH(Branch_id, Branch_Name, Address)

Write SQL queries to

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 9


Global Academy of Technology

2 Consider the following schema for Order Database:

SALESMAN(Salesman_id, Name, City, Commission)

CUSTOMER(Customer_id, Cust_Name, City, Grade, Salesman_id)

ORDERS(Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)

Write SQL queries to

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

5. Demonstrate the DELETE operation by removing salesman with id 1000.


Allhis orders must also be deleted.
3 Consider the schema for Movie Database:

ACTOR(Act_id, Act_Name, Act_Gender)

DIRECTOR(Dir_id, Dir_Name, Dir_Phone)

MOVIES(Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)

MOVIE_CAST(Act_id, Mov_id, Role)

RATING(Mov_id, Rev_Stars)

Write SQL queries to

1. List the titles of all movies directed by ‘Hitchcock’.


2. Find the movie names where one or more actors acted in two or more
movies.

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.

4 Consider the schema for College Database:

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

4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.

5. Categorize students based on the following criterion:


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.

5 Consider the schema for Company Database:

EMPLOYEE(SSN, Name, Address, Sex, Salary, SuperSSN, DNo)

DEPARTMENT(DNo, DName, MgrSSN, MgrStartDate)

DLOCATION(DNo,DLoc)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 11


Global Academy of Technology

PROJECT(PNo, PName, PLocation, DNo)

WORKS_ON(SSN, PNo, Hours)

Write SQL queries to

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


projectsControlled by department number 5 (use NOT EXISTS
operator).

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.

Part B: Mini project

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 12


Global Academy of Technology

VTU Lab Evaluation Process


Rubrics for DBMS Lab (Part A)
Sl. No Criteria Marks
1 Record 04
2 Write Up 02
3 Execution 04
4 Viva 02
TOTAL 12

Rubrics for DBMS Mini Project Evaluation (Part B)

Sl. No Criteria Marks


1 Requirement Collection 02
2 Identify Relations, attributes of a Relation 02
3 Draw ER Diagram 05
4 Mapping of ER Diagram to Tables 04
5 Front End Design 05
6 Project Demo( Demonstration & Questionnaire Session) 07
7 Report 05
TOTAL 30

Internal Assessment Evaluation (End of Semester)


Sl. No Activity Marks
Part A:
1
Procedure + Conduction + Viva 50
Part B:
2
Demonstration + Report + Viva voce 30
TOTAL 80

FINAL INTERNAL ASSESSMENT CALCULATION


Sl.No Activity Marks
1 Average of Weekly Entries 12
2 Internal Assessment Reduced To 8
TOTAL 20

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 13


Global Academy of Technology

Steps to log in to the isqlplus:

1.TYPE HTTP://192.168.0.6:5560/ISQLPLUS IN THE WEB BROWSER.


2.TYPE YOUR USN NUMBER AGAINST THE USER NAME BOX.
3.TYPE PASSWORD AGAINST THE PASSWORD BOX.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 14


Global Academy of Technology

Introduction
Overview of SQL DDL, DML and DCL Commands.

DDL is Data Definition Language statements:

Some examples:

CREATE - to create objects in the database


ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
COMMENT - add comments to the data dictionary
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command

DML is Data Manipulation Language statements:

Some examples:

SELECT - retrieve data from the a database


INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency

DCL is Data Control Language statements:

Some examples:

COMMIT - save work done


SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like what rollback segment to use.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 15


Global Academy of Technology

DATA TYPES

1. Numeric: NUMBER, NUMBER(s,p), INTEGER, INT, FLOAT, DECIMAL.


2. Character: CHAR(n), VARCHAR(n), VARCHAR2(n), CHAR VARYING(n)
3. Bit String: BLOB, CLOB
4. Boolean: true, false, and null
5. Date and Time: DATE (YYYY-MM-DD) TIME( HH:MM:SS)
6. Timestamp: DATE + TIME
To limit the type of information stored in a table can be done through the
CONSTRAINTkeyword, which is discussed next.

CONSTRAINT:

Common types of constraints include the following:

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 16


Global Academy of Technology

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

Below are examples for specifying a primary key by altering a table:

ALTER TABLE Customer ADD PRIMARY KEY (SID);


Note:- Before using the ALTER TABLE command to add a primary key, you'll need to
make sure that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an
accepted value for that field.
Foreign Key :-
A foreign key is a field (or fields) that points to the primary key of another table. Thepurpose
of the foreign key is to ensure referential integrity of the data. In other words, only values
that are supposed to appear in the database are permitted.
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>(<AttributeA1><Data TypeD1>
[<Constraints>],<Attribute A2><Data Type D2> [<Constraints>],
…….
<Attribute An><Data Type Dn> [<Constraints>],
[<integrity-constraint1>, <integrity-constraint k> ] );

a. A constraint NOT NULL may be specified on an attribute A constraint


NOT NULL may be specified on an attribute .
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 17
Global Academy of Technology

Ex: CREATE TABLE DEPARTMENT (


DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9) );

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

c. 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(SSN)
ON DELETE SET DEFAULT ON UPDATE CASCADE);
DROP TABLE

1. Used to remove a relation (base table) and its definition.


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

Example: DROP TABLE DEPENDENT;

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 18


Global Academy of Technology

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

1. ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE;


All constraints and views that reference the column are dropped automatically, along
with the column.
2. ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS RESTRICT;
Successful if no views or constraints reference the column.
3. ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN DROP DEFAULT;
4. ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT
“333445555”;

Basic SQL DML Commands.


To practice basic SQL DML Commands such as INSERT, DELETE, etc.

1. SQL - INSERT INTO


Syntax: INSERT INTO tablename VALUES (value list)
Examples:
Insert into prog values('&pname','&doj');
Enter value for pname: ravi www.jntuhome.com
Enter value for doj: 15-june-81
(or)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 19


Global Academy of Technology

Insert into prog values('ravi','15-june-81')


1 row created.

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.

Basic SQL DCL Commands.


To practice basic SQL DCL Commands such as COMMIT, ROLLBACK, SAVEPOINT.

1. COMMIT
Save changes (transactional).

Syntax:
COMMIT [WORK] [COMMENT 'comment_text']
COMMIT [WORK] [FORCE 'force_text' [,int] ]

FORCE - will manually commit an in-doubt distributed transaction force_text -


transaction identifier (see the DBA_2PC_PENDING view) int - sets a specific SCN.
If a network or machine failure prevents a distributed transaction from committing
properly, Oracle will store any commit comment in the data dictionary along with the
transaction ID.
INPUT:
commit;
Commit complete.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 20


Global Academy of Technology

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;

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 21


Global Academy of Technology

BASIC QUERIES IN SQL

 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

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

SIMPLE SQL QUERIES

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

1. Get the description of EMP table.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 22


Global Academy of Technology

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 23


Global Academy of Technology

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 24


Global Academy of Technology

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 4: Retrieve the SSN values for all employees.

Q4: 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:
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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 25


Global Academy of Technology

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.

Q5:(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')

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 26


Global Academy of Technology

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

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

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 27


Global Academy of Technology

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 7 in an alternative form that uses
EXIST.

Q7b: SELECT FNAME, LNAME


FROM EMPLOYEE
WHERE EXISTS (SELECT * FROM DEPENDENT WHERE SSN=ESSN AND
FNAME=DEPENDENT_NAME)
Query 8: Retrieve the names of employees who have no dependents.
Q8: SELECT FNAME, LNAME
FROM EMPLOYEE
WHERE NOT EXISTS
(SELECT * FROM DEPENDENT WHERE SSN=ESSN)

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

It is also possible to use an explicit (enumerated) set of values in the WHERE-clause


ratherthan a nested query
Query 9: Retrieve the social security numbers of all employees who work on
Projectnumber 1, 2, or 3.
Q9: 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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 28


Global Academy of Technology

Query 10: Retrieve the names of all employees who do not have supervisors.

Q10: 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 notincluded in the result

AGGREGATE FUNCTIONS

Includes COUNT, SUM, MAX, MIN, and AVG

Query 11: Find the maximum salary, the minimum salary, and the average salary among
allemployees.

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:SELECTMAX (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
WHERE DNO=DNUMBER AND DNAME='Research’

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 29


Global Academy of Technology

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 15: For each department, retrieve the department number, the number of
employees in the department, and their average salary.

Q15: SELECT DNO, COUNT (*), AVG (SALARY)


FROM EMPLOYEE GROUP BY DNO

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

Q16: SELECT PNUMBER, PNAME, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP 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 than on individual tuples)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 30


Global Academy of Technology

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
HAVING COUNT (*) > 2

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.

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 31


Global Academy of Technology

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.

Q20: SELECT FNAME, LNAME, 1.1*SALARY


FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSNAND 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 theemployee's
department, and within each department ordered alphabetically by employeelast name.

Q21: SELECT DNAME, LNAME, FNAME, PNAME


FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNOAND 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

MORE EXAMPLE QUERIES:


Query 22: Retrieve the names of all employees who have two or more dependents.

Q22: SELECT LNAME, FNAME


FROMEMPLOYEE
WHERE (SELECT COUNT (*) FROM DEPENDENTWHERE SSN=ESSN) ≥ 2);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 32


Global Academy of Technology

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

SPECIFYING UPDATES IN SQL


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

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

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 34


Global Academy of Technology

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 35


Global Academy of Technology

LAB EXPERIMENTS

PART A: SQL PROGRAMMING

A. Consider the following schema for a Library Database:

BOOK (Book_id, Title, Publisher_Name, Pub_Year)

BOOK_AUTHORS (Book_id, Author_Name)

PUBLISHER (Name, Address, Phone)

BOOK_COPIES (Book_id, Branch_id, No-of_Copies)

BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)

LIBRARY_BRANCH (Branch_id, Branch_Name, Address)

Write SQL queries to

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 36


Global Academy of Technology

Schema Diagram

Card
Card_no

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 37


Global Academy of Technology

Table Creation

CREATE TABLE PUBLISHER

(NAME VARCHAR (20) PRIMARY KEY,

PHONE INT,

ADDRESS VARCHAR (20));

CREATE TABLE BOOK


(BOOK_ID INT PRIMARY
KEY, TITLE VARCHAR (20),

PUB_YEAR VARCHAR (20),

PUBLISHER_NAME REFERENCES PUBLISHER (NAME) ON DELETE CASCADE);

CREATE TABLE BOOK_AUTHORS

(AUTHOR_NAME VARCHAR(20),

BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,

PRIMARY KEY (BOOK_ID, AUTHOR_NAME));


Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 38
Global Academy of Technology

CREATE TABLE LIBRARY_BRANCH


(BRANCH_ID INT PRIMARY KEY,
BRANCH_NAME VARCHAR(50),
ADDRESS VARCHAR(50));

CREATE TABLE BOOK_COPIES


(NO_OF_COPIES INT,
BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
BRANCH_ID REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON DELETE CASCADE,
PRIMARY KEY (BOOK_ID, BRANCH_ID));

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 39


Global Academy of Technology

CREATE TABLE CARD

(CARD_NO INT PRIMARY KEY);

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 REFERENCES CARD (CARD_NO) ON DELETE CASCADE,


PRIMARY KEY (BOOK_ID, BRANCH_ID, CARD_NO));

Insertion of Values to Tables

INSERT INTO PUBLISHER VALUES (‘MCGRAW-HILL’, 9989076587, ‘BANGALORE’);


INSERT INTO PUBLISHER VALUES (‘PEARSON’, 9889076565, ‘NEWDELHI’);

INSERT INTO PUBLISHER VALUES (‘PRENTICE HALL’, 7455679345, ‘HYDERABAD’);


INSERT INTO PUBLISHER VALUES (‘WILEY’, 8970862340, ‘CHENNAI’);

INSERT INTO PUBLISHER VALUES (‘MIT’, 7756120238, ‘BANGALORE’);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 40


Global Academy of Technology

Select * from PUBLISHER;

NAME PHONE ADDRESS


MCGRAW-HILL 9989076587 BANGALORE
PEARSON 9889076565 NEWDELHI
PRENTICE HALL 7455679345 HYDERABAD
WILEY 8970862340 CHENNAI
MIT 7756120238 BANGALORE

INSERT INTO BOOK VALUES (1,’DBMS’,’JAN-2017’, ‘MCGRAW-HILL’);

INSERT INTO BOOK VALUES (2,’ADBMS’,’JUN-2016’, ‘MCGRAW-HILL’);


INSERT INTO BOOK VALUES (3,’CD’,’SEP-2016’, ‘PEARSON’);

INSERT INTO BOOK VALUES (4,’ALGORITHMS’,’SEP-2015’, ‘MIT’);

INSERT INTO BOOK VALUES (5,’OS’,’MAY-2016’, ‘PEARSON’);

Select * from BOOK;

BOOK_ID TITLE PUB_YEAR PUBLISHER_NAME


1 DBMS Jan-17 MCGRAW-HILL
2 ADBMS Jun-16 MCGRAW-HILL
3 CD Sep-16 PEARSON
4 ALGORITHMS Sep-15 MIT
5 OS May-16 PEARSON

INSERT INTO BOOK_AUTHORS VALUES (’NAVATHE’, 1);

INSERT INTO BOOK_AUTHORS VALUES (’NAVATHE’, 2);

INSERT INTO BOOK_AUTHORS VALUES (’ULLMAN’, 3);

INSERT INTO BOOK_AUTHORS VALUES (’CHARLES’, 4);

INSERT INTO BOOK_AUTHORS VALUES (’GALVIN’, 5);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 41


Global Academy of Technology

Select * from BOOK_AUTHORS;

AUTHOR_NAME BOOK_ID
NAVATHE 1
NAVATHE 2
ULLMAN 3
CHARLES 4
GALVIN 5

INSERT INTO LIBRARY_BRANCH VALUES (10,’VIJAY NAGAR’,’BANGALORE’);

INSERT INTO LIBRARY_BRANCH VALUES (11,’GAT’,’BANGALORE’);

INSERT INTO LIBRARY_BRANCH VALUES (12,’RAJAJI NAGAR’, ’BANGALORE’);

INSERT INTO LIBRARY_BRANCH VALUES (13,’NITTE’,’MANGALORE’);

INSERT INTO LIBRARY_BRANCH VALUES (14,’MANIPAL’,’UDUPI’);

Select * from LIBRARY_BRANCH;

BRANCH_ID BRANCH_NAME ADRESS


10 VIJAY NAGAR BANGALORE
11 GAT BANGALORE
12 RAJAJI NAGAR BANGALORE
13 NITTE MANGALORE
14 MANIPAL UDUPI

INSERT INTO BOOK_COPIES VALUES (10, 1, 10);


INSERT INTO BOOK_COPIES VALUES (5, 1, 11);
INSERT INTO BOOK_COPIES VALUES (2, 2, 12);
INSERT INTO BOOK_COPIES VALUES (5, 2, 13);
INSERT INTO BOOK_COPIES VALUES (7, 3, 14);
INSERT INTO BOOK_COPIES VALUES (1, 5, 10);
INSERT INTO BOOK_COPIES VALUES (3, 4, 11);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 42


Global Academy of Technology

Select * from BOOK_COPIES;

NO_OF_COPIES BOOK_ID BRANCH_ID


10 1 10
5 1 11

2 2 12
5 2 13
7 3 14
1 5 10
3 4 11
INSERT INTO CARD VALUES (101);

INSERT INTO CARD VALUES (102);

INSERT INTO CARD VALUES (103);

INSERT INTO CARD VALUES (104);

INSERT INTO CARD VALUES (105);

Select * from CARD;

CARDNO
101
102
103
104
105
INSERT INTO BOOK_LENDING VALUES (’01-JAN-17’,’01-JUN-17’, 1, 10, 101);

INSERT INTO BOOK_LENDING VALUES (’11-JAN-17’,’11-MAR-17’, 3, 14, 101);

INSERT INTO BOOK_LENDING VALUES (’21-FEB-17’,’21-APR-17’, 2, 13, 101);

INSERT INTO BOOK_LENDING VALUES (’15-MAR-17’,’15-JUL-17’, 4, 11, 101);

INSERT INTO BOOK_LENDING VALUES (‘12-APR-17’,’12-MAY-17’, 1, 11, 104);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 43


Global Academy of Technology

Select * from BOOK_LENDING;

BOOKID BRANCHID CARDNO DATEOUT DUEDATE

1 10 101 1-Jan-17 1-Jun-17

3 4 101 11-Jan-17 11-Mar-17

2 13 101 21-Feb-17 21-Apr-17

4 11 101 15-Mar-17 15-Jul-17

1 11 104 12-Apr-17 12-May-17

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 DBMS MCGRAW-HILL NAVATHE 10 10


1 DBMS MCGRAW-HILL NAVATHE 5 11
2 ADBMS MCGRAW-HILL NAVATHE 2 12
2 ADBMS MCGRAW-HILL NAVATHE 5 13
3 CD PEARSON ULLMAN 7 14
5 OS PEARSON GALVIN 1 10
4 ALGORITHMS MIT CHARLES 3 11

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;

BOOK_ID TITLE PUB_YEAR PUBLISHER_NAME


1 DBMS Jan-17 MCGRAW-HILL
2 ADBMS Jun-16 MCGRAW-HILL
4 ALGORITHMS Sep-15 MIT
5 OS May-16 PEARSON

3. Partition the BOOK table based on year of publication. Demonstrate its working
with a simple query.

CREATE VIEW V_PUBLICATION AS


SELECT PUB_YEAR
FROM BOOK;

PUB_YEAR
Jan-17
Jun-16
Sep-16
Sep-15
May-16

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 45


Global Academy of Technology

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

BOOK_ID TITLE NO_OF_COPIES


1 DBMS 10
1 DBMS 5
2 ADBMS 2
2 ADBMS 5
3 CN 7
5 OS 1
4 ALGORITHMS 3

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 46


Global Academy of Technology

B. Consider the following schema for Order Database:

SALESMAN (Salesman_id, Name, City, Commission)


CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
ORDERS (Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)

Write SQL queries to


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.

Schema Diagram

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 47


Global Academy of Technology

Table Creation

CREATE TABLE SALESMAN (SALESMAN_ID NUMBER (4) PRIMARY KEY,

NAME VARCHAR (20), CITY VARCHAR (20), COMMISSION VARCHAR (20));

DESC SALESMAN

Name Null? Type

SALESMAN_ID NOT NULL NUMBER(4)

NAME VARCHAR(20)

CITY VARCHAR(20)

COMMISSION NUMBER(3)

CREATE TABLE CUSTOMER1


(CUSTOMER_ID NUMBER (4) PRIMARY KEY,
CUST_NAME VARCHAR(20),
CITY VARCHAR (20),
GRADE NUMBER (3),
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE CASCADE);

DESC CUSTOMER1

Name Null? Type

CUSTOMER_ID NOT NULL NUMBER(4)

CUST_NAME VARCHAR(20)

CITY VARCHAR(20)

GRADE NUMBER(3)

SALESMAN_ID NUMBER(4)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 48


Global Academy of Technology

CREATE TABLE ORDERS (


ORD_NO NUMBER (5) PRIMARY KEY,
PURCHASE_AMT NUMBER (10, 2),
ORD_DATE DATE,
CUSTOMER_ID REFERENCES CUSTOMER1 (CUSTOMER_ID) ON DELETE CASCADE,
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE CASCADE);

DESC ORDERS

Name Null? Type

ORD_NO NOT NULL NUMBER(5)

PURCHASE_AMT NUMBER(10,2)

ORD_DATE DATE

CUSTOMER_ID NUMBER(4)

SALESMAN_ID NUMBER(4)

Insertion of Values to Tables

INSERT INTO SALESMAN VALUES(101,'RICHARD','LOS ANGELES','18%');


INSERT INTO SALESMAN VALUES(1000,''GEORGE','NEWYORK','32%');
INSERT INTO SALESMAN VALUES(110,'CHARLES','BANGALORE','54%');
INSERT INTO SALESMAN VALUES(122,'ROWLING','PHILADELPHIA','46%');
INSERT INTO SALESMAN VALUES(126,'KURT','CHICAGO','52%');
INSERT INTO SALESMAN VALUES(132,'EDWIN','PHOENIX','41%');

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 49


Global Academy of Technology

SELECT * FROM SALESMAN

SALESMAN_ID NAME CITY COMMISSION


101 RICHARD LOS ANGELES 18%
1000 GEORGE NEWYORK 32%
110 CHARLES BANGALORE 54%
122 ROWLING PHILADELPHIA 46%
126 KURT CHICAGO 52%
132 EDWIN PHO 41%

INSERT INTO CUSTOMER1 VALUES(501,'SMITH','LOS ANGELES',10,1000);


INSERT INTO CUSTOMER1 VALUES(510,'BROWN','ATLANTA',14,122);
INSERT INTO CUSTOMER1 VALUES(522,'LEWIS','BANGALORE',10,132);
INSERT INTO CUSTOMER1 VALUES(534,'PHILIPS','BOSTON',17,1000);
INSERT INTO CUSTOMER1 VALUES(543,'EDWARD','BANGALORE',14,110);
INSERT INTO CUSTOMER1 VALUES(550,'PARKER','ATLANTA',19,126);

SELECT * FROM CUSTOMER1

CUSTOMER_ID CUST_NAME CITY GRADE SALESMAN_ID


501 SMITH LOS ANGELES 10 1000
510 BROWN ATLANTA 14 122
522 LEWIS BANGALORE 10 132
534 PHILIPS BOSTON 17 1000
543 EDWARD BANGALORE 14 110
550 PARKER ATLANTA 19 126

INSERT INTO ORDERS VALUES(001,1000,'05-APR-08',501,1000);

INSERT INTO ORDERS VALUES(002,4000,'12-JUL-03',522,132);

INSERT INTO ORDERS VALUES(003,2500,'04-JUL-06',550,126);

INSERT INTO ORDERS VALUES(005,6000,'09-MAY-70',522,1000);

INSERT INTO ORDERS VALUES(006,7000,'30-AUG-98',550,126);

INSERT INTO ORDERS VALUES (007,3400,'20-FEB-17',501,122);


Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 50
Global Academy of Technology

SELECT * FROM ORDERS;

ORD_NO PURCHASE_AMT ORD_DATE CUSTOMER_ID SALESMAN_ID


001 1000 05-APR-08 501 1000
002 4000 12-JUL-03 522 132
003 2500 04-JUL-06 550 126
005 6000 09-MAY-70 522 1000
006 7000 30-AUG-98 550 126
007 3400 20-FEB-17 501 122

Queries:

1. Count the customers with grades above Bangalore’s average.

SELECT GRADE, COUNT (DISTINCT


CUSTOMER_ID) FROM CUSTOMER1
GROUP BY GRADE
HAVING GRADE > (SELECT AVG(GRADE)
FROM CUSTOMER1
WHERE CITY='BANGALORE');

GRADE COUNT(DISTINCT CUSTOMER_ID)


14 2
17 1
19 1

2. Find the name and numbers of all salesmen who had more than one customer.

SELECT SALESMAN_ID, NAME


FROM SALESMAN A
WHERE 1 < (SELECT COUNT (*) FROM CUSTOMER1
WHERE SALESMAN_ID=A.SALESMAN_ID);

SALESMAN_ID NAME
------------------- -----------
1000 GEORGE

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 51


Global Academy of Technology

3. List all salesmen and indicate those who have and don’t have customers in their
cities (Use UNION operation.)

SELECT SALESMAN.SALESMAN_ID, NAME, CUST_NAME,


COMMISSION FROM SALESMAN, CUSTOMER1
WHERE SALESMAN.CITY = CUSTOMER1.CITY UNION
SELECT SALESMAN_ID, NAME, 'NO MATCH',
COMMISSION FROM SALESMAN
WHERE NOT CITY = ANY (SELECT CITY
FROM CUSTOMER1) ORDER BY 2 DESC;

SALESMAN_ID NAME CUST_NAME COMMISSION


122 ROWLING NOMATCH 46%
101 RICHARD SMITH 18%
126 KURT NOMATCH 52%
1000 GEORGE NOMATCH 32%
132 EDWIN NOMATCH 41%
110 CHARLES EDWARD 54%
110 CHARLES LEWIS 54%

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

SELECT * FROM ELITSALESMAN;

ORD_DATE SALESMAN_ID NAME


05-APR-08 1000 GEORGE
12-JUL-03 132 EDWIN
04-JUL-06 126 KURT
09-MAY-70 1000 GEORGE
30-AUG-98 126 KURT
20-FEB-17 122 ROWLING

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 52


Global Academy of Technology

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:

DELETE FROM SALESMAN WHERE SALESMAN_ID=1000;

SALESMAN_ID NAME CITY COMMISSION


------------------- -------- ------- -------------------
101 RICHARD LOS ANGELES 18%
110 CHARLES BANGALORE 54%
122 ROWLING PHILADELPHIA 46%
126 KURT CHICAGO 52%
132 EDWIN PHOENIX 41%

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 53


Global Academy of Technology

C) Consider the schema for Movie Database:


ACTOR (Act_id, Act_Name, Act_Gender)
DIRECTOR (Dir_id, Dir_Name, Dir_Phone)
MOVIES (Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)
MOVIE_CAST (Act_id,Mov_id, Role)
RATING (Mov_id, Rev_Stars)

Write SQL queries to


1. List the titles of all movies directed by ‘Hitchcock’.
2. Find the movie names where one or more actors acted in two or more movies.

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 54


Global Academy of Technology

Table Creation

CREATE TABLE ACTOR (

ACT_ID NUMBER (3),

ACT_NAME VARCHAR (20),

ACT_GENDER CHAR (1),

PRIMARY KEY (ACT_ID));

DESC ACTOR

Name Null? Type


ACT_ID NOT NULL NUMBER(3)
ACT_NAME VARCHAR(20)
ACT_GENDER CHAR(1)

CREATE TABLE DIRECTOR (

DIR_ID NUMBER (3),

DIR_NAME VARCHAR (20),

DIR_PHONE NUMBER (10),

PRIMARY KEY (DIR_ID));

DESC DIRECTOR

Name Null? Type


DIR_ID NOT NULL NUMBER(3)
DIR_NAME VARCHAR(20)
DIR_PHONE NUMBER(10)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 55


Global Academy of Technology

CREATE TABLE MOVIES (

MOV_ID NUMBER (4) PRIMARY KEY,

MOV_TITLE VARCHAR (25),

MOV_YEAR NUMBER (4),

MOV_LANG VARCHAR (12),

DIR_ID NUMBER (3),

FOREIGN KEY (DIR_ID) REFERENCES DIRECTOR (DIR_ID));

DESC MOVIES

Name Null? Type


MOV_ID NOT NULL NUMBER(4)
MOV_TITLE VARCHAR(25)
MOV_YEAR NUMBER(4)
MOV_LANG VARCHAR(12)
DIR_ID NUMBER(3)

CREATE TABLE MOVIE_CAST (


ACT_ID REFERENCES ACTOR (ACT_ID),
MOV_ID REFERENCES MOVIES (MOV_ID),
ROLE VARCHAR (10),
PRIMARY KEY (ACT_ID, MOV_ID));

DESC MOVIE_CAST

Name Null? Type


ACT_ID NOT NULL NUMBER(3)
MOV_ID NOT NULL NUMBER(4)
ROLE VARCHAR(10)

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 56


Global Academy of Technology

CREATE TABLE RATING (

MOV_ID NUMBER (4),

REV_STARS VARCHAR (25),

FOREIGN KEY (MOV_ID) REFERENCES MOVIES (MOV_ID));

DESC RATING

Name Null? Type


MOV_ID NUMBER(4)
REV_STARS VARCHAR(25)

Insertion of Values to Tables

INSERT INTO ACTOR VALUES (001,’MADHURI DIXIT’,’F’);

INSERT INTO ACTOR VALUES (002,’AAMIR KHAN’,’M’);

INSERT INTO ACTOR VALUES (003,’JUHI CHAWLA’,’F’);

INSERT INTO ACTOR VALUES (004,’SRIDEVI’,’F’);

SELECT * FROM ACTOR

ACT_ID ACT_NAME ACT

4 SRIDEVI F

1 MADHURI DIXIT F

2 AAMIR KHAN M

3 JUHI CHAWLA F

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 57


Global Academy of Technology

INSERT INTO DIRECTOR VALUES (100,’SUBHASH KAPOOR’, 56340015);


INSERT INTO DIRECTOR VALUES(102,'ALAN TAYLOR',719600310);
INSERT INTO DIRECTOR VALUES (103,’SANTHOSH ANANDDRAM’, 99346111);
INSERT INTO DIRECTOR VALUES (104,’IMTIAZ ALI’, 85399209);
INSERT INTO DIRECTOR VALUES (105,'HITCHCOCK',7766138911);
INSERT INTO DIRECTOR VALUES (106,'STEVEN SPIELBERG',9966138934);

SELECT * FROM DIRECTOR

DIR_ID DIR_NAME DIR_PHONE

100 SUBHASH KAPOOR 56340015

102 ALAN TAYLOR 719600310

103 SANTHOSH ANANDDRAM 99346111

104 IMTIAZ ALI 85399209

105 HITCHCOCK 7766138911

106 STEVEN SPIELBERG 9966138934

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 58


Global Academy of Technology

SELECT * FROM MOVIES

MOV_ID MOV_TITLE MOV_YEAR MOV_LANG DIR_ID

501 JAB HARRY MET SEJAL 2017 HINDI 104

502 RAJAKUMARA 2017 KANNADA 103

503 JOLLY LLB 2 2013 HINDI 100

504 TERMINATOR GENESYS 2015 ENGLISH 102

505 JAWS 1975 ENGLISH 106

506 BRIDGE OF SPIES 2015 ENGLISH 106

507 VERTIGO 1958 ENGLISH 105

508 SHADOW OF A DOUBT 1943 ENGLISH 105

INSERT INTO MOVIE_CAST VALUES (001, 501, ‘HEROINE’);

INSERT INTO MOVIE_CAST VALUES (001, 502, ‘HEROINE’);

INSERT INTO MOVIE_CAST VALUES (003, 503, ‘COMEDIAN’);

INSERT INTO MOVIE_CAST VALUES (004, 504, ‘GUEST’);

INSERT INTO MOVIE_CAST VALUES (004, 501, ‘HERO’);

SELECT * FROM MOVIE_CAST

ACT_ID MOV_ID ROLE

1 501 HEROINE

1 502 HEROINE

3 503 COMEDIAN

4 504 GUEST

4 501 HERO

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 59


Global Academy of Technology

INSERT INTO RATING VALUES (501, 4);


INSERT INTO RATING VALUES (502, 2);
INSERT INTO RATING VALUES (503, 5);
INSERT INTO RATING VALUES (504, 4);
INSERT INTO RATING VALUES (505, 3);
INSERT INTO RATING VALUES (506, 2);

SELECT * FROM RATING

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 60


Global Academy of Technology

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

SELECT ACT_NAME, MOV_TITLE, MOV_YEAR


FROM ACTOR A
JOIN MOVIE_CAST C
ON A.ACT_ID=C.ACT_ID
JOIN MOVIES M
ON C.MOV_ID=M.MOV_ID
WHERE M.MOV_YEAR NOT BETWEEN 2000 AND 2015;

OR

SELECT A.ACT_NAME, A.ACT_NAME, C.MOV_TITLE, C.MOV_YEAR FROM


ACTOR A, MOVIE_CAST B, MOVIES C
WHERE A.ACT_ID=B.ACT_IDAND B.MOV_ID=C.MOV_ID
AND C.MOV_YEAR NOT BETWEEN 2000 AND 2015;

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 61


Global Academy of Technology

ACT_NAME MOV_TITLE MOV_YEAR


-----------------------------------------------------------------------------------------------------------
MADHURI DIXIT JAB HARRY MET SEGAL 2017
SRIDEVI JAB HARRY MET SEGAL 2017
MADHURI DIXIT RAJAKUMARA 2017

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.

SELECT MOV_TITLE, MAX (REV_STARS)


FROM MOVIES
INNER JOIN RATING USING (MOV_ID)
GROUP BY MOV_TITLE
HAVING MAX (REV_STARS)>0
ORDER BY MOV_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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 62


Global Academy of Technology

5. Update rating of all movies directed by ‘Steven Spielberg’ to 5

UPDATE RATING
SET REV_STARS=5
WHERE MOV_ID IN (SELECT MOV_ID FROM MOVIES WHERE DIR_ID IN

(SELECT DIR_IDFROM DIRECTOR

WHERE DIR_NAME='STEVEN SPIELBERG'));

2 ROWS UPDATED

SELECT * FROM RATING

MOV_ID REV_STARS

501 4

502 2

503 5

504 4

505 5

506 5

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 63


Global Academy of Technology

D. Consider the schema for College Database:


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 ‘1GA15CS101’ in all subjects.

4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.

5. Categorize students based on the following criterion:

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 64


Global Academy of Technology

Schema Diagram

Table Creation

CREATE TABLE STUDENT (


USN VARCHAR (10) PRIMARY KEY,
SNAME VARCHAR (25),
ADDRESS VARCHAR (25),
PHONE NUMBER (10),
GENDER CHAR (1));

CREATE TABLE SEMSEC (


SSID VARCHAR (5) PRIMARY KEY,
SEM NUMBER (2),
SEC CHAR (1));

CREATE TABLE CLASS (


USN VARCHAR (10),
SSID VARCHAR (5),
PRIMARY KEY (USN, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGNKEY (SSID) REFERENCES SEMSEC (SSID));
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 65
Global Academy of Technology

CREATE TABLE SUBJECT (


SUBCODE VARCHAR (8),
TITLE VARCHAR (20),
SEM NUMBER (2),
CREDITS NUMBER (2),
PRIMARY KEY (SUBCODE));

CREATE TABLE IAMARKS(


USN VARCHAR (10),
SUBCODE VARCHAR (8),
SSID VARCHAR (5),
TEST1 NUMBER (2),
TEST2 NUMBER (2),
TEST3 NUMBER (2),
FINALIA NUMBER (2),
PRIMARY KEY (USN, SUBCODE, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGN KEY (SUBCODE) REFERENCES SUBJECT (SUBCODE),
FOREIGN KEY (SSID) REFERENCES SEMSEC (SSID));
Insertion of values to tables

INSERTINTO STUDENT VALUES ('1GA15CS062','SANDHYA','BENGALURU',


890201324564,'F');

INSERT INTO STUDENT VALUES


('1GA15CS092','TEESHA','BENGALURU', 7712312359,'F');

INSERT INTO STUDENT VALUES


('1GA15CS066','SUPRIYA','MANGALURU', 99020132418,'F');
INSERT INTO STUDENTVALUES
('11GA17CS010','ABHAY','BENGALURU', 8900211201,'M');

INSERT INTO STUDENT VALUES


('1GA17CS032','BHASKAR','BENGALURU', 7223211099,'M');

INSERT INTO STUDENT VALUES ('1GA17CS011','AJAY','TUMKUR', 890201324278,'M');

INSERT INTO STUDENT VALUES


('1GA15CS029','CHITRA','DAVANGERE', 7696772121,'F');

INSERT INTO STUDENT VALUES ('1GA15CS045','JEEVA','BELLARY',


9944850121,'M');

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 66


Global Academy of Technology

INSERT INTO STUDENT VALUES


('1GA14CS045','ISMAIL','KALBURGI', 9900232201,'M');

INSERT INTO STUDENT VALUES


('1GA14CS088','SAMEERA','SHIMOGA', 9905542212,'F');

INSERT INTO STUDENT VALUES


('1GA14CS122','VINAYAKA','CHIKAMAGALUR', 8800880011,'M');

INSERT INTO SEMSEC VALUES ('CSE8A', 8,'A');


INSERT INTO SEMSEC VALUES (‘CSE8B’, 8,'B');
INSERT INTO SEMSEC VALUES ('CSE7A', 7,’A’);
INSERT INTO SEMSEC VALUES (‘CSE7B’, 7,’B’);
INSERT INTO SEMSEC VALUES ('CSE7C', 7,'C');
INSERT INTO SEMSEC VALUES (‘CSE6A’, 6,’A’);
INSERT INTO SEMSEC VALUES (‘CSE6B’, 6,’B’);
INSERT INTO SEMSEC VALUES (‘CSE6C’, 6,’C’);
INSERT INTO SEMSEC VALUES (‘CSE5A’, 5,'A’);
INSERT INTO SEMSEC VALUES ('CSE5B', 5,'B');
INSERT INTO SEMSEC VALUES (‘CSE5C', 5,'C');
INSERT INTO SEMSEC VALUES (‘CSE4A’, 4,’A’);
INSERT INTO SEMSEC VALUES ('CSE4B', 4,’B’);
INSERT INTO SEMSEC VALUES (‘CSE4C’, 4,'C’);
INSERT INTO SEMSEC VALUES ('CSE3A', 3,'A');
INSERT INTO SEMSEC VALUES (‘CSE3B', 3,'B');
INSERT INTO SEMSEC VALUES (‘CSE3C’, 3,’C’);
INSERT INTO SEMSEC VALUES ('CSE2A', 2,’A’);
INSERT INTO SEMSEC VALUES (‘CSE2B’, 2,'B’);
INSERT INTO SEMSEC VALUES ('CSE2C', 2,'C');
INSERT INTO SEMSEC VALUES (‘CSE1A', 1,'A');
INSERT INTO SEMSEC VALUES (‘CSE1B’, 1,’B’);
INSERT INTO SEMSEC VALUES ('CSE1C', 1,’C’);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 67


Global Academy of Technology

INSERT INTO CLASS VALUES (‘1GA13CS020’,’CSE8A’);


INSERT INTO CLASS VALUES (‘1GA13CS062’,’CSE8A’);
INSERT INTO CLASS VALUES (‘1GA13CS066’,’CSE8B’);
INSERT INTO CLASS VALUES (‘1GA13CS091’,’CSE8C’);
INSERT INTO CLASS VALUES (‘1GA14CS010’,’CSE7A’);
INSERT INTO CLASS VALUES (‘1GA14CS025’,’CSE7A’);
INSERT INTO CLASS VALUES (‘1GA14CS032’,’CSE7A’);
INSERT INTO CLASS VALUES (‘1GA15CS011’,’CSE4A’);
INSERT INTO CLASS VALUES (‘1GA15CS029’,’CSE4A’);
INSERT INTO CLASS VALUES (‘1GA15CS045’,’CSE4B’);
INSERT INTO CLASS VALUES (‘1GA15CS091’,’CSE4C’);
INSERT INTO CLASS VALUES (‘1GA14CS045’,’CSE3A’);
INSERT INTO CLASS VALUES (‘1GA14CS088’,’CSE3B’);
INSERT INTO CLASS VALUES (‘1GA14CS122’,’CSE3C’);

INSERT INTO SUBJECT VALUES ('10CS81','ACA', 8, 4);


INSERT INTO SUBJECT VALUES ('10CS82','SSM', 8, 4);
INSERT INTO SUBJECT VALUES ('10CS83','NM', 8, 4);
INSERT INTO SUBJECT VALUES ('10CS84','CC', 8, 4);
INSERT INTO SUBJECT VALUES ('10CS85','PW', 8, 4);
INSERT INTO SUBJECT VALUES ('10CS71','OOAD', 7, 4);
INSERT INTO SUBJECT VALUES ('10CS72','ECS', 7, 4);
INSERT INTO SUBJECT VALUES ('10CS73','PTW', 7, 4);
INSERT INTO SUBJECT VALUES ('10CS74','DWDM', 7, 4);
INSERT INTO SUBJECT VALUES (‘10CS75','JAVA', 7, 4);
INSERT INTO SUBJECT VALUES ('10CS76','SAN', 7, 4);
INSERT INTO SUBJECT VALUES ('15CS51', 'ME', 5, 4);
INSERT INTO SUBJECT VALUES ('15CS52','CN', 5, 4);
INSERT INTO SUBJECT VALUES ('15CS53','DBMS', 5, 4);
INSERT INTO SUBJECT VALUES ('15CS54','ATC', 5, 4);
INSERT INTO SUBJECT VALUES ('15CS55','JAVA', 5, 3);
INSERT INTO SUBJECT VALUES ('15CS56','AI', 5, 3);
Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 68
Global Academy of Technology

INSERT INTO SUBJECT VALUES ('15CS41','M4', 4, 4);


INSERT INTO SUBJECT VALUES ('15CS42','SE', 4, 4);
INSERT INTO SUBJECT VALUES ('15CS43','DAA', 4, 4);
INSERT INTO SUBJECT VALUES ('15CS44','MPMC', 4, 4);
INSERT INTO SUBJECT VALUES ('15CS45','OOC', 4, 3);
INSERT INTO SUBJECT VALUES ('15CS46','DC', 4, 3);
INSERT INTO SUBJECT VALUES ('15CS31','M3', 3, 4);
INSERT INTO SUBJECT VALUES ('15CS32','ADE', 3, 4);
INSERT INTO SUBJECT VALUES ('15CS33','DSA', 3, 4);
INSERT INTO SUBJECT VALUES ('15CS34','CO', 3, 4);
INSERT INTO SUBJECT VALUES ('15CS35','USP', 3, 3);
INSERT INTO SUBJECT VALUES ('15CS36','DMS', 3, 3);

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

SELECT * FROM STUDENT;

USN SNAME ADDRESS PHONE GENDER


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

1GA15CS062 SANDHYA BENGALURU 890201324564 F

1GA15CS091 THEESHA BENGALURU 7712312359 F

1GA15CS066 SUPRIYA MANGALURU 99020132418 F

1GA17CS032 BHASKAR BENGALURU 7712311099 M

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 69


Global Academy of Technology

1GA17CS010 ABHAY BENGALURU 8900211201 M

1GA15CS029 CHITRA DAVANGERE 7696772121 F

1GA15CS045 JEEVA BELLARY 9944850121 M

1GA14CS045 ISMAIL BENGALURU 9900232201 M

1GA14CS088 SAMEERA SHIMOGA 9905542212 F

1GA14CS122 VINAYAKA CHIKKAMAGALUR 8800880011 M

1GA17CS011 AJAY TUMKUR 890201324278 M

SELECT * FROM SEMSEC;

SSID SEM SEC


CSE8A 8 A
CSE7C 7 C
CSE8B 8 B
CSE7A 7 A
CSE7B 7 B
CSE6A 6 A
CSE6B 6 B
CSE6C 6 C
CSE5B 5 B
CSE5A 5 A
CSE5C 5 C
CSE4A 4 A
CSE4B 4 B
CSE4C 4 C
CSE3A 3 A
CSE3B 3 B
CSE3C 3 C
CSE2A 2 A
CSE2B 2 B
CSE2C 2 C
CSE1A 1 A
CSE1B 1 B
CSE1C 1 C

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 70


Global Academy of Technology

SELECT * FROM CLASS;

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

SELECT * FROM SUBJECT;

SUBCODE TITLE SEM CREDITS


10CS81 ACA 8 4
10CS82 SSM 8 4
10CS83 NM 8 4
10CS84 CC 8 4
10CS85 PW 8 4
10CS71 OOAD 7 4
10CS72 ECS 7 4
10CS73 PTW 7 4
10CS74 DWDM 7 4
10CS75 JAVA 7 4
10CS76 SAN 7 4
15CS51 ME 5 4
15CS52 CN 5 4
15CS53 DBMS 5 4
15CS54 ATC 5 4
15CS55 JAVA 5 3
15CS56 AI 5 3
15CS41 M4 4 4
15CS42 SE 4 4
15CS43 DAA 4 4
15CS44 MPMC 4 4
15CS45 OOC 4 3
15CS46 DC 4 3
15CS31 M3 3 4

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 71


Global Academy of Technology

15CS32 ADE 3 4
15CS33 DSA 3 4
15CS34 CO 3 4

SELECT * FROM IAMARKS;

USN SUBCODE SSID TEST1 TEST2 TEST3

1GA13CS091 10CS81 CSE8C 15 16 18


1GA13CS091 10CS82 CSE8C 12 19 14
1GA13CS091 10CS83 CSE8C 19 15 20
1GA13CS091 10CS84 CSE8C 20 16 19
1GA13CS091 10CS81 CSE8C 15 15 12
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
ANDSS.SEC=’C’;

USN NAME ADDRESS PHONE GENDER SEM SEC

1GA15CS091 THEESA BENGALURU 7712312359 F 4 C

2. Compute the total number of male and female students in each semester and in each
section.

SELECT SS.SEM, SS.SEC, S.GENDER, COUNT (S.GENDER) AS


COUNT FROM STUDENT S, SEMSEC SS, CLASS C
WHERES.USN = C.USN
AND SS.SSID = C.SSID
GROUP BY SS.SEM, SS.SEC,
S.GENDER ORDER BY SEM;

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 72


Global Academy of Technology

SEM SEC GENDER COUNT


-----------------------------------------------------
3 A M 1
3 B F 1
3 C M 1
4 B M 1
4 C F 1

3. Create a view of Test1 marks of student USN ‘1GA15CS091’ in all subjects.

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.

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 73


Global Academy of Technology

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:

SELECT * FROM IAMARKS;

USN SUBCODE SSID TEST1 TEST2 TEST3


-------------------------------------------------------------------------------------------------------------
1GA13CS091 10CS81 CSE8C 15 16 18

1GA13CS091 10CS82 CSE8C 12 19 14

1GA13CS091 10CS83 CSE8C 19 15 20

1GA13CS091 10CS84 CSE8C 20 16 19

1GA13CS091 10CS85 CSE8C 15 15 12

Below SQL code is to invoke the PL/SQL stored procedure from the command line:

BEGIN
AVGMARKS;
END;

SELECT * FROM IAMARKS;

USN SUBCODE SSID TEST1 TEST2 TEST3 FINALIA


-----------------------------------------------------------------------------------------------------------
1GA13CS091 10CS81 CSE8C 15 16 18 17

1GA13CS091 10CS82 CSE8C 12 19 14 17

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 74


Global Academy of Technology

1GA13CS091 10CS83 CSE8C 19 15 20 20

1GA13CS091 10CS84 CSE8C 20 16 19 20

1GA13CS091 10CS85 CSE8C 15 15 12 15

5. Categorize students based on the following criterion:

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.

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;

USN SNAME ADDRESS PHONE G CAT


---------------------------------------------------------------------------------------------------------------
IGA13CS091 TEESHA BENGALURU 7712312359 F OutStanding

IGA13CS091 TEESHA BENGALURU 7712312359 F OutStanding

IGA13CS091 TEESHA BENGALURU 7712312359 F OutStanding

IGA13CS091 TEESHA BENGALURU 7712312359 F OutStanding

IGA13CS091 TEESHA BENGALURU 7712312359 F Average

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 75


Global Academy of Technology

E. Consider the schema for Company Database:


EMPLOYEE (SSN, Name, Address, Sex, Salary, SuperSSN, DNo)

DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate)

DLOCATION (DNo,DLoc)

PROJECT (PNo, PName, PLocation, DNo)

WORKS_ON (SSN, PNo, Hours)

Write SQL queries to

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 76


Global Academy of Technology

Schema Diagram

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 77


Global Academy of Technology

Table Creation

CREATE TABLE DEPARTMENT


(DNO VARCHAR2 (20) PRIMARY KEY,
DNAME VARCHAR2 (20),
MGRSTARTDATE DATE);

CREATE TABLE EMPLOYEE


(SSN VARCHAR2 (20) PRIMARY KEY,
FNAME VARCHAR2 (20),
LNAME VARCHAR2 (20), ADDRESS
VARCHAR2 (20),
SEX CHAR (1),
SALARY INTEGER,
SUPERSSN REFERENCES EMPLOYEE (SSN), DNO REFERENCES DEPARTMENT (DNO));

NOTE:Once DEPARTMENT and EMPLOYEE tables are created we must alter


Departmenttable to add foreign constraint MGRSSN using sql command.

ALTER TABLE DEPARTMENT


ADD MGRSSN REFERENCES EMPLOYEE (SSN);

CREATE TABLE DLOCATION


(DLOC VARCHAR2 (20),
DNO REFERENCES DEPARTMENT (DNO),
PRIMARY KEY (DNO, DLOC));

CREATE TABLE PROJECT


(PNO INTEGER PRIMARY KEY,
PNAME VARCHAR2 (20),
PLOCATION VARCHAR2 (20),
DNO REFERENCES DEPARTMENT (DNO));

CREATE TABLE WORKS_ON


(HOURS NUMBER (2),
SSN REFERENCES EMPLOYEE (SSN),
PNO REFERENCES PROJECT(PNO),
PRIMARY KEY (SSN, PNO));

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 78


Global Academy of Technology

Insertion of values to tables

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

INSERT INTO DEPARTMENT VALUES (‘1’,’ACCOUNTS’,’01-JAN-1’,’GATACC02’);


INSERT INTO DEPARTMENT VALUES (‘2’,’IT’,’01-AUG-16’,’GATIT01’);
INSERT INTO DEPARTMENT VALUES (‘3’,’ECE’,’01-JUN-08’,’GATECE01’);
INSERT INTO DEPARTMENT VALUES (‘4’,’ISE’,’01-AUG-15’,’GATISE01’);
INSERT INTO DEPARTMENT VALUES (‘5’,’CSE’,’01-JUN-02’,’GATCSE05’);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 79


Global Academy of Technology

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 80


Global Academy of Technology

INSERT INTO DLOCATION VALUES (’BANGALORE’, ‘1’);


INSERT INTO DLOCATION VALUES (’BANGALORE’, ‘2’);
INSERT INTO DLOCATION VALUES (’BANGALORE’, ‘3’);
INSERT INTO DLOCATION VALUES (’MANGALORE’, ‘4’);
INSERT INTO DLOCATION VALUES (’MANGALORE’, ‘5’);

INSERT INTO PROJECT VALUES (100,’IOT’,’BANGALORE’,’5’);


INSERT INTO PROJECT VALUES (101,’CLOUD’,’BANGALORE’,’5’);
INSERT INTO PROJECT VALUES (102,’BIGDATA’,’BANGALORE’,’5’);
INSERT INTO PROJECT VALUES (103,’SENSORS’,’BANGALORE’,’3’);
INSERT INTO PROJECT VALUES (104,’BANK MANAGEMENT’,’BANGALORE’,’1’);
INSERT INTO PROJECT VALUES (105,’SALARY MANAGEMENT’,’BANGALORE’,’1’);
INSERT INTO PROJECT VALUES (106,’OPENSTACK’,’BANGALORE’,’4’);
INSERT INTO PROJECT VALUES (107,’SMART CITY’,’BANGALORE’,’2’);

INSERT INTO WORKS_ON VALUES (4, ‘GATCSE01’, 100);


INSERT INTO WORKS_ON VALUES (6, ‘GATCSE01’, 101);
INSERT INTO WORKS_ON VALUES (8, ‘GATCSE01’, 102);
INSERT INTO WORKS_ON VALUES (10, ‘GATCSE02’, 100);
INSERT INTO WORKS_ON VALUES (3, ‘GATCSE04’, 100);
INSERT INTO WORKS_ON VALUES (4, ‘GATCSE05’, 101);
INSERT INTO WORKS_ON VALUES (5, ‘GATCSE06’, 102);
INSERT INTO WORKS_ON VALUES (6, ‘GATCSE03’, 102);
INSERT INTO WORKS_ON VALUES (7, ‘GATECE01’, 103);
INSERT INTO WORKS_ON VALUES (5, ‘GATACC01’, 104);
INSERT INTO WORKS_ON VALUES (6, ‘GATACC02’, 105);
INSERT INTO WORKS_ON VALUES (4, ‘GATISE01’, 106);
INSERT INTO WORKS_ON VALUES (10, ‘GATIT01’, 107);

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 81


Global Academy of Technology

SELECT * FROM EMPLOYEE;

SSN FNAME LNAME ADDRESS SEX SALARY SUPERSSN DNO


--------------------------------------------------------------------------------------------------------------------
GATECE01 MOHAN KUMAR BENGALURU M 450000 3
GATCSE01 JAGAN RAO BENGALURU M 500000 GATCSE02 5
GATCSE02 HEMANTH BHATT BENGALURU M 700000 GATCSE03 5
GATCSE03 ESHWAR KUMAR MYSORE M 500000 GATCSE04 5
GATCSE04 PAVAN HEGADE MANGALORE M 650000 GATCSE05 5
GATCSE05 GIRISH MALYA MYSORE M 450000 GATCSE06 5
GATCSE06 NEHA SN BENGALURU F 800000 5
GATACC01 AHANA K MANGALORE M 300000 1
GATACC02 SANTOSH KUMAR MANGALORE M 300000 1
GATISE01 VEENA M BENGALURU M 600000 4
GATIT01 NAGESH HR BENGALURU M 500000 2

SELECT * FROM DEPARTMENT;

DNO DNAME MGRSTARTDATE MGRSSN


---------------------------------------------------------------------
1 ACCOUNTS 01-JAN-01 GATACC02
3 ECE 01-JUN-08 GATECE01
4 ISE 01-AUG-15 GATISE01
5 CSE 01-JUN-02 GATCSE05

SELECT * FROM DLOCATION;


DLOC DNO
---------------------------------------
BANGALORE 1
BANGALORE 2
BANGALORE 3
MANGALORE 4
MANGALORE 4
SELECT * FROM PROJECT;

PNO PNAME PLOCATION DNO


-----------------------------------------------------------------------------------
100 IOT BANGALORE 5
101 CLOUD BANGALORE 5
102 BIGDATA BANGALORE 5
103 SENSORS BANGALORE 3
104 BANK MANAGEMENT BANGALORE 1
105 SALARY MANAGEMENT BANGALORE 1
106 OPEMSTACK BANGALORE 4
107 SMART CITY BANGALORE 2

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 82


Global Academy of Technology

SELECT * FROM WORKS_ON;

HOURS SSN PNO


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

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.

(SELECT DISTINCT P.PNO


FROM PROJECT P, DEPARTMENT D, EMPLOYEE E WHERE E.DNO=D.DNO
AND D.MGRSSN=E.SSN
AND E.LNAME=’KUMAR’)
UNION
(SELECT DISTINCT P1.PNO
FROM PROJECT P1, WORKS_ON W, EMPLOYEE E1
WHERE P1.PNO=W.PNO AND E1.SSN=W.SSN
AND E1.LNAME=’KUMAR’);

PNO
------------------------------------------------------------------------------------------
100
101
102
103
104
105
106
107

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 83


Global Academy of Technology

2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a
10 percent raise.

SELECT E.FNAME, E.LNAME, 1.1*E.SALARY AS INCR_SAL


FROM EMPLOYEE E, WORKS_ON W, PROJECT P
WHERE E.SSN=W.SSN
AND W.PNO=P.PNO
AND P.PNAME=’IOT’;

FNAME LANME INCR_SAL


-------------------------------------------------------------------------------
JAGAN RAO 550000
HEMANTH BHATT 770000
PAVAN HEGADE 715000

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

SELECT SUM (E.SALARY), MAX (E.SALARY), MIN (E.SALARY), AVG


(E.SALARY)
FROM EMPLOYEE E, DEPARTMENT D
WHERE E.DNO=D.DNO
AND D.DNAME=’ACCOUNTS’;

SUM MAX MIN AVG


---------------------------------------------------------------
65000 35000 30000 325000

4. Retrieve the name of each employee who works on all the projects Controlled by
department number 5 (use NOT EXISTS operator).

SELECT E.FNAME, E.LNAME


FROM EMPLOYEE E
WHERE NOT EXISTS((SELECT PNO
FROM PROJECT
WHERE DNO=’5’)
MINUS (SELECT PNO
FROM WORKS_ONWHERE E.SSN=SSN));

FNAME LNAME
------------------------------------
JGAN RAO

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 84


Global Academy of Technology

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.

SELECT D.DNO, COUNT (*)


FROM DEPARTMENT D, EMPLOYEE E
WHERE D.DNO=E.DNO
AND E.SALARY>600000
AND D.DNO IN (SELECT E1.DNO
FROM EMPLOYEE E1
GROUP BY E1.DNO
HAVING COUNT (*)>5)
GROUP BY D.DNO;

DNO COUNT(*)
---------------------------------------
5 3

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 85


Global Academy of Technology

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.

4. What is a Database system?


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

5. Advantages of DBMS?

o Redundancy is controlled.

o Unauthorized access is restricted.


o Providing multiple user interfaces.
o Enforcing integrity constraints.
o Providing backup and recovery.

6. Disadvantage in File Processing System?


o Data redundancy & inconsistency.
o Difficult in accessing data.
o Data isolation.
o Data integrity.
o Concurrent access is not possible.

o Security Problems.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 86


Global Academy of Technology

7.Describe the three levels of data abstraction?


There are three levels of abstraction:
 Physical level: The lowest level of abstraction describes how data are stored.

 Logical level:The next higher level of abstraction, describes what data are stored in database and

what relationship among those data.


 View level:The highest level of abstraction describes only part of entire database.

8. Define the "integrity rules"


There are two Integrity rules.
o Entity Integrity:States that “Primary key cannot have NULL value”

o Referential Integrity:States that “Foreign Key can be either a NULL value or should be
Primary Key value of other relation.

9.What is extension and intension?


Extension - It is the number of tuples present in a table at any instance. This is time dependent.
Intension -It is a constant value that gives the name, structure of table and the constraints laid on
it.

10. What is Data Independence?


Data independence means that “the application is independent of the storage structure and access
strategy of data”. In other words, The ability to modify the schema definition in one level should
not affect the schema definition in the next higher level.

Two types of Data Independence:

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.

NOTE: Logical Data Independence is more difficult to achieve

11. What is a view? How it is related to data independence?


A view may be thought of as a virtual table, that is, a table that does not really exist in its own
right but is instead derived from one or more underlying base table. In other words, there is no
stored file that direct represents the view instead a definition of view is stored in data dictionary.

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 87


Global Academy of Technology

12. What is Data Model?


A collection of conceptual tools for describing data, data relationships data semantics and
constraints.

13. What is E-R model?


This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.

14. What is Object Oriented model?


This model is based on collection of objects. An object contains values stored in instance
variables within the object. An object also contains bodies of code that operate on the object.
These bodies of code are called methods. Objects that contain same types of values and the same
methods are grouped together into classes.

15. What is an Entity?


It is an 'object' in the real world with an independent existence.

16. What is an Entity type?


It is a collection (set) of entities that have same attributes.

17. What is an Entity set?


It is a collection of all entities of particular entity type in the database.

18. What is an Extension of entity type?


The collections of entities of a particular entity type are grouped together into an entityset.
19. What is an attribute?
It is a particular property, which describes the entity.
20. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation
R and the list of attributes Ai that it contains. A relation is defined as
be the relation which contains set tuples (t1, t2, t3, ...,tn). Each tuple
values t=(v1,v2, ..., vn).
21. What is degree of a Relation?
It is the number of attribute of its relation schema.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 88


Global Academy of Technology

22. What is Relationship?


It is an association among two or more entities.
23. What is Relationship set?
The collection (or set) of similar relationships.
24. What is Relationship type?
Relationship type defines a set of associations or a relationship set among a given set of entity
types.
25. What is degree of Relationship type?
It is the number of entity type participating.
26. What is DDL (Data Definition Language)?
A data base schema is specified by a set of definitions expressed by a special language called
DDL.

27. What is VDL (View Definition Language)?


It specifies user views and their mappings to the conceptual schema.
28. What is SDL (Storage Definition Language)?
This language is to specify the internal schema. This language may specify the mapping between
two schemas.
29. What is Data Storage - Definition Language?
The storage structures and access methods used by database system are specified by aset of
definition in a special type of DDL called data storage-definition language.

30. What is DML (Data Manipulation Language)?


This language that enable user to access or manipulate data as organized by appropriate
Datamodel.Procedural DML or Low level: DML requires a user to specify what data are
needed and how to get those data. Non-Procedural DML or High level: DML requires a
user to specify what data are needed without specifying how to get those data.
31. What is DML Compiler?
It translates DML statements in a query language into low-level instruction that the query
evaluation engine can understand.
32. What is Relational Algebra?
It is a procedural query language. It consists of a set of operations that take one or two relations
asinput and produce a new relation.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 89


Global Academy of Technology

33. What is Relational Calculus?


It is an applied predicate calculus specifically tailored for relational databases proposed by E.F.
Codd.
E.g. of languages based on it are DSL, ALPHA, QUEL.
34. What is normalization?
It is a process of analyzing the given relation schemas based on their Functional Dependencies
(FDs)and primary key to achieve the properties Minimizing redundancy, Minimizing insertion,
deletion and update anomalies.
35. What is Functional Dependency?
A Functional dependency is denoted by X Y between two sets of attributes X and Y that are
subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The
constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This
means the value of X component of a tuple uniquely determines the value of component Y.
36. When is a functional dependency F said to be minimal?
Every dependency in F has a single attribute for its right hand side.
We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset
of X and still have a set of dependency that is equivalent to F.
We cannot remove any dependency from F and still have set of dependency that is equivalent to
F.
37. What is Multivalued dependency?
Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are
bothsubsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2
exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following
properties
t3[x] = t4[X] = t1[X] = t2[X]
t3[Y] = t1[Y] and t4[Y] = t2[Y]
t3[Z] = t2[Z] and t4[Z] = t1[Z]
where [Z = (R-(X U Y)) ]
38. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation
schemas after decomposition.
39. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values.
40. What is Fully Functional dependency?
It is based on concept of full functional dependency. A functional dependency X Y is fully

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 90


Global Academy of Technology

functional dependency if removal of any attribute A from X means that the dependency
does not hold any more.

41. What is 2NF?


A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.
42. What is 3NF?
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following
is true
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
43. What is BCNF (Boyce-Codd Normal Form)?
A relation schema R is in BCNF if it is in 3NF and satisfies additional constraints that for
every FD X A, X must be a candidate key.
44. What is 4NF?
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that
holds over R, one of following is true
X is subset or equal to (or) XY = R.
X is a super key.
45. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ...,Rn} that
holds R, one the following is true
Ri = R for some i.
The join dependency is implied by the set of FD, over R in which the left side is key of R.
46. What is Domain-Key Normal Form?
A relation is said to be in DKNF if all constraints and dependencies that should hold on the
constraint can be enforced by simply enforcing the domain constraint and key constraint on
the relation.
47. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 91


Global Academy of Technology

owner entity. It is sometime called as Discriminator.


Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
ArtificialKey:
If no obvious key, either stand alone or compound is available, then the last resort is to
simply create a key, by assigning a unique number to each record or occurrence. Then this
is known as developing an artificial key.
CompoundKey:
If no single data element uniquely identifies occurrences within a construct, then combining
multiple elements to create a unique identifier for the construct is known as creating a
compound key.
NaturalKey:
When one of the data elements stored within a construct is utilized as the primary key, then it is
called the natural key.
48. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
49. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every
relation and index that it contains. This information is stored in a collection of relations
maintained by the system called metadata. It is also called data dictionary.
50. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the least
estimated cost is referred to as query optimization.
51. What is join dependency and inclusion dependency?
JoinDependency:
A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ...,Rn} is
said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R .
There is no set of sound and complete inference rules for JD.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 92


Global Academy of Technology

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

57. What do you mean by flat file database?


It is a database in which there are no programs or user access languages. It has no cross-file
capabilities but is user-friendly and provides user-interface management.
58. What is "transparent DBMS"?
It is one, which keeps its Physical Structure hidden from user.
59. Brief theory of Network, Hierarchical schemas and their properties

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 93


Global Academy of Technology

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

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 94


Global Academy of Technology

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.

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 95


Global Academy of Technology

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 96


Global Academy of Technology

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 97


Global Academy of Technology

Dept of CSE DBMS LABORATORY WITH MINI PROJECT– 15CSL58 98

You might also like