Sie sind auf Seite 1von 52

www.Vidyarthiplus.

com
LIST OF EXPERIMENTS
CS 6312 - DBMS LAB
LIST OF EXPERIMENTS:
1. Creation of a database and writing SQL queries to retrieve information from the database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of database triggers and functions
11. Mini project (Application Development using Oracle/ Mysql )
a) Inventory Control System.
b) Material Requirement Processing.
c) Hospital Management System.
d) Railway Reservation System.
e) Personal Information System.
f) Web Based User Identification System.
g) Timetable Management System.
h) Hotel Management System.
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement a database schema for a given problem-domain
Populate and query a database
Create and maintain tables using PL/SQL.
Prepare reports.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:
HARDWARE:
Standalone desktops 30 Nos.
(or)
Server supporting 30 terminals or more.
SOFTWARE:
Front end: VB/VC ++/JAVA or Equivalent
Back end: Oracle / SQL / MySQL/ PostGress / DB2 or Equivalent
CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
CONTENTS

S.NO

NAME OF THE EXERCISE

PAGE NO.

DDL- Data Definition, Table Creation, Constraints.

DML- Insert, Select Commands, Update & Delete Commands.

TCL Rollback, Commit commands.

11

Writing and Practice of Simple Queries.

13

Nested Queries & Queries Using Group By And Other Clauses.

19

Problems Based On Views, Synonym, Sequence & Index.

26

Creating Database.

31

High Level Programming Language Extension (PL/SQL Blocks).

34

PL/SQL Procedures.

41

10

PL/SQL Functions.

45

11

Triggers

48

12

Database Design and implementation (Mini Project).

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
1. DDL COMMANDS
AIM:
To create, alter, truncate and drop a table using DDL commands.
DDL COMMANDS:
OVERVIEW:
CREATE - to create objects in the database
ALTER - alters the structure of the objects in 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
SQL - CREATE TABLE
Syntax: CREATE TABLE tablename (column_name data_ type constraints, )
Example:
INPUT::
SQL>

CREATE TABLE DEPARTMENT ( DEPTID VARCHAR(5) CONSTRAINT PKEY PRIMARY KEY,


DEPTNAME VARCHAR(15),

DOS DATE CONSTRAINT NOTNULL );

OUTPUT: Table created.

SQL>

CREATE TABLE EMPLOYE ( EMPID VARCHAR(5) CONSTRAINT PKEY PRIMARY KEY,


EMPNAME VARCHAR(15), JOB CHAR(10) CONSTRAINT UNIQ1 UNIQUE,
MGRID VARCHAR(5) CONSTRAINT FKEY1 REFERENCES EMP (EMPID),
HIREDATE DATE,

DEPTID VARCHAR(5) CONSTRAINT FKEY2 REFERENCES DEPT(DEPTID),

SALARY NUMBER(7,2));
OUTPUT: Table created.

SQL - DESC TABLE

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
SQL>desc Employe;
Name

Null?

--------------------------------- -------EMPID

Type
----------------------------

NOT NULL

EMPNAME

VARCHAR2(5)
VARCHAR2(20)

JOB

NOT NULL

CHAR(10)

MGRID

NOT NULL

VARCHAR2(5)

HIREDATE

DATE

DEPTID

VARCHAR2(5)

SALARY

NUMBER(7,2)

SQL - ALTER TABLE


INPUT::
SQL>ALTER TABLE EMPLOYE ADD CONSTRAINT NTNLL NOT NULL (SALARY);
OUTPUT: Table Altered.
Similarly, ALTER TABLE EMPLOYE DROP CONSTRAINT UNIQ1;

SQL - DROP TABLE


Deletes table structure

Cannot be recovered

Use with caution

INPUT::
SQL> DROP TABLE EMP;

Here EMP is table name

OUTPUT: Table Dropped.

SQL - TRUNCATE TABLE


TRUNCATE

TRUNCATE TABLE <TABLE NAME>;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. What is a 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.
2. What is the role of data dictionary in DBMS architecture?
A data dictionary contains a list of all files in the database, the number of records in each file, and
the names and types of each field. Data dictionaries do not contain any actual data from the database,
only bookkeeping information for managing it.
3. What is a data model?
Data Models are fundamental entities to introduce abstraction in DBMS. Data models define how
data is connected to each other and how it will be processed and stored inside the system.
4. Compare instance and schema of a database.
In DBMS,Schema is the overall Design of the Database.Instance is the information stored in the
Database at a particular moment.
5. Highlight the intention of ER-model in designing a database.
The whole purpose of ER modelling is to create an accurate reflection of the real world in a
database. It gives us an intermediate step from which it is easy to define a database.
6. What is weak entity set? Is it recommended to have a weak entity set in a relation?
An entity set is a set of entities of the same type that share the same properties. An entity set
that does not possess sufficient attributes to form a primary key is called a weak entity set. One that
does have a primary key is called a strong entity set.
POSTLAB QUESTIONS:
1.

What are the SQL commands used for the following:


i)

To know the current database.


SELECT ORA_DATABASE_NAME;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
ii)

To list down the tables that is available in the current database.


SELECT * FROM TAB;

iii)

To list down the constraints related with a particular table.


SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = '<your table name>'

2. What system table is used to store the list of constraints that were associated with the relations
available in the database?
USER_CONSTRAINTS, ALL_CONSTRAINTS
3. Is it possible to alter referential integrity constraint that was already available with referring another
relation in a table?
YES.
4. Differentiate the operations performed by drop and truncate command.
The DROP command removes a table from the database. All the tables' rows, indexes and
privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will
be fired. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
5. Is it possible to recover the data that were available in a dropped table?
We can recover the dropped table data by invoking a database restore operation,
6. A table is classified as a parent table and you want to drop and re-create it. How would you do this
without affecting the child tables?
This can be done by disable foreign key constraint, drop the parent table and then
recreate the parent table.

RESULT:
Thus the table was successfully created, altered, truncated, and dropped.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
2. DML COMMANDS
AIM:
To insert, select, update and delete records in a table using DML commands.
DML COMMANDS:
COMMANDS OVERVIEW:
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
SQL SELECT FROM
Selecting all records from a table
SELECT * FROM EMPLOYE
Listing the selected records which satisfies the given condition from a table
SELECT * FROM EMPLOYE WHERE DEPTID=DPT01
SQL - INSERT INTO
Syntax:

INSERT INTO tablename VALUES (value list)

Single-row insert
INSERT INTO DEPARTMENT VALUES (DPT02,TESTING,10-JAN-2012)
Inserting one row, with values to the column in the given order
INSERT INTO DEPARTMENT (DEPTNAME, DEPTID) VALUES (DESIGN, DPT02);
Inserting one or more rows with values from other tables.
INSERT INTO DEPARTMENT (DEPTID, DEPTNAME)
SELECT EMPID, EMPNAME

FROM EMP WHERE MGRID=EMPID;

OTHER EXAMPLES:
INPUT::
SQL>INSERT INTO EMPLOYE VALUES (Emp121,Gayle,Testing,Emp01,01-Feb-2013, Dpt01, 32000);
OUTPUT: 1 row created.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
INPUT::
SQL>INSERT INTO DEPARTMENT VALUES(&deptid,&deptname);
Enter value for deptid: Dpt01
Enter value for deptname: Development
OUTPUT:
old
new

1: Insert into department values(&deptid,&deptname)


1: Insert into department values(Dpt01,' Development)

1 row created.

SQL - UPDATE
Syntax: UPDATE tablename SET COLUMN_NAME =value [ WHERE CONDITION]
INPUT::
SQL> UPDATE DEPT SET DOS=01-JAN-2010 WHERE DEPTID=DPT01;
1 row updated.
SQL - DELETE FROM
Syntax: DELETE FROM tablename WHERE condition
INPUT::
SQL> DELETE FROM DEPARTMENT;
OUTPUT: 1 row deleted.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. In which system table the structure of all tables will be stored.
USER_TABLES
2. In which relation the constraints of all tables will be stored.
USER_CONSTRAINTS
3. What is the role of DML compiler in the database architecture?
It translates DML statements in a query language into low-level instruction (Relational Algebra)
that the query evaluation engine can understand.
4. What is the objective of specifying primary key in a relation?
A table typically has a column or combination of columns that contain values that uniquely
identify each row in the table. This column, or columns, is called the primary key (PK) of the table and
enforces the entity integrity of the table. Because primary key constraints guarantee unique data, they
are frequently defined on an identity column.
When you specify a primary key constraint for a table, the Database Engine enforces data
uniqueness by automatically creating a unique index for the primary key columns. This index also
permits fast access to data when the primary key is used in queries
POSTLAB QUESTIONS:
1.

What happens if we try to delete any record present in the parent table and if the same record was
referred by some record in the child table?
We will be getting error message stating
ORA-02292: integrity constraint <constraint name> violated - child record found.

2.

What happens if values were given only for few attributes while inserting a record in a table?
If the missing attributes accept NULL value then the record will be inserted else the record will
not be inserted.

3.

Is it possible to delete a column using delete command?

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
No, because delete is a DML command.
4. Can update command can be used to change the structure of the table.
No, because update command is a DML command.
5. How to add a new constraint to a table using update command?
Update command is a DML command, hence only the records can be updated. The structure cant be
altered.
6. What is the use of Cascade Constraints?
When this clause is used with the DROP command, a parent table can be dropped even when a child
table exists.
7. What is the role of dual table in Oracle?
The DUAL table is a special one-row, one-column table present by default in all Oracle database
installations. It is suitable for use in selecting a pseudo column such as SYSDATE or USER. The table
has a single VARCHAR2(1) column called DUMMY that has a value of 'X'.

RESULT:
Thus the table was successfully inserted, updated, select, and deleted.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

www.Vidyarthiplus.com
3. TCL COMMANDS
AIM:
To create save point, commit and rollback while using a transaction.
TCL COMMANDS:
COMMANDS OVERVIEW
COMMIT - save work done & it is visible to other users.
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
SAVEPOINT
Syntax: savepoint username;
INPUT::
SQL> savepoint emp;
Output:
savepoint created;
COMMIT
Syntax: commit;
INPUT::
SQL> commit;
Output:
Commit complete.
ROLLBACK
Syntax:
rollback to savepoint_text_identifier;
INPUT::
SQL> rollback to emp;
Output:
Rollback complete.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

10

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. What is mean by transaction?
A transaction is a logical unit that is independently executed for data retrieval or updates. In
relational databases, database transactions must be atomic, consistent, isolated and durable-summarized as the ACID acronym.
2. When the updated records will be visible to other users?
The changes (Insertion, deletion or updation) performed by the user will be highlighted to other
user only after performing commit operation.
3. Can the deleted records be recovered using rollback command?
It can be recovered if commit operation was not performed.
4. What is savepoint in Oracle?
The SAVEPOINT statement names and marks the current point in the processing of a transaction.
With the ROLLBACK TO statement, savepoints undo parts of a transaction instead of the whole
transaction.
5. What is the role of buffer manager in DBMS architecture?
A DBMS must manage a huge amount of data, and in the course of processing the required space
for the blocks of data will often be greater than the memory space available. For this there is the need
to manage a memory in which to load and unload the blocks. The buffer manager is responsible
primarily for managing the operations inherent saving and loading of the blocks.
POSTLAB QUESTIONS:
1.

Compare total rollback and partial rollback (Savepoint).


In total rollback, all the changes caused by the transaction will be rollbacked where as in case of
partial rollback, the transaction will be rollbacked till the savepoint.

2. Is it possible to recover a deleted table using rollback command?


The changes caused by DML commands only can be rollbacked and not DDL commands.
3.

Is it possible to have nested transaction?


Yes it is possible.

4.

What is DBMS_TRANSACTION?
The DBMS_TRANSACTION is a package that provides access to SQL transaction statements from
stored procedures.

RESULT:
Thus the table was successfully saved, committed and rollback.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

11

www.Vidyarthiplus.com
4. WRITING AND PRACTICE OF SIMPLE QUERIES
AIM:
To write simple SQL queries and to practice them.
PROBLEM STATEMENTS:
1. Get the description of EMP table.
SQL> DESC EMP;
OUTPUT:
Name
-------------------------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
AGE
ESAL

Null?
Type
----------------------- ------------------------NOT NULL
NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(3)
NUMBER(3)
NUMBER(10)

2.List all employee details.


SQL>SELECT * FROM EMP;
OUTPUT:
EMPNO ENAME
JOB
MGR
HIREDATE SAL
COMM DEPTNO
AGE
ESAL
-------- ---------- --------- ---------- --------- ---------- ---------- ---------- ---------- ----------------7369
SMITH
CLERK
7902 17-DEC-10 8000
0
20
25
0
7499
ALLEN
SALESMAN 7698 20-FEB-11 16000
300
30
25
0
7521
WARD
SALESMAN 7698 22-FEB-11 12500
500
30
25
0
7566
JONES
MANAGER
7839 02-APR-11 29705
500
20
25
0
7698
BLAKE
MANAGER
7839 01-MAY-12 28500
1400
30
25
0
3. List all employee names and their salaries, whose salary lies between 1500/- and 3500/- both inclusive.
INPUT:
SQL>SELECT ENAME FROM EMP WHERE SAL BETWEEN 1500 AND 3500;
OUTPUT:
ENAME
---------ALLEN
JONES
BLAKE
CLARK

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

12

www.Vidyarthiplus.com
4 rows selected.
4. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789.
INPUT: SQL> SELECT ENAME FROM EMP WHERE MGR IN(7602,7566,7789);
OUTPUT:
ENAME
------SCOTT
FORD
5. List all employees which starts with either J or T.
INPUT: SQL> SELECT ENAME FROM EMP WHERE ENAME LIKE J% OR ENAME LIKE T%;
OUTPUT:
ENAME
--------JONES
TURNER
JAMES
6. List all employee names and jobs, whose job title includes M or P.
INPUT: SQL> SELECT ENAME,JOB FROM EMP WHERE JOB LIKE M% OR JOB LIKE P%;
OUTPUT:
ENAME
---------JONES
BLAKE
CLARK
KING

JOB
--------MANAGER
MANAGER
MANAGER
PRESIDENT

7. List all jobs available in employee table.


INPUT: SQL> SELECT DISTINCT JOB FROM EMP;
OUTPUT:
JOB
--------ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
assistant
clerk
7 rows selected.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

13

www.Vidyarthiplus.com
8. List all employees who belongs to the department 10 or 20.
INPUT: SQL> SELECT ENAME FROM EMP WHERE DEPTNO IN (10,20);
OUTPUT:
ENAME
---------SMITH
JONES
CLARK
SCOTT
KING
ADAMS
FORD
MILLER
8 rows selected.
9. List all employee names , salary and 15% rise in salary.
INPUT: SQL> SELECT ENAME , SAL , SAL+0.15* SAL FROM EMP;
RESULT:
ENAME
SAL
------------------SMITH
800
ALLEN
1600
WARD
1250
JONES
2975
MARTIN
1250
BLAKE
2850
CLARK
2450
7 rows selected.

SAL+0.15*SAL
-----------920
1840
1437.5
3421.25
1437.5
3277.5
2817.5

10. List minimum, maximum, average salaries of employee.


INPUT: SQL> SELECT MIN(SAL),MAX(SAL),AVG(SAL) FROM EMP;
OUTPUT:
MIN(SAL)
--------3

MAX(SAL)
---------5000

AVG(SAL)
---------1936.94118

11. Find how many job titles are available in employee table.
INPUT: SQL> SELECT COUNT (DISTINCT JOB) FROM EMP;
OUTPUT:
COUNT(DISTINCTJOB)
-----------------7

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

14

www.Vidyarthiplus.com
12. What is the difference between maximum and minimum salaries of employees in the organization?
INPUT: SQL> SELECT MAX(SAL)-MIN(SAL) FROM EMP;
OUTPUT:
MAX(SAL)-MIN(SAL)
----------------4997
13. Display all employee names and salary whose salary is greater than minimum salary of the company
and job title starts with M.
INPUT: SQL> SELECT ENAME,SAL FROM EMP WHERE JOB LIKE M% AND SAL >
(SELECT MIN (SAL) FROM EMP);
OUTPUT:
ENAME
---------JONES
BLAKE
CLARK

SAL
---------2975
2850
2450

14. Find how much amount the company is spending towards salaries.
INPUT: SQL> SELECT SUM (SAL) FROM EMP;
OUTPUT:
SUM(SAL)
--------32928
15. Display name of the dept. with deptno 20.
INPUT: SQL>SELECT ENAME FROM EMP WHERE DEPTNO = 20;
OUTPUT :
ENAME
---------SMITH
JONES
SCOTT
ADAMS
16. List ename whose commission is NULL.
INPUT: SQL> SELECT ENAME FROM EMP WHERE COMM IS NULL;
OUTPUT:
ENAME
------------

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

15

www.Vidyarthiplus.com
CLARK
SCOTT
KING
ADAMS
JAMES
FORD
6 rows selected.
17. Find no.of dept in employee table.
INPUT: SQL> SELECT COUNT (DISTINCT ENAME) FROM EMP;
OUTPUT:
COUNT(DISTINCT ENAME)
--------------------------------------17
18. List ename whose manager is not NULL.
INPUT: SQL> SELECT ENAME FROM EMP WHERE MGR IS NOT NULL;
OUTPUT:
ENAME
---------SMITH
ALLEN
WARD
JONES
MARTIN
5 rows selected.
19. Calculate the experience in years of each programmer and display along with their name in
descending order.
INPUT: SQL> SELECT PNAME, ROUND (MONTHS_BETWEEN(SYSDATE, DOJ)/12, 2) "EXPERIENCE" FROM
PROGRAMMER ORDER BY MONTHS_BETWEEN (SYSDATE, DOJ) DESC;
20 . In which month most number of programmers has joined.
INPUT: SQL>SELECT TO_CHAR (DOJ,YY) FROM PROGRAMMER GROUP BY TO_CHAR (DOJ,YY) HAVING
COUNT (*) = (SELECT MAX (COUNT(*)) FROM PROGRAMMER GROUP BY TO_CHAR (DOJ,YY);
PRELAB QUESTIONS:
1. Which operator is used for pattern matching?
LIKE - Combine with a string and one or more wildcard characters to find all values with string.
NOT LIKE - Combine with a string and one or more wildcard characters to find all values without
string.
EXISTS - Finds a value from a multivalue group.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

16

www.Vidyarthiplus.com
2. What are the wildcards symbols used for pattern matching?
* (asterisk) Wildcard for any number of characters before or after the value entered. Used in
combination with LIKE.
? (question mark) Wildcard for a single character. Used in combination with LIKE.
3. Which system tables contains information about privileges granted and privileges obtained?
SESSION_PRIVS
POSTLAB QUESTIONS:
1.

What is the purpose of DISTINCT keyword?


The SQL DISTINCT clause is used to remove duplicates from the result set of a SELECT
statement.

2. What is the purpose of DESC keyword?


The DESC keyword is used to sort the fields of a set. The DESC keyword is used in conjunction
with the ORDER BY expression in a SELECT statement.
3. Give the SQL query to find the number of days between two dates?
SELECT TO_DATE(DD-MON-YYYY) - TO_DATE(DD-MON-YYYY) FROM DUAL;
4. What is the purpose of CEIL()?
The Oracle/PLSQL CEIL function returns the smallest integer value that is greater than or equal to
a number.
5.

What is the purpose of TRUNC() with dates as argument?


The Oracle/PLSQL TRUNC function returns a date truncated to a specific unit of measure.
Eg: TRUNC(TO_DATE('22-AUG-03'), 'YEAR')

would return '01-JAN-03'

6. What is TIMESTAMP and what is the purpose of TO_TIMESTAMP()?


Timestamp is an extension of the Date datatype that can store date and time data (including
fractional seconds). The Oracle/PLSQL TO_TIMESTAMP function converts a string to a timestamp.

RESULT:
Thus the given problem statements were solved using simple queries.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

17

www.Vidyarthiplus.com
5. NESTED QUERIES & QUERIES USING GROUP BY AND OTHER CLAUSES
AIM:
To write queries using Set operations, to write nested queries and also to write queries using
clauses such as GROUP BY, ORDER BY, etc. and retrieving information by joining tables.
SET OPERATIONS & OTHER CLAUSES:
NESTED QUERY: - A nested query makes use of another sub-query to compute or retrieve
the information.
UNION

OR

INTERSECT

AND

EXCEPT

NOT

Order by : The order by clause is used to display the results in sorted order.
Group by : The attribute or attributes given in the clauses are used to form groups. Tuples with the
same value on all attributes in the group by clause are placed in one group.
Having: SQL applies predicates (conditions) in the having clause after groups have been formed, so
aggregate function be used.
PROBLEM STATEMENTS:
1. Find the name of the institute in which the person studied and developed the costliest package.
INPUT: SQL> SELECT SPLACE, PNAME FROM STUDY WHERE PNAME = (SELECT PNAME FROM SOFTWARE
WHERE SCOST = (SELECT MAX (SCOST) FROM SOFTWARE);
OUTPUT:
SPLACE
-----------SAHBHARI

PNAME
------------MARY

2. Find the salary and institute of a person who developed the highest selling package.
INPUT: SQL> SELECT STUDY.PNAME, SAL, SPLACE FROM STUDY, PROGRAMMER WHERE
STUDY.PNAME = PROGRAMMER.PNAME AND STUDY.PNAME = (SELECT PNAME FROM SOFTWARE WHERE
SCOST = (SELECT MAX (SCOST) FROM SOFTWARE));
OUTPUT:

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

18

www.Vidyarthiplus.com
PNAME
SAL
----------- -----MARY
4500S

SPLACE
----------ABHARI

3. How many packages were developed by the person who developed the cheapest package.
INPUT: SQL> SELECT PNAME, COUNT (TITLE) FROM SOFTWARE WHERE DCOST = (SELECT MIN(DCOST)
FROM SOFTWARE) GROUP BY PNAME;
RESULT
PNAME
------------VIJAY

COUNT(TITLE)
---------------------1

4. Calculate the amount to be recovered for those packages whose development cost has not yet
recovered.
INPUT: SQL>SELECT TITLE, (DCOST-SCOST) FROM SOFTWARE WHERE DCOST > SCOST;

5. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference.
INPUT: SQL> SELECT TITLE, SCOST, DCOST, (SCOST - DCOST) FROM SOFTWARE DESCENDING ORDER
BY (SCOST-DCOST);

6. Display the details of those who draw the same salary.


INPUT: SQL> SELECT P.PNAME, P.SAL FROM PROGRAMMER P, PROGRAMMER T WHERE P.PNAME <>
T.PNAME AND P.SAL = T.SAL;(OR)
INPUT: SQL>SELECT PNAME,SAL FROM PROGRAMMER T WHERE PNAME<>T.PNAME AND SAL= T.SAL;
7. Display total salary spent for each job category.
INPUT: SQL>SELECT JOB,SUM (SAL) FROM EMP GROUP BY JOB;
OUTPUT:
JOB
SUM(SAL)
-----------------ANALYST
6000
CLERK
23050
MANAGER
8275
PRESIDENT 5000
SALESMAN 5600
assistant
2200

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

19

www.Vidyarthiplus.com
clerk
2003
7 rows selected.
8. Display lowest paid employee details under each manager.
INPUT: SQL>SELECT ENAME, SAL FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMP GROUP BY
MGR);
OUTPUT:
ENAME
SAL
------------------CHAI
3
JAMES
950
MILLER
1000
ADAMS
1100
russel
2200
5 rows selected.
9. Display number of employees working in each department and their department name.
INPUT: SQL> SELECT DNAME, COUNT (ENAME) FROM EMP, DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO
GROUP BY DNAME;
OUTPUT:
DNAME
-------------ACCOUNTING
RESEARCH
SALES

COUNT(ENAME)
-----------3
5
9

10. Display the sales cost of package developed by each programmer.


INPUT: SQL> SELECT PNAME, SUM(SCOST) FROM SOFTWARE GROUP BY PNAME;
OUTPUT:
PNAME
-------------------john
kamala
raju
3 rows selected.

SUM(SCOST)
---------12000
12000
12333

11. Display the number of packages sold by each programmer.


INPUT: SQL>SELECT PNAME, COUNT(TITLE) FROM SOFTWARE GROUP BY PNAME;
OUTPUT:
PNAME
-------------------john
kamala

COUNT(TITLE)
-----------1
1

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

20

www.Vidyarthiplus.com
raju
ramana
rani
5 rows selected.

1
1
1

12. Display the number of packages in each language for which the development cost is less than
thousand.
INPUT: SQL>SELECT DEVIN, COUNT(TITLE) FROM SOFTWARE WHERE DCOST < 1000 GROUP BY DEVIN;
OUTPUT:
DEVIN
COUNT(TITLE)
---------- -----------cobol
1
13. Display each institute name with number of students.
INPUT: SQL> SELECT
OUTPUT:
SPLACE
-------------------BDPS
BITS
BNRILLIANI
COIT
HYD
5 rows selected.

SPLACE, COUNT(PNAME) FROM STUDY GROUP BY SPLACE;


COUNT(PNAME)
-----------2
1
1
1
1

13. How many copies of package have the least difference between development and selling cost, were
sold?
INPUT: SQL>select SOLD FROM SOFTWARE WHERE SCOST DCOST=(SELECT MIN(SCOST DCOST)
FROM SOFTWARE);
OUTPUT:
SOLD
--------11
14. Which is the costliest package developed in Pascal.
INPUT: SQL>SELECT TITLE FROM SOFTWARE WHERE DEVIN = PASCAL AND DCOST = (SELECT
MAX(DCOST) FROM SOFTWARE WHERE DEVIN = PASCAL);
OUTPUT:
no rows selected
15. Which language was used to develop most no .of packages?

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

21

www.Vidyarthiplus.com
INPUT: SQL>SELECT DEVIN, COUNT (*) FROM SOFTWARE GROUP BY DEVIN HAVING COUNT(*)
= (SELECT MAX(COUNT(*) ) FROM SOFTWARE GROUP BY DEVIN);
OUTPUT:
DEVIN
---------jsp

COUNT(*)
---------2

16.Who are the male programmers earning below the average salary of female programmers?
INPUT: SQL>SELECT PNAME FROM PROGRAMMER WHERE SAL < (SELECT AVG(SAL) FROM PROGRAMMER
WHERE SEX = F) AND SEX = M;
OUTPUT:
PNAME
-------------------vijay
17. Display the details of software developed by the male programmers earning more than 3000/-.
INPUT: SQL> SELECT PROGRAMMER.PNAME, TITLE, DEVIN FROM PROGRAMMER, SOFTWARE WHERE SAL
> 3000 AND SEX = M AND PROGRAMMER.PNAME = SOFTWARE.PNAME;
OUTPUT:
no rows selected
18. Display the details of software developed in c language by female programmers of Pragathi.
INPUT: SQL>SELECT SOFTWARE.PNAME, TITLE, DEVIN, SCOST, DCOST, SOLD FROM PROGRAMMER,
SOFTWARE, STUDY WHERE DEVIN = C AND SEX =F AND SPLACE = PRAGATHI AND
PROGRAMMER.PNAME = SOFTWARE.PNAME AND SOFTWARE.PNAME = STUDY.PNAME;

PRELAB QUESTIONS:
1. List out the purpose of EXISTS, SOME & ANY operators in SQL.
EXISTS: The SQL EXISTS condition is used in combination with a subquery and is considered to
be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or
DELETE statement.
ANY: The ANY comparison condition is used to compare a value to a list or subquery. It must be
preceded by =, !=, >, <, <=, >= and followed by a list or subquery.
SOME: The SOME and ANY comparison conditions do exactly the same thing and are completely
interchangeable.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

22

www.Vidyarthiplus.com
2. What is the purpose of ROWID keyword?
An Oracle server assigns each row in each table with a unique ROWID to identify the row in the
table. The ROWID is the address of the row which contains the data object number, the data block of
the row, the row position and data file. Using the ROWID method is generally considered to be the
fastest way to search for a given row in the database.
3. What is the purpose of ROWNUM?
For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the
order in which Oracle selects the row from a table or set of joined rows. The first row selected has a
ROWNUM of 1, the second has 2, and so on.
POSTLAB QUESTIONS:
1.

What happens if a group by query is given with a particular attribute used as group by and the values
in that attribute are distinct?
The number of record in the result will be same as the number of records in that particular
relation.

2.

What is the purpose of Having clause?


A HAVING clause restricts the results of a GROUP BY in a SelectExpression. The HAVING clause is
applied to each group of the grouped table, much as a WHERE clause is applied to a select list. If there
is no GROUP BY clause, the HAVING clause is applied to the entire result as a single group. The
SELECT clause cannot refer directly to any column that does not have a GROUP BY clause. It can,
however, refer to constants, aggregates, and special registers.

3.

Compare union, intersect and minus operators.


All the above operators are set operators in which union combines the given two relations and
whereas intersect gives only those records that were present in both the relation. Minus operators
gives only those records that were present only in first relation.

4.

What will be the output of the below query?


SELECT EMPID, EMPNAME FROM EMPLOYE WHERE EMPID=(SELECT EMPID,EMPNAME FROM EMPLOYE
WHERE MGRID=EMPID)
The above query has an error as the sub query has two attributes which were tried to compare
with a single attribute EMPID.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

23

www.Vidyarthiplus.com
5.

When UNION AND UNION ALL operators can be used?


The SQL UNION ALL operator is used to combine the result sets of 2 or more SELECT statements.
It returns all rows from the query (even if the row exists in more than one of the SELECT statements)
and where as UNION operator omits duplicate records.
6. Compare = and in operators.
Equal to(=) operator is used to compare a attributes value with a single value where as in
operator is used to compare the attributes value with multiple values.

RESULT:
Thus the given problem statements were solved using nested queries and group by & other
clauses.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

24

www.Vidyarthiplus.com
6. PROBLEMS BASED ON VIEWS, SYNONYM, SEQUENCE & INDEX
AIM:
To solve the problem statements based on views, synonym, sequence and Indexes.
OVERVIEW:
VIEW:
A view is simply the representation of a SQL statement that is stored in memory so that it can
easily be re-used. Its also referred as logical table.
SYNTAX:
CREATE OR REPLACE VIEW <view name > AS < select statement >
SYNONYM:
A synonym is an alias or alternate name for a table, view, sequence, or other schema object.
They are used mainly to make it easy for users to access database objects owned by other users.
SYNTAX:
CREATE OR REPLACE SYNONYM <synonym_name> FOR <object_name>
SEQUENCE:
A sequence is a database object from which multiple users may generate unique integers. User
can use sequences to automatically generate primary key values.
INDEXES:
Database system uses indexes to avoid the need for large-table, full-table scans and disk sorts,
which are required when the SQL optimizer cannot find an efficient way to service the SQL query.
SYNTAX:
CREATE INDEX <index_name> ON <table_name(attribute)>

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

25

www.Vidyarthiplus.com
PROBLEM STATEMENTS:
1. Create a view from single table containing all columns from the base table.
SQL>CREATE VIEW VIEW1 AS (SELECT * FROM PROGRAMMER);

2. Create a view from single table with selected columns.


SQL>CREATE A VIEW VIEW2 AS (SELECT PNAME,DOB,DOJ,SEX,SAL FROM PROGRAMMER);

3. Create a view from two tables with all columns.


SQL>CREATE VIEW XYZ AS SELECT * FROM PROGRAMMER FULL NATURAL JOIN SOFTWARE;

4. Create a view from two tables with selected columns.


SQL> CREATE VIEW LMN AS (SELECT PROGRAMMER, PNAME, TITLE, DEVIN FROM PROGRAMMER,
SOFTWARE WHERE SAL < 3000 AND PROGRAMMER.PNAME = SOFTWARE.PNAME);

5. Check all DML commands with above 4 views.


INPUT: SQL> INSERT INTO VIEW1 VALUES (RAMU,12-SEP-03,28-JAN-85 ,F, DBASE, ORACLE,
74000);
OUTPUT:
1 row created;
INPUT: SQL>UPDATE VIEW1 SET SALARY =50000 WHERE PNAME LIKE SARVAN;
OUTPUT:
1 row updated.
Note: update command does not works for all queries on views.
INPUT: SQL>DELETE FROM VIEW1 WHERE PNAME LIKE SMITH;
OUTPUT:
1 row deleted.
7.

Drop views which you generated.

INPUT: SQL>DROP VIEW VIEW1;


OUTPUT:
View dropped.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

26

www.Vidyarthiplus.com
8. Create a synonym for a table created by other user.
SQL> CREATE SYNONYM EMP FOR SP.EMPLOYE;
9. Try to perform all DML operations through the created synonym.
SQL> INSERT INTO EMP VALUES (EMP10,LARA,MAINTENANCE,27-OCT-1998);
OUTPUT:
1 row created.
SQL> UPDATE EMP SET EMPNAME=BRAIN LARA WHERE EMPID=EMP10;
OUTPUT:
1 row Updated.
10. Create a sequence to generate unique value for empid field in the employee table while inserting.
SQL> CREATE SEQUENCE EMP_SEQ
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
OUTPUT:
Sequence Created.
SQL> INSERT INTO EMP VALUES (EMP_SEQ.NEXTVAL,SAHA,TESTING,27-DEC-1999);
OUTPUT:
1 row created;
11. Create index for city attribute in employee table.
SQL> CREATE INDEX EMP_INDEX ON EMP(CITY);
OUTPUT:
Index Created.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

27

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. What are the various Oracle Database objects?
Various database objects are as follows:
Tables This is a set of elements organized in vertical and horizontal fashion.
Tablespaces This is a logical storage unit in Oracle.
Views It is virtual table derived from one or more tables.
Indexes This is a performance tuning method to process the records.
Synonyms This is a name for tables.
Sequences To generate values automatically.
2. Compare implicit index with explicit index that were available in Oracle.
Implicite index is created by oracle Internally ex: when we make a primary key in a Column then
implicit Index created which is Clustered Type index(Default) whereas Explicit index was created by
"Create Index Command' by the Users.
3. How many types of indexes were available in Oracle?
B-tree index, Bitmap index & Function based index.
4. What do you mean by a tablespace?
A tablespace is a container for segments (tables, indexes, etc). A database consists of one or
more tablespaces, each made up of one or more data files. Tables and indexes are created within a
particular tablespace.
5. What are the various types of synonym?
Private & Public synonym.
6. List out the uses of synonym.
Object invisibility: Synonyms can be created to keep the original object hidden from the user.
Location invisibility: Synonyms can be created as aliases for tables and other objects that are not
part of the local database

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

28

www.Vidyarthiplus.com
POSTLAB QUESTIONS:
1. In which system table details about the created views are stored?
USER_VIEWS & DBA_VIEWS
2. List out the limitation of sequences.
Sequences can generate only numerical values.
3. What is the difference between NEXTVAL AND CURRVAL keywords while using sequences in Oracle?
The Oracle NEXTVAL function is used to retrieve the next value in a sequence. The Oracle
NEXTVAL function must be called before calling the CURRVAL function which gives the current value
of the sequence. No current value exists for the sequence until the Oracle NEXVAL function has been
called at least once
4. How do you rebuild an index?
ALTER INDEX <index_name> REBUILD;
5. Whats the advantage of using an index?
Indexes provide quicker access to data blocks.

RESULT:
Thus the given problem statements based on views, synonyms, sequences and indexes were
solved.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

29

www.Vidyarthiplus.com
7. CREATING DATABASE
AIM:
To create database and also to create relationship among database.
COMMAND OVERVIEW:
SYNTAX:
CREATE DATABASE [ database ]
{ USER SYS IDENTIFIED BY password
| USER SYSTEM IDENTIFIED BY password
| CONTROLFILE REUSE
| MAXDATAFILES integer
| MAXINSTANCES integer
| CHARACTER SET charset
| NATIONAL CHARACTER SET charset
| SET DEFAULT
{ BIGFILE | SMALLFILE } TABLESPACE
| database_logging_clauses
| tablespace_clauses
| set_time_zone_clause
};
PROBLEM STATEMENT:
1. Create a new database by the name student_db with required features.
SQL> CREATE DATABASE STUDENT_DB
USER SYS IDENTIFIED BY ORACLE
USER SYSTEM IDENTIFIED BY ORACLE
DATAFILE C:\oracle\oradata\ORA11\SYSTEM01.DBF SIZE 325M REUSE AUTOEXTEND ON NEXT
10240K MAXSIZE UNLIMITED
SYSAUX DATAFILE C:\oracle\oradata\ORA11\SYSAUX01.DAT SIZE 120M REUSE AUTOEXTEND
ON NEXT 5M MAXSIZE 2048M
DEFAULT TABLESPACE USERS DATAFILE C:\oracle\oradata\ORA11\USERS01.DBF SIZE 50M
REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

30

www.Vidyarthiplus.com
PRELAB QUESTION:
1. What is normalization?
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs)
and primary key to achieve the properties
(1).Minimizing redundancy, (2). Minimizing insertion, deletion and update anomalies.
2. 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.

3. 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.
4. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation schemas after
decomposition.
5. Name the three major set of files on disk that compose a database in Oracle.
There are three major sets of files on disk that compose a database. All the files are binary. These are

Database files

Control files

Redo logs

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

31

www.Vidyarthiplus.com
The most important of these are the database files where the actual data resides. The control files and
the redo logs support the functioning of the architecture itself. All three sets of files must be present,
open, and available to Oracle for any data on the database to be useable. Without these files, you
cannot access the database, and the database administrator might have to recover some or all of the
database using a backup, if there is one.
6. What is table space?
A tablespace is a storage location where the actual data underlying database objects can be kept. It
provides a layer of abstraction between physical and logical data, and serves to allocate storage for all
DBMS managed segments.
POSTLAB QUESTION:
1. What is the purpose of UNMOUNT command?
After the database is closed, Oracle un-mounts the database to disassociate it from the instance. At
this point, the instance remains in the memory of your computer. After a database is un-mounted,
Oracle closes the control files of the database.
2. How to know the current database we are working with?
SELECT ORA_DATABASE_NAME FROM DUAL;
3. What ORACLE_SID refers to?
ORACLE_SID - is used to identify the current database instance.
4. How to create table space?
CREATE TABLESPACE <tablespace name>
DATAFILE <location>
SIZE 50M;
5. How to create a user in oracle?
CREATE USER <username> IDENTIFIED BY <password>;
6. How access rights can be granted to a particular user for the newly created database?
GRANT ALL ON <dbname> to <username>;
RESULT:
Thus the database was created with the specified parameters.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

32

www.Vidyarthiplus.com
8. HIGH LEVEL PROGRAMMING LANGUAGE EXTENSION (PL/SQL BLOCKS)
AIM:
To solve the given problem statements using PL/SQL blocks.
PL/SQL BLOCK:
PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and written in
logical blocks of code. Each block consists of three sub-parts:
1. Declarations: This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
2: Executable Commands: This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that nothing should be
executed.
3: Exception Handling: This section starts with the keyword EXCEPTION. This section is again optional and
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL
blocks using BEGIN and END.
SYNTAX:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
PROBLEM STATEMENTS:
REFERED TABLES:
Employe (emp_id,emp_name,dept_id,basic,hra,da,pf,net);

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

33

www.Vidyarthiplus.com
1.

Create a PL/SQL block for inserting values in the Employee table. Only emp_id, emp_name,

department & basic should be received as input while executing the block and for the rest of the fields
the values need to be calculated as given below.
Calculations:
HRA=50% OF BASIC
DA=20% OF BASIC
PF=7% OF BASIC
NETPAY=BASIC+DA+HRA-PF
INPUT:
DECLARE
ENO1 employe.emp_id%type;
ENAME1 employe.emp_name%type;
DEPTNO1 employe.dept_id%type;
BASIC1 employe.basic%type;
HRA1 employe.HRA%type;
DA1 employe.DA%type;
PF1 employe.pf%type;
NETPAY1 employe.net%type;
BEGIN
ENO1:=&ENO1;
ENAME1:='&ENAME1';
DEPTNO1:=&DEPTNO1;
BASIC1:=&BASIC1;
HRA1:=(BASIC1*50)/100;
DA1:=(BASIC1*20)/100;
PF1:=(BASIC1*7)/100;
NETPAY1:=BASIC1+HRA1+DA1-PF1;
INSERT INTO EMPLOYE VALUES (ENO1, ENAME1, DEPTNO1, BASIC1, HRA1, DA1, PF1,

NETPAY1);

END;
OUTPUT:

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

34

www.Vidyarthiplus.com
SQL> @BASIC
Enter value for eno1: 104
old 11: ENO1:=&ENO1;
new 11: ENO1:=104;
Enter value for ename1: SRINIVAS REDDY
old 12: ENAME1:='&ENAME1';
new 12: ENAME1:='SRINIVAS REDDY';
Enter value for deptno1: 10
old 13: DEPTNO1:=&DEPTNO1;
new 13: DEPTNO1:=10;
Enter value for basic1: 6000
old 14: BASIC1:=&BASIC1;
new 14: BASIC1:=6000;
PL/SQL procedure successfully completed.
SQL>/
Enter value for eno1: 105
old 11: ENO1:=&ENO1;
new 11: ENO1:=105;
Enter value for ename1: CIRAJ
old 12: ENAME1:='&ENAME1';
new 12: ENAME1:='CIRAJ';
Enter value for deptno1: 10
old 13: DEPTNO1:=&DEPTNO1;
new 13: DEPTNO1:=10;
Enter value for basic1: 6000
old 14: BASIC1:=&BASIC1;
new 14: BASIC1:=6000;
PL/SQL procedure successfully completed.
SQL> SELECT * FROM EMPDET;
OUTPUT:

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

35

www.Vidyarthiplus.com
EMP_ID EMP_ NAME

DEPT_ID

BASIC

HRA

DA

PF

NETPAY

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

2.

101

GAYLE

10

5000

2500

1000

350

8150

102

SARVAN

20

5000

2500

1000

350

8150

103

POINTING

20

5500

2750

1100

385

8965

104

SMITH

10

6000

3000

1200

420

9780

105

KALIS

10

6000

3000

1200

420

9780

Create a PL/SQL block for updating records in Employe table where the user should provide the
emp_id and the new basic salary and thus the HRA,DA, PF and NETPAY should get calculated and
updated accordingly.

INPUT:
DECLARE
ENO1 employe.emp_id%type;
BASIC1 employe.basic%type;
HRA1 employe.HRA%type;
DA1 employe.DA%type;
PF1 employe.pf%type;
NETPAY1 employe.net%type;
BEGIN
ENO1:=&ENO1;
BASIC1:=&BASIC1;
HRA1:=(BASIC1*50)/100;
DA1:=(BASIC1*20)/100;
PF1:=(BASIC1*7)/100;
NETPAY1:=BASIC1+HRA1+DA1-PF1;
UPDATE EMPLOYE SET BASIC=BASIC1, HRA=HRA1, DA=DA1, PF=PF1, NETPAY=NETPAY1 WHERE
EMP_ID=ENO1;
END;
OUTPUT:
SQL>/

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

36

www.Vidyarthiplus.com
Enter value for eno1: 105
old 11: ENO1:=&ENO1;
new 11: ENO1:=105;
Enter value for basic1: 8000
old 14: BASIC1:=&BASIC1;
new 14: BASIC1:=8000;
PL/SQL procedure successfully completed.
3. Create a PL/SQL block for showing the new netpay after getting new basic salary for a particular
employee. Display the new netpay along the old netpay without updating in the table. Also If no
customer found with the given customer id then show appropriate error message.
INPUT:
DECLARE
ENO employe.emp_id%type;
BASICNW employe.basic%type;
HRANW employe.HRA%type;
DANW employe.DA%type;
PFNW employe.pf%type;
NETPAY employe.net%type;
NETPAYNW employe.net%type;
BEGIN
ENO:=&ENO;
BASICNW:=&BASICNW;
HRANW:=(BASICNW*50)/100;
DANW:=(BASICNW*20)/100;
PFNW:=(BASICNW*7)/100;
NETPAY1:=BASICNW+HRA1+DA1-PF1;
SELECT NET INTO NETPAY FROM EMPLOYE WHERE EMP_ID=ENO;
DBMS_OUTPUT.PUT_LINE(EN0||

|| NETPAY || || NETPAY1);

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO SUCH EMPLOYEE.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('ERROR');
END;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

37

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. What is the difference between SQL & PL/SQL?
SQL is a database language that allows us to directly interact with the database. We can write
queries (SELECT), manipulate objects (DDL) and data (DML) with SQL. However, SQL doesn't include
all the things that normal programming languages have, such as loops and IF...THEN...ELSE
statements.
PL/SQL is a normal programming language that includes all the features of most other
programming languages. But, it has one thing that other programming languages don't have: the
ability to easily integrate with SQL.
2.

What are the components of a PL/SQL Block?


Declarative part, Executable part and Exception part.

3.

What are the datatypes a available in PL/SQL?


Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.

4. What are the control statements available in PL/SQL?


Just like other programming language, Oracle lets you process the data using conditional,
iterative, and sequential flow-of-control statements such as IF-THEN-ELSE, CASE, FOR-LOOP, WHILELOOP, EXIT-WHEN, and GOTO.
POSTLAB QUESTIONS:
1. What package can be used to display messages through the PL/SQL?
DBMS_OUTPUT
2. What is the purpose of the following command?
SET SERVEROUTPUT ON;
By default, SQL*PLUS doesn't prints what a PL/SQL program has written with dbms_output. With
set serveroutput on, this behavior is changed.
3.

What is an Exception? What are types of Exception?


Exception is the error handling part of PL/SQL block. The types are Predefined and user_defined.
Some of Predefined execptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

38

www.Vidyarthiplus.com
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.

RESULT:
Thus PL/SQL statements were written for inserting & updating the rows in the EMPLOYE table.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

39

www.Vidyarthiplus.com
9. PROCEDURES
AIM:
To solve the given problem statements using procedures.
PL/SQL PROCEDURES:
An Oracle stored procedure is a program stored in an Oracle database. The following are the
advantages of using procedures.
Better performance: Oracle stored procedures load once into the shared pool and remain there
unless they become paged out. Subsequent executions of the Oracle stored procedure are far faster than
executions of external code.
Coupling of data with behaviour: DBAs can use naming conventions to couple relational tables
with the behaviors associated with a table by using Oracle stored procedures as "methods". If all
behaviors associated with the employee table are prefixed with the table name--employee.hire,
employee.give_raise, for example--the data dictionary can be queries to list all behaviors associated with
a table (select * from dba_objects where owner = 'EMPLOYEE'), and it's easy to identify and reuse code
via stored procedures.
Isolation of code: Since all SQL is moved out of the external programs and into the Oracle stored
procedures, the application programs become nothing more than calls to Oracle stored procedures. As
such, it becomes very simple to swap out one database and swap in another one.
SYNTAX:
CREATE [OR REPLACE] PROCEDURE procedure_name (parameters list)
IS
<declaration_section>
BEGIN
<executable_section>
EXCEPTION
<exception_section>
END;
PROBLEM STATEMENTS:
REFERRED TABLES:
Borrow(acc_no , rollno, date_issue);

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

40

www.Vidyarthiplus.com

1. Write a procedure to insert a record in borrower relation. Before inserting check whether the book
is available or not.
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR, DOI DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO;
IF(CNT=0)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI);
ELSE
DBMS_OUTPUT.PUT_LINE(BOOK NOT AVAILABLE);
END IF;
END;

OUTPUT:
SQL> @ e:\proc.sql;
Procedure Created.
SQL> exec pro1(123,CS01,27-OCT-2013);
Procedure successfully completed.
SQL> SELECT * FROM BORROW;
ACC_NOROLLNO

DOI

----------

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

123
128

CS01
CS10

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

27-OCT-2013
18-OCT-2013

2. Write a procedure to insert a record in borrower relation with the above constraints and also
ensure that the member has not borrowed more than three books.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

41

www.Vidyarthiplus.com
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR, DOI DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO;
IF(CNT=0)
THEN
SELECT COUNT(*) INTO CNT1 FROM BORROW WHERE ROLLNO=ROLL;
IF(CNT1<4)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI);
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE(BOOK NOT AVAILABLE);
END IF;
END;

OUTPUT:
SQL> @ e:\proc.sql;
Procedure Created.

PRELAB QUESTIONS:
1.

What is a stored procedure?


In a database management system (DBMS), a stored procedure is a precompiled set of Structured
Query Language (SQL) statements that can be shared by a number of programs.

2.

What is a stand-alone procedure?

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

42

www.Vidyarthiplus.com
Procedures that are not part of a database are known as stand-alone procedure because they are
independently defined. These types of procedures are not available for reference from other Oracle
tools. Another limitation of stand-alone procedures is that they are complied at run time, which
slows the execution.
3.

What are the modes of parameters that can be passed to a procedure?


IN,OUT,IN-OUT parameters.

4.

What are advantages of Stored Procedures?


Extensibility, Modularity, Reusability, Maintainability and one time compilation.

POSTLAB QUESTIONS:
1. How to find the list of procedures that were available in the database?
SELECT OBJECT_NAME FROM ALL_OBJECTS WHERE OBJECT_TYPE=PROCEDURE;
2. What are the purposes and advantages stored procedure?

Manage, control and validate data

It can also be used for access mechanisms

Large queries can be avoided

Reduces network traffic since they need not be recompiled

Even though the stored procedure itself may be a complex piece of code, we need not write it over
and over again. Hence stored procedures increases reusability of code

Permissions can be granted for stored procedures. Hence, increases security.

Result:
Thus PL/SQL Procedures were created to solve the given problem statements.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

43

www.Vidyarthiplus.com
10. FUNCTIONS
AIM:
To solve the given problem statements using PL/SQL functions.

PL/SQL FUNCTION:
A PL/SQL function is same as a procedure except that it returns a value. A standalone function is
created using the CREATE FUNCTION statement.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name (parameter_name [IN | OUT | IN OUT] type [, ...])
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END;

PROBLEM STATEMENT:
REFERRED TABLES:
Transaction (accno number(5), amount number(7,2), trans_type varchar(5),dot date);
1. Create a function to insert the records into the transaction table, after performing each transaction
in the transaction table show the net balance of the particular account.
CREATE OR REPLACE FUNCTION FUNC_TRANS (ACC_ID NUMBER,AMNT NUMBER,TYPE VARCHAR)
RETURN NUMBER
IS
BALANCE NUMBER;
BEGIN
INSERT INTO TRANSACTION VALUES(ACC_ID,AMNT,TYPE);
SELECT SUM(AMNT) INTO BALANCE FROM TRANSACTION WHERE ACC_NO=ACC_ID;
RETURN BALANCE;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

44

www.Vidyarthiplus.com
END;

PL/SQL FUNCTION:
DECLARE
BALANCE_AMNT NUMBER(6);
ACC_NO VARCHAR(5);
AMNT NUMBER(5);
TYPE VARCHAR(2);
RESULT NUMBER(5);
BEGIN
ACC_NO:=&ACC_NO;
AMNT:=&AMNT;
TYPE:=&TYPE;
BALANCE_AMNT:=FUNC1(ACC_ID,AMNT,TYPE);
DBMS_OUTPUT.PUT_LINE(TOTAL AMOUNT || TOTAL_AMNT);
END;

OUTPUT:
SQL> @E:\SQL\FUNCPLSQL.SQL;
Enter value for accno: 001
Enter value for amt: 25000
Enter value for type=CRDT
RESULT 26000
PL/SQL procedure successfully completed.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

45

www.Vidyarthiplus.com
PRELAB QUESTIONS:
1. What is difference between a PROCEDURE & FUNCTION?
A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
2. How do we call a function normally?
Can be called from a PL/SQL block.
var:functionname(arg);
DBMS_OUTPUT.PUT_LINE(functionname(arg));
3. Give the basic structure of function definition.
CREATE OR REPLACE FUNCTION <function name> ( <parameters list>)
RETURN <TYPE>
IS
BEGIN
RETURN <value>;
EXCEPTION
WHEN others THEN
RETURN NULL;
END;

POSTLAB QUESTIONS:
1. How a function can be called from a SELECT statement?
SELECT <function name> FROM DUAL;
2. Name the tables where the characteristics of functions are stored?
USER_OBJECTS, USER_SOURCE AND USER_ERROR

RESULT:
Thus PL/SQL functions were created to solve the given problem statements.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

46

www.Vidyarthiplus.com
11.TRIGGERS
AIM:
To solve the given problem statements using triggers.
PL/SQL TRIGGERS:
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions.
SYNTAX:
CREATE OR REPLACE TRIGGER < trigger_name >
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name]
ON < table_name >
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN < condition >
DECLARE
< Declaration-statements >
BEGIN
< Executable-statements >
EXCEPTION
< Exception-handling-statements >
END;

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

47

www.Vidyarthiplus.com
PROBLEM STATEMENT:
REFERRED TABLES:
Account ( accnt_no,cst_id,acnt_type,last_trans_date,balance )
Account_bckup(accnt_no,last_trans_date,balance)
Loan (ln_id,cst_id,ln_amount,ln_date);
1.

Create a trigger for Account relation such that whenever a record is inserted in the Account table

the same record also gets inserted in the backup table.


CREATE OR REPLACE TRIGGER TRIG_ACNT_BCKUP AFTER INSERT ON ACCOUNT
FOR EACH ROW
DECLARE
BEGIN
INSERT INTO ACCOUNT_BCKUP VALUES (:NEW.ACCNT_NO, :NEW.LAST_TRANS_DATE,
:NEW.BALANCE);
END;
OUTPUT:
SQL> @e:/plsql/accnt_trig.sql
Trigger Created.
SQL> INSERT INTO ACCOUNT VALUES (AC010,CST011,SVNG,27-AUG-2013,12000);
1 Row inserted.
SQL> SELECT * FROM ACCOUNT_BCKUP;
ACCNO

LAST_TRANS_DATE BALANCE

----------

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

AC010

2.

27-AUG-2013

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

12,000

Create a trigger for account relation such that whenever account record is inserted in account

relation with negative relation then that record should also be inserted in the loan relation with positive
balance.
CREATE OR REPLACE TRIGGER TRIG_LOAN AFTER INSERT ON ACCOUNT

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

48

www.Vidyarthiplus.com
FOR EACH ROW
DECLARE
BEGIN
IF(:NEW.BALANCE<0)
THEN
INSERT INTO LOAN VALUES (:NEW.ACCNT_NO, :NEW.CST_ID, -(:NEW.BALANCE), SYSDATE);
END IF;
END;

OUTPUT:
SQL> @e:/plsql/loan_trig.sql
Trigger Created.
SQL> INSERT INTO ACCOUNT VALUES (AC011,CST011,SVNG,27-DEC-2013,-8000);
1 Row inserted.
SQL> SELECT * FROM LOAN;
LN_ID

CST_ID

LN_AMOUNT LN_DATE

----------

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

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

AC010

CST011

8000

----------------30-DEC-2013

PRELAB QUESTIONS:
1. What is trigger in oracle?
Triggers are constructs in PL/SQL that need to be just created and associated with a table. Once
they are created, when the table associated with it gets updated due to an UPDATE, INSERT or a
DELETE, the triggers get implicitly fired depending upon the instructions passed to them.
2. What are the various types of triggers?
Row Level Trigger: Row Level Trigger is fired each time row is affected by Insert, Update or
Delete command. If statement doesnt affect any row, no trigger action happens.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

49

www.Vidyarthiplus.com
Statement Level Trigger: This kind of trigger fires when a SQL statement affects the rows of the
table. The trigger activates and performs its activity irrespective of number of rows affected due to
SQL statement.
3.

How the triggers are attached to the table?


When we write a trigger, we also have to give the reference of the table the trigger has to be
fired on. The Data Dictionary too is used for this purpose. The view includes the trigger body, WHEn
clause, triggering table, and trigger type.

4.

Describe triggers features and limitations.


Trigger features:Can execute a batch of SQL code for an insert, update or delete command is executed.
Business rules can be enforced on modification of data.
Trigger Limitations:Does not accept arguments or parameters.
Cannot perform commit or rollback.
Can cause table errors if poorly written.

5.

Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database


Trigger? Why?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a
trigger, it affects logical transaction processing.

6.

What are cascading triggers?


At times when SQL statement of a trigger can fire other triggers. This results in cascading
triggers. Oracle allows around 32 cascading triggers. Cascading triggers can cause result in abnormal
behavior of the application.

7.

Compare Triggers vs. Declarative Integrity Constraints


Triggers and declarative integrity constraints can both be used to constrain data input. However,
triggers and integrity constraints have significant differences. A declarative integrity constraint is a
statement about the database that is never false while the constraint is enabled. A constraint applies
to existing data in the table and any statement that manipulates the table. Triggers constrain what
transactions can do. A trigger does not apply to data loaded before the definition of the trigger.
Therefore, it does not guarantee all data in a table conforms to its rules.

POSTLAB QUESTIONS:
1.

What is RAISE_APPLICATION_ERROR?
RAISE_APPLICATION_ERROR is a procedure of package DBMS_STANDARD which allows to issue
an user_defined error messages from stored sub-program or database trigger.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

50

www.Vidyarthiplus.com
2.

Give the sql statement to list the triggers associated with a particular table.
SELECT TRIGGER_NAME FROM ALL_TRIGGERS WHERE TABLE_NAME = <table name>;

3.

How to disable and enable triggers?


DISABLE TRIGGER <trigger name>;
ENABLE TRIGGER <trigger name>;

4.

How to drop a trigger?


DROP TRIGGER <trigger name>;

5.

What are two virtual tables available during database trigger execution?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only available.

6.

What happens if a procedure that updates a column of table X is called in a database trigger of the
same table?
Mutation of table occurs.

7.

8.

Write the order of precedence for validation of a column in a table?

done using Database triggers.

done using Integarity Constraints.

What are the instances when triggers are appropriate?

When security is the top most priority. i.e. to allow unauthorized access

When backups are essential

When Maintenance is desired. Triggers can be fired when any error message is logged

Keeping the database consistent.

Result:
Thus the triggers were created accordingly to solve the given problem statements.

CS6312 - DATABASE MANAGEMENT SYSTEMS LAB

www.Vidyarthiplus.com

51

Das könnte Ihnen auch gefallen