Dbms Lab Manual
Dbms Lab Manual
Dbms Lab Manual
SQL: It is structured query language, basically used to pass the query to retrieve and manipulate 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:
4. Describe statements: To describe the structure (column and data types) of an existing
database, table, index, or view.
Syntax:
DESC table_name;
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 relational database.
Syntax:
UPDATE: UPDATE statement that changes the data of one or more records in a table. Either all 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 be defined
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:
SELECT<attribute list> FROM<table list>
WHERE<condition> Where
• Attribute list is a list of attribute name whose values to be retrieved by the query.
• Table list is a list of table name required to process query.
• Condition is a Boolean expression that identifies the tuples to be retrieved by query.
Data Constraints are the business Rules which are enforced on the data being stored in a table are
called Constraints.
Syntax:
CREATE TABLE tablename (Columnname1 DATATYPE, columnname2 DATATYPE,
columnname3 DATATYPE, PRIMARY KEY (columnname1, columnname2));
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:
CREATE TABLE tablename (Columnname1 DATATYPE, columnname2 DATATYPE,
columnname3 DATATYPE, PRIMARY KEY (columnname1, columnname2), FOREIGN KEY
(columnname2) REFERENCES tablename2;
Note:
The NOT NULL constraint can only be applied at column level.
ER- Diagram: It is an Entity –Relationship diagram which is used to represent the relationship
between different entities. An entity is an object in the real world which is distinguishable from
other objects. The overall logical structure of a database can be expressed graphically by an ER
diagram, which is built up from following components.
Solution:
Entity-Relationship Diagram
M N
Book_Copies Library_Branch
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
4 rows selected.
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
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 one customer.
3. List all salesmen and indicate those who have and don’t have customers in their
cities (Use UNION operation.)
4. Create a view that finds the salesman who has the customer with the highest order
of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders
must also be deleted.
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table
orders and then execute the following:
Use ON DELETE SET NULL at the end of foreign key definitions while creating child table
customers and then executes the following:
Solution:
Entity-Relationship Diagram
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 more movies.
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOIN operation).
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
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.
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:
1. List all the student details studying in fourth semester ‘C’ section.
SELECT S.*, SS.SEM, SS.SEC
FROM STUDENT S, SEMSEC SS, CLASS C
WHERE S.USN = C.USN AND
SS.SSID = C.SSID AND
SS.SEM = 4 AND
SS.SEc=’C’;
2. Compute the total number of male and female students in each semester and in each
section.
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for all students.
CREATE OR REPLACE PROCEDURE AVGMARKS IS
CURSOR C_IAMARKS IS
SELECT GREATEST(TEST1,TEST2) AS A, GREATEST(TEST1,TEST3) AS B,
GREATEST(TEST3,TEST2) AS C
FROM IAMARKS
WHERE FINALIA IS NULL
FOR UPDATE;
C_A NUMBER;
C_B NUMBER;
C_C NUMBER;
C_SM NUMBER;
C_AV NUMBER;
BEGIN
OPEN C_IAMARKS;
LOOP
FETCH C_IAMARKS INTO C_A, C_B, C_C;
EXIT WHEN C_IAMARKS%NOTFOUND;
--DBMS_OUTPUT.PUT_LINE(C_A || ' ' || C_B || ' ' || C_C);
IF (C_A != C_B) THEN
C_SM:=C_A+C_B;
ELSE
C_SM:=C_A+C_C;
END IF;
C_AV:=C_SM/2;
--DBMS_OUTPUT.PUT_LINE('SUM = '||C_SM);
--DBMS_OUTPUT.PUT_LINE('AVERAGE = '||C_AV);
UPDATE IAMARKS SET FINALIA=C_AV WHERE CURRENT OF C_IAMARKS;
END LOOP;
CLOSE C_IAMARKS;
END;
/
Note: Before execution of PL/SQL procedure, IAMARKS table contents are:
Below SQL code is to invoke the PL/SQL stored procedure from the command line:
BEGIN
AVGMARKS;
END;
SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER,
(CASE
WHEN IA.FINALIA BETWEEN 17 AND 20 THEN 'OUTSTANDING'
WHEN IA.FINALIA BETWEEN 12 AND 16 THEN 'AVERAGE'
ELSE 'WEAK'
END) AS CAT
FROM STUDENT S, SEMSEC SS, IAMARKS IA, SUBJECT SUB
WHERE S.USN = IA.USN AND
SS.SSID = IA.SSID AND
SUB.SUBCODE = IA.SUBCODE AND
SUB.SEM = 8;
Entity-Relationship Diagram
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 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).
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 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?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
6. Disadvantage in File Processing System?
Data redundancy & inconsistency.
Difficult in accessing data.
Data isolation.
Data integrity.
Concurrent access is not possible.
Security Problems.
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.
Entity Integrity:States that “Primary key cannot have NULL value”
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.
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 entity
set.
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 name
R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r
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 a Relation?
It is the number of attribute of its relation schema.
22. What is Relationship?
It is an association among two or more entities.
23. What is Relationship set?