Dbms Lab Manual-2017
Dbms Lab Manual-2017
INTRODUCTION TO SQL
CREATE SCHEMA
Specifies a new database schema by giving it a name
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> ( <Attribute A1> <Data
Type D1> [< Constraints>],
<Attribute A2> <Data Type D2> [< Constraints>],
.
<Attribute An> <Data Type Dn> [< Constraints>],
[<integrity-constraint1>, <integrity-constraint k> ] );
- A constraint NOT NULL may be specified on an attribute
Ex: CREATE TABLE DEPARTMENT (
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP
ON DELETE SET DEFAULT ON UPDATE CASCADE);
DROP TABLE
Used to remove a relation (base table) and its definition.
The relation can no longer be used in queries, updates, or any
other commands since its description no longer exists
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.
JOIN
All subsequent examples uses COMPANY database as shown
below:
Example of a simple query on one relation
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
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
USE OF *
USE OF DISTINCT
SQL does not treat a relation as a set; duplicate tuples can
appear. To eliminate duplicate tuples in a query result, the
keyword DISTINCT is used
Example: the result of Q1c may have duplicate SALARY values
whereas Q1d does not have any duplicate values
SET OPERATIONS
NESTING OF QUERIES
EXPLICIT SETS
It is also possible to use an explicit (enumerated) set of values in
the WHERE-clause rather than a nested query
Query 9: Retrieve the social security numbers of all
employees who work on project number 1, 2, or 3.
AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVG
Query 11: Find the maximum salary, the minimum salary,
and the average salary among all employees.
Q11: SELECT MAX (SALARY), MIN(SALARY),
AVG(SALARY)
FROM EMPLOYEE
Note: Some SQL implementations may not allow more than one
function in the SELECT-clause
Query 12: Find the maximum salary, the minimum salary,
and the average salary among employees who work for the
'Research' department.
Q12: SELECT MAX (SALARY), MIN(SALARY),
AVG(SALARY) FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND DNAME='Research'
Queries 13 and 14: Retrieve the total number of employees in
the company (Q13), and the number of employees in the
'Research' department (Q14).
Q13: SELECT COUNT (*) FROM EMPLOYEE
Q14: SELECT COUNT (*) FROM EMPLOYEE,
DEPARTMENT
GROUPING
In many cases, we want to apply the aggregate functions to
subgroups of tuples in a relation
Each subgroup of tuples consists of the set of tuples that have
the same value for the grouping attribute(s)
THE HAVING-CLAUSE
Sometimes we want to retrieve the values of these functions for
only those groups that satisfy certain conditions. The HAVING-
clause is used for specifying a selection condition on groups
(rather than on individual tuples)
Query 17: For each project on which more than two
employees work, retrieve the project number, project name,
and the number of employees who work on that project.
Q17: SELECT PNUMBER, PNAME, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
SUBSTRING COMPARISON
The LIKE comparison operator is used to compare partial
strings. Two reserved characters are used: '%' (or '*' in some
ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition,
subtraction, multiplication, and division, respectively) can be
applied to numeric values in an SQL query result
Query 20: Show the effect of giving all employees who work
on the 'ProductX' project a 10% raise.
Q20: SELECT FNAME, LNAME, 1.1*SALARY
FROM EMPLOYEE, WORKS_ON, PROJECT
WHERE SSN=ESSN
AND PNO=PNUMBER AND PNAME='ProductX
ORDER BY
AND 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
Query 22: Retrieve the names of all employees who have two
or more dependents.
Q22: SELECT LNAME, FNAME FROM
EMPLOYEE
WHERE (SELECT COUNT (*) FROM DEPENDENT
WHERE SSN=ESSN) 2);
Query 23: List the names of managers who have least one
dependent.
Q23: SELECT FNAME, LNAME
FROM EMPLOYEE
INSERT
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;
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
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;
UPDATE EMPLOYEE
SET SALARY = SALARY *1.1
WHERE DNO IN (SELECT DNUMBER FROM
DEPARTMENT
WHERE DNAME='Research');
SQL TRIGGERS
Objective: to monitor a database and take initiate action
when a condition occurs
Triggers are nothing but the procedures/functions that
involve actions and fired/executed automatically whenever
an event occurs such as an insert, delete, or update operation
or pressing a button or when mouse button is clicked
VIEWS IN SQL
A view is a single virtual table that is derived from other
tables. The other tables could be base tables or previously
defined view.
Allows for limited update operations Since the table may not
physically be stored
Allows full query operations
A convenience for expressing certain operations
A view does not necessarily exist in physical form, which
limits the possible update operations that can be applied to
views.
LAB EXPERIMENTS
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
Book
Book_Authors
Book_id Author_name
Publisher
Book_Copies
Book_Lending
Library_Branch
Table Creation
CREATE TABLE PUBLISHER
(NAME VARCHAR2 (20) PRIMARY KEY,
PHONE INTEGER,
ADDRESS VARCHAR2 (20));
Table Descriptions
DESC PUBLISHER;
DESC BOOK;
DESC BOOK_AUTHORS;
DESC LIBRARY_BRANCH;
DESC BOOK_COPIES;
DESC CARD;
DESC BOOK_LENDING;
Queries:
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN 01-JAN-2017 AND
01-JUL-2017
GROUP BY CARD_NO
HAVING COUNT (*)>3;
4. Create a view of all books and its number of copies that are
currently available in the Library.
Solution:
Entity-Relationship Diagram
Schema Diagram
Salesman
Customer
Orders
Table Creation
Table Descriptions
DESC SALESMAN;
DESC CUSTOMER1;
DESC ORDERS;
Queries:
FROM CUSTOMER1
GROUP BY GRADE
HAVING GRADE > (SELECT AVG(GRADE)
FROM CUSTOMER1
WHERE CITY='BANGALORE');
3. List all salesmen and indicate those who have and dont
have customers in their cities (Use UNION operation.)
WHERE C.ORD_DATE =
B.ORD_DATE);
Spielberg to 5.
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
CSE, Vemana IT, Bangalore Page 54
DBMS Lab Manual-2017
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);
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN
(SELECT ACT_ID
FROM MOVIE_CAST GROUP
BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also
in a movie after 2015 (use JOIN operation).
OR
2015;
Schema Diagram
Table Creation
CREATE TABLE STUDENT (
USN VARCHAR (10) PRIMARY KEY,
SNAME VARCHAR (25),
ADDRESS VARCHAR (25),
PHONE NUMBER (10),
GENDER CHAR (1));
Table Descriptions
DESC STUDENT;
DESC SEMSEC;
DESC CLASS;
DESC SUBJECT;
DESC IAMARKS;
Queries:
C_A NUMBER;
C_B NUMBER;
CSE, Vemana IT, Bangalore Page 79
DBMS Lab Manual-2017
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;
/
CSE, Vemana IT, Bangalore Page 80
DBMS Lab Manual-2017
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
Department
DLocation
DNO DLOC
CSE, Vemana IT, Bangalore Page 85
DBMS Lab Manual-2017
Project
Works_on
Table Creation
Table Descriptions
DESC EMPLOYEE;
CSE, Vemana IT, Bangalore Page 87
DBMS Lab Manual-2017
DESC DEPARTMENT;
DESC DLOCATION;
DESC PROJECT;
DESC WORKS_ON;
Queries:
AND D.DNAME=ACCOUNTS;
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;
Viva Questions
1. What is SQL?
CSE, Vemana IT, Bangalore Page 99
DBMS Lab Manual-2017
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).
CSE, Vemana IT, Bangalore Page 104
DBMS Lab Manual-2017
Atomicity:
Either all actions are carried out or none are. Users should
not have to worry about the effect of 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.
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?
objects) for all the user accounts can go in one database filebut
that's not an ideal situation because it does not make the database
structure very flexible for controlling access to storage for
different users, putting the database on different disk drives, or
backing up and restoring just part of the database.
You must have at least one database file but usually, more
than one files are used. In terms of accessing and using the data
in the tables and other objects, the number (or location) of the files
is immaterial.
The database files are fixed in size and never grow bigger
than the size at which they were created
ControlFiles
The control files and redo logs support the rest of the
architecture. Any database must have at least one control file,
although you typically have more than one to guard against loss.
The control file records the name of the database, the date and
time it was created, the location of the database and redoes logs,
and the synchronization information to ensure that all three sets
of files are always in step. Every time you add a new database or
redo log file to the database, the information is recorded in the
control files.
CSE, Vemana IT, Bangalore Page 122
DBMS Lab Manual-2017
Redo Logs
Any database must have at least two redo logs. These are the
journals for the database; the redo logs record all changes to the
user objects or system objects. If any type of failure occurs, the
changes recorded in the redo logs can be used to bring the
database to a consistent state without losing any committed
transactions. In the case of non-data loss failure, Oracle can apply
the information in the redo logs automatically without
intervention from the DBA.
The redo log files are fixed in size and never grow dynamically
from the size at which they were created.
77. What is ROWID?
The ROWID is a unique database-wide physical address for
every row on every table. Once assigned (when the row is first
inserted into the database), it never changes until the row is
deleted or the table is dropped.
The ROWID consists of the following three components, the
combination of which uniquely identifies the physical storage
location of the row.
Oracle database file number, which contains the block
with the rows
CSE, Vemana IT, Bangalore Page 123
DBMS Lab Manual-2017
(a) i& iii because theta joins are joins made on keys that are
not primary keys.
85. In mapping of ERD to DFD
a) entities in ERD should correspond to an existing
entity/store in DFD
b) entity in DFD is converted to attributes of an entity in
ERD
c) relations in ERD has 1 to 1 correspondence to processes
in DFD
d) relationships in ERD has 1 to 1 correspondence to flows
in DFD
(a) entities in ERD should correspond to an existing entity/store
in DFD
86. A dominant entity is the entity
a) on the N side in a 1 : N relationship
b) on the 1 side in a 1 : N relationship
c) on either side in a 1 : 1 relationship
d) nothing to do with 1 : 1 or 1 : N relationship
(b) on the 1 side in a 1 : N relationship
87. Select 'NORTH', CUSTOMER From CUST_DTLS
Where REGION = 'N' Order By
CSE, Vemana IT, Bangalore Page 128
DBMS Lab Manual-2017
Explicit
95. What is cold backup and hot backup (in case of Oracle)?
Cold Backup:
Itis copying the three sets of files (database files, redo logs, and
control file) when the instance is shut down. This is a straight file
copy, usually from the disk directly to tape. You must shut down
the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the
event of data file loss is restoring all the files from the latest
backup. All work performed on the database since the last backup
is lost.
Hot Backup:
Some sites (such as worldwide airline reservations systems)
cannot shut down the database while making a backup copy of the
files. The cold backup is not an available option.
So different means of backing up database must be used
the hot backup. Issue a SQL command to indicate to Oracle, on a
tablespace-by-tablespace basis, that the files of the tablespace are
to backed up. The users can continue to make full use of the files,
including making changes to the data. Once the user has indicated
that he/she wants to back up the tablespace files, he/she can use
CSE, Vemana IT, Bangalore Page 131
DBMS Lab Manual-2017
SQL Questions:
9. State true or false. !=, <>, ^= all denote the same operation.
True
10. What are the privileges that can be granted on a table by
a user to others?
Insert, update, delete, select, references, index, execute,
alter, all
11. What command is used to get back the privileges offered
by the GRANT command?
REVOKE
12. Which system tables contain information on privileges
granted and privileges obtained?
USER_TAB_PRIVS_MADE,
USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints
on all the tables created?
USER_CONSTRAINTS
14. TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP.
TROUBLETHETROUBLE
18. What will be the output of the following query?
SELECT
DECODE(TRANSLATE('A','1234567890','1111111111'),
'1','YES', 'NO' );
Answer :
NO
Explanation :
The query checks whether a given string is a numerical digit.
19. What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;
This displays the total salary of all employees. The null
values in the commission column will be replaced by 0 and added
to salary.
20. Which date function is used to find the difference
between two dates?
MONTHS_BETWEEN
21. Why does the following command give a compilation
error?
DROP TABLE &TABLE_NAME;
SQL HANDSON
b. EMP:
COLUMN NAME
DATATYPE(SIZE)
---------------------------------------------------------------------
--------------------------
EMPNO NUMBER (4)
ENAME
VARCHAR2 (10)
JOB VARCHAR2 (9)
MGR NUMBER (4)
HIREDATE DATE
SAL NUMBER (7, 2)
COMM NUMBER (7,
2)
DEPTNO NUMBER
(2)
COLUMN NAME
DATATYPE (SIZE)
-----------------------------------------------------------------
------------------------------
ENAME CHAR (15)
7. Decrease the size for the column EMPNO with the
following information:-
COLUMN NAME DATATYPE
(SIZE)
---------------------------------------------------------------------
--------------------------
EMPNO NUMBER (2)
8. Modify the column name of EMPNO to
EMPLOYEE_NUMBER present in the EMP table verify
the result.
9. Add a new column nationality placed between JOB and
MGR columns and verify the result
10. Drop the table DEPT and EMP.
11. What is the data type of the column HIREDATE
and how many bytes it occupies.
b.EMP:
COLUMN NAME DATATYPE(SIZE)
---------------------------------------------------------------------
--------------------------
EMPNO NUMBER(4) CONSTRAINT
PK_EMPNO PRIMARY KEY
ENAME VARCHAR2(10) CONSTRAINT
UQ_DEPTNO UNIQUE
JOB VARCHAR2(9)
CSE, Vemana IT, Bangalore Page 144
DBMS Lab Manual-2017
MGR NUMBER(4)
HIREDATE DATE DEFAULT
SYSDATE
SAL NUMBER(7,2) CONSTRAINT
CK_SAL CHECK(SAL)
COMM NUMBER(7,2)
DEPTNO NUMBER(2) CONSTRAINT
FK_DEPTNO REFERENCE
13. Select all the constraints in the EMP table
SOL: SELECT * FROM USER_CONSTRAINTS WHERE
TABLE_NAME=EMP;
14. select the owner, constraints name, constraints type,
table name, status for DEPT table
SOL: SELECT OWNER, CONSTRAINTS_ NAME,
CONSTRAINTS_TYPE, TABLE_ NAME, STATUS FROM
USER_CONSTRAINTS WHERE
TABLE_NAME=DEPT;
15. Drop the constraints UQ_FMANE from EMP table
SOL: ALTER TABLE EMP DROP CONSTRAINT
UQ_FNAME;
Name Type
-----------------------------------------------------
EMPNO NUMBER (6)
ENAME VARCHAR2 (20)
DOB DATE
JOB VARCHAR2 (10)
DEPTNO NUMBER (2)
SAL NUMBER (7,2)
Allow NULL for all columns except ENAME and JOB.
EMPNO is the Primary Key
b. Add a column EXPERIENCE of type NUMERIC to the
EMP table. Allow NULL to it.
Name Type
-----------------------------------------------------
DEPTNO NUMBER (2)
DNAME VARCHAR2 (15)
LOCN VARCHAR2 (10)
DEPTNO is the Primary Key and DNAME cannot be
NULL