Dbms Manual 2022
Dbms Manual 2022
2022-2023
DBMS LAB MANNUAL
(18CSL58)
Compiled by:
Prof. Keerthana Shankar
SQL: It is structured query language, basically used to pass the query to retrieve andmanipulate the
information from database. Depending upon the nature of query, SQL is divided into different
components:
DDL: The Data Definition Language (DDL) is used to create the database (i.e. tables,
keys,relationships etc), maintain the structure of the database and destroy databases and database
objects.
Syntax:
CREATE TABLE table_name(columnName1 datatype(size), columnName2 datatype(size),.........);
• Adding new
columns:
Syntax:
5. Truncate statements: To destroy the data in an existing database, table, index, or view.If a
table is truncated all records held within it are lost and cannot be recovered but the table
structure is maintained.
Syntax :
TRUNCATE TABLE table_name;
INSERT: INSERT statement adds one or more records to any single table in a relationaldatabase.
Syntax:
UPDATE: UPDATE statement that changes the data of one or more records in a table. Eitherall the
rows can be updated, or a subset may be chosen using a condition.
Syntax:
UPDATE table_name SET column_name = value [, column_name = value ...] [WHERE
condition]
DELETE: DELETE statement removes one or more records from a table. A subset may bedefined
for deletion using a condition, otherwise all records are removed.
Syntax:
DELETE FROM tablename WHERE condition:
SELECT: SELECT statement returns a result set of records from one or more tables.
Syntax:
• Attribute list is a list of attribute name whose values to be retrieved by the query.
1. I/O Constraint This type of constraint determines the speed at which data can be inserted
or extracted from an Oracle table. I/O Constraints is divided into two different types
●The Primary Key Constraint
●The Foreign Key Constraint
2. Business rule Constraint This type of constraint is applied to data prior the data being
Inserted into table columns.
●Column level
●Table level
Syntax:
Syntax
CREATE TABLE tablename (Columnname1
tablename[(columnname)] [ON DELETE CASCADE],
columnname3 DATATYPE ,.....);
The table in which FOREIGN KEY is defined is called FOREIGN TABLE or DETAIL TABLE.
The table in which PRIMARY KEY is defined and referenced by FOREIGN KEY is called
PRIMARY TABLE or MASTER TABLE.
ON DELETE CASCADE is set then DELETE operation in master table will trigger the
DELETE operation for corresponding records in the detail table.
Syntax:
Note:
The NOT NULL constraint can only be applied at column level.
One to one
One to many
Many to one
Many to many
Solution:
Entity-Relationship Diagram
Author_Name
Book_id Title
Pub_Year M N
Has
Published-by
N No_of_copies
Branch_id
Publisher_Name
M M N
1 Book_Copies In Library_Branch
Branch_Name
Address
Publisher
N Address
Date_out
Book_Lending
Phone
Card_No
Due_date
N
Card
Schema Diagram
Table Creation:
PUBLISHER
Table created.
BOOK
Table created.
BOOK_AUTHORS
Table created.
LIBRARY_BRANCH
Table created.
BOOK_COPIES
Table created.
BOOK_LENDING
PUBLISHER
BOOK
BOOK_AUTHORS
LIBRARY_BRANCH
ROAD');
BOOK_COPIES
BOOK_LENDING
BOOK_ID AUTHOR_NAME
------- ------------
1111 SOMMERVILLE
2222 NAVATHE
3333 HENRY GRAY
4444 THOMAS
4 rows selected.
3 rows selected.
5 rows selected.
7 rows selected.
SQL> SELECT * FROM LIBRARY_BRANCH;
5 rows selected.
Queries:
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.
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN '01-JAN-2017' AND '30-JUN-2017'
GROUP BY CARD_NO
HAVING COUNT(*) > 3;
CARD_NO
-------
1
3) Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
1 row deleted.
4) Partition the BOOK table based on year of publication. Demonstrate its working with a simple
query.
PUB_YEAR
2004
2005
2010
2010
5) Create a view of all books and its number of copies that are currently available in the Library.
View created.
BOOK_I
D TITLE NO_OF_COPIES
------- -------------------- ------------
1111 SE 5
3333 ANOTOMY 6
4444 ENCYCLOPEDIA 10
2222 DBMS 12
4444 ENCYCLOPEDIA 3
Solution:
Entity-Relationship Diagram
Schema Diagram
Table Creation
Table Descriptions
DESC SALESMAN;
DESC CUSTOMER1;
DESC ORDERS;
Queries:
2. Find the name and numbers of all salesmen who had more than onecustomer.
3. List all salesmen and indicate those who have and don’t have customers in their
cities (Use UNIONoperation.)
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 bedeleted.
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:
Solution:
Entity-Relationship Diagram
Dir_id Dir_Name
Act_id Act_Name
Dir_Phone
Act_Gender Actor Director
M
Has
Movie_Cast
N
Role
Rev_Stars
N Movies
Mov_Lang
Mov_id
Mov_Title Mov_Year
Schema Diagram
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
Table Creation
Table Descriptions
DESC ACTOR;
DESC DIRECTOR;
DESC MOVIES;
DESC MOVIE_CAST;
DESC RATING;
Queries:
SELECT MOV_TITLE
FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME = ‘HITCHCOCK’);
2. Find the movie names where one or more actors acted in two or moremovies.
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOINoperation).
FROM ACTOR A
JOIN MOVIE_CASTC
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
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
movietitle.
Schema Diagram
Table Creation
Table Descriptions
DESC STUDENT;
DESC SEMSEC;
DESC CLASS;
DESC SUBJECT;
DESC IAMARKS;
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1RN13CS091','10CS81','CSE8C', 15, 16, 18);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1RN13CS091','10CS82','CSE8C', 12, 19, 14);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1RN13CS091','10CS83','CSE8C', 19, 15, 20);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1RN13CS091','10CS84','CSE8C', 20, 16, 19);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1RN13CS091','10CS85','CSE8C', 15, 15, 12);
Queries:
SS.SEc=’C’;
2. Compute the total number of male and female students in each semester and ineach
section.
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for allstudents.
CREATE OR REPLACE PROCEDURE AVGMARKS IS
CURSOR C_IAMARKS IS
SELECT GREATEST(TEST1,TEST2) AS A, GREATEST(TEST1,TEST3) AS B,
GREATEST(TEST3,TEST2) ASC
FROM IAMARKS
WHERE FINALIA IS NULL
FOR UPDATE;
C_A NUMBER;
C_B NUMBER;
C_C NUMBER;
C_SM NUMBER;
C_AV NUMBER;
BEGIN
OPEN C_IAMARKS;
LOOP
FETCH C_IAMARKS INTO C_A, C_B, C_C;
EXIT WHEN C_IAMARKS%NOTFOUND;
--DBMS_OUTPUT.PUT_LINE(C_A || ' ' || C_B || ' ' || C_C);
IF (C_A != C_B) THEN
C_SM:=C_A+C_B;
ELSE
C_SM:=C_A+C_C;
END IF;
C_AV:=C_SM/2;
--DBMS_OUTPUT.PUT_LINE('SUM = '||C_SM);
--DBMS_OUTPUT.PUT_LINE('AVERAGE = '||C_AV);
UPDATE IAMARKS SET FINALIA=C_AV WHERE CURRENT OF C_IAMARKS;
END LOOP;
CLOSE C_IAMARKS;
END;
/
Note: Before execution of PL/SQL procedure, IAMARKS table contents are:
Below SQL code is to invoke the PL/SQL stored procedure from the command line:
BEGIN
AVGMARKS;
END;
SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER,
(CASE
WHEN IA.FINALIA BETWEEN 17 AND 20 THEN'OUTSTANDING'
WHEN IA.FINALIA BETWEEN 12 AND 16 THEN 'AVERAGE'
ELSE'WEAK'
END) AS CAT
FROM STUDENT S, SEMSEC SS, IAMARKS IA, SUBJECT SUB
WHERE S.USN = IA.USN AND
SS.SSID = IA.SSID AND
SUB.SUBCODE = IA.SUBCODE AND
SUB.SEM = 8;
Entity-Relationship Diagram
SSN Controlled_by
Name N 1
DNO
Salary
DName
1 N
MgrStartDate
1
Sex 1
N
M Dlocation
Supervisee
Supervisor
Supervision Works_on Controls
N
Hours
Project PName
PNO PLocation
Schema Diagram
Employee
SSN Fname Lname Address Sex Salary SuperSSN DNO
Department
DLocation
DNO DLOC
Project
Works_on
Table Creation
NOTE: Once DEPARTMENT and EMPLOYEE tables are created we must alter department
table to add foreign constraint MGRSSN using sql command
Table Descriptions
DESC EMPLOYEE;
DESC DEPARTMENT;
DESC DLOCATION;
DESC PROJECT;
DESC WORKS_ON;
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSECE01’,’JOHN’,’SCOTT’,’BANGALORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE01’,’JAMES’,’SMITH’,’BANGALORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE02’,’HEARN’,’BAKER’,’BANGALORE’,’M’, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE03’,’EDWARD’,’SCOTT’,’MYSORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE04’,’PAVAN’,’HEGDE’,’MANGALORE’,’M’, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE05’,’GIRISH’,’MALYA’,’MYSORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSCSE06’,’NEHA’,’SN’,’BANGALORE’,’F’, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSACC01’,’AHANA’,’K’,’MANGALORE’,’F’, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSACC02’,’SANTHOSH’,’KUMAR’,’MANGALORE’,’M’, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSISE01’,’VEENA’,’M’,’MYSORE’,’M’, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘RNSIT01’,’NAGESH’,’HR’,’BANGALORE’,’M’, 500000);
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘Scott’, either as a worker or as a manager of the department that controlsthe
project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a10
percentraise.
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 thisdepartment
4. Retrieve the name of each employee who works on all the projects Controlled by
department number 5 (use NOT EXISTSoperator).
WHERE DNO=’5’)
MINUS (SELECT PNO
FROM WORKS_ON
WHERE E.SSN=SSN));
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.
Viva Questions
1. What is SQL?
Structured Query Language
2. What isdatabase?
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 specificpurpose.
3. What isDBMS?
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 Databasesystem?
The database and DBMS software together is called as Database system.
5. Advantages ofDBMS?
Redundancy iscontrolled.
Unauthorized access isrestricted.
Providing multiple userinterfaces.
Enforcing integrityconstraints.
Providing backup andrecovery.
6. Disadvantage in File ProcessingSystem?
Data redundancy &inconsistency.
Difficult in accessingdata.
Dataisolation.
Dataintegrity.
Concurrent access is notpossible.
SecurityProblems.
7. Describe the three levels of dataabstraction?
There are three levels of abstraction:
Physical level: The lowest level of abstraction describes how data arestored.
Logical level: The next higher level of abstraction, describes what data are stored in
database and what relationship among thosedata.
A collection of conceptual tools for describing data, data relationships data semantics and
constraints.
13. What is E-Rmodel?
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 Orientedmodel?
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 anEntity?
It is an 'object' in the real world with an independent existence.
16. What is an Entitytype?
It is a collection (set) of entities that have same attributes.
17. What is an Entityset?
It is a collection of all entities of particular entity type in the database.
18. What is an Extension of entitytype?
The collections of entities of a particular entity type are grouped together into an entity
set.
19. What is anattribute?
It is a particular property, which describes the entity.
20. What is a Relation Schema and aRelation?
A relation Schema denoted by R(A1, A2, …, An) is made up oftherelation name
R and the list of attributes Ai that it contains. A relation isdefinedas a set of tuples.Letr
be the relation which contains set tuples (t1,t2,t3, ...,tn). Each tuple is an ordered list of n-
values t=(v1,v2, ...,vn).
21. What is degree of aRelation?
It is the number of attribute of its relation schema.
22. What isRelationship?
It is an association among two or more entities.
23. What is Relationshipset?
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 isnormalization?
It is a process of analyzing the given relation schemas basedontheir Functional
Dependencies (FDs) and primary key to achieve theproperties
Minimizingredundancy
Minimizing insertion, deletion and updateanomalies.
35. What is FunctionalDependency?
A Functional dependency is denoted byX Y between two sets of attributes X
andYthat 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
componentY.
36. When is a functional dependency F said to beminimal?
Every dependency in F has a single attribute for its right handside.
We cannot replace any dependencyX A in F with a dependencyY A where Yisa
proper subset of X and still have a set of dependency that is equivalent toF.
We cannot remove any dependency from F and still have set of dependency that is
equivalent toF.
37. What is Multivalueddependency?
Multivalued dependency denoted by X Y specified on relation schema R, where X
and Y are both subsets 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
followingproperties
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 joinproperty?
It guarantees that the spurious tuple generation does not occur with respect to relation
schemas after decomposition.