Section 2 Dbms Lab: Structure Page Nos
Section 2 Dbms Lab: Structure Page Nos
2.0 INTRODUCTION
Information Technology (IT) has influenced organisational performance and
competitive standing. The increasing processing power and sophistication of
analytical tools and techniques require a strong foundation of structured form of data.
Thus, the presence of a commercial, secure, reliable database management system is
the major requirement of businesses.
This section is an attempt to familiarise you with commercial database management
features, so that you are able to apply some of the important features of DBMS in a
commercial situation. This would require a sound background of the concepts of
DBMS which can be acquired through the courses MCS-023: Introduction to DBMSs
and MCS-043: Advanced DBMSs. You would also have to apply the conceptual
background to obtain problem solving skills using a commercial DBMS. The topics
that have been included in this section are sub-queries, joins, views, indexes,
41
Lab Manual embedded languages including cursors, triggers, and some advanced features like
object tables, nested tables, user management etc.
Please note that we have given many examples in this lab section in different sessions,
highlighting the basic syntax of various statements; however, they are not exhaustive,
as commercial DBMSs implement a large number of statements and functions.
Therefore, you must refer to the user reference manuals of the commercial DBMS for
more details on these topics. Also, we have given the examples for a typical DBMS;
however, you may do practicals on any commercial RDBMS supporting such
concepts. However, you should find the changes in the statements used here for the
DBMS you may be using. Remember, the objectives of this section consisting of ten
sessions will be completed only if you practice using any commercial DBMS.
2.1 OBJECTIVES
After going through this section and performing all the practical exercises you should
be able to:
42
Single-Row Subquery DBMS Lab
Single-row subquery is the query that returns only one value or row to the calling
SELECT statement. For example:
Query 1: Display the name of the teacher who is oldest among all teachers.
Explanation: To know the name of the teacher who is oldest, you need to first find
the minimum birth date and then corresponding to that date display the name of the
teacher.
SELECT f_name, l_name
FROM teacher
WHERE birthdate = (SELECT MIN(birthdate)
FROM teacher);
Query 2: Display teacher numbers and names of those teachers who are earning less
than ‘Jatin’.
Explanation: To find the list of teachers earning less than ‘Jatin’, you need to find
first the salary of ‘Jatin’.
SELECT t_no, f_name, l_name
FROM teacher
WHERE salary < (SELECT salary
FROM teacher
WHERE UPPER(f_name) = ‘JATIN’);
Multiple-Row Subquery
Multiple-row subqueries are the queries that return only more than one value or rows
to the calling SELECT statement. For example:
Query 3: Display the list of all teachers who are earning equal to any teacher who
have joined before ‘31-dec-94’
Explanation: First you need to know the salaries of all those who have joined before
‘31-dec-94’ and then any teacher whose salary matches any of these returned salaries.
IN operator looks for this existence into the set. You can also use Distinct to avoid
duplicate salary tuples.
SELECT t_no, f_name, l_name
FROM teacher
WHERE salary IN (SELECT salary
FROM teacher
WHERE joindate < ‘31-dec-94’);
Query 4: Display the list of all those teachers whose salary is greater than any other
teacher with job title ‘PRT’.
Explanation: First you need to know the salaries of all those who are ‘PRT’ and then
any teacher whose salary is greater than any of these returned salaries. ANY operator
looks for inequality.
SELECT t_no, f_name, l_name, salary
FROM teacher
WHERE salary > ANY (SELECT salary
FROM teacher
WHERE UPPER (title) = ‘PRT’);
Query 5: Display the list of all those teachers whose salary is greater than all the
teachers with job title as ‘PRT’.
Explanation: First you need to know the salaries of all those who are ‘PRT’ and then
any teacher whose salary is greater than all of these returned salaries. ALL operator
looks for inequality.
SELECT t_no, f_name, l_name, salary
FROM teacher
WHERE salary > ALL (SELECT salary
43
Lab Manual FROM teacher
WHERE UPPER(title) = ‘PRT’);
Multiple-Column subquery
Multiple-Column subquery is the subquery that returns more than one column to the
calling or main SELECT statement. For example:
Query 6: Display the list of all teachers whose job title and salary is same as that of
the employee whose first name is ‘Jaideep’.
Explanation: Firstly you need to find the job title and salary of ‘Jaideep’ and then
you need to find all other teachers whose job title and salary exactly matches
Jaideep’s job title and salary.
SELECT t_no, f_name,l_name, title, salary
FROM teacher
WHERE (title, salary) = (SELECT title, salary
FROM teacher
WHERE LOWER(f_name) = ‘jaideep’);
Correlated Subqueries
This is another type of subquery where the subquery is executed for each and every
record retrieved by the calling or main SELECT statement. A correlated subquery
returns only a Boolean value (true/false). A true is returned if the subquery returns
one or more records otherwise a false is returned. The operator EXISTS can be used
for these types of subqueries. For example:
Query 7: Display the records in the format given below for all class teachers:
Jaideep Kumar is a class teacher
Explanation: The main query uses the EXISTS operator to find whether the teacher is
a class teacher or not. If the correlated subquery returns a true value, then the record
retrieved by main SELECT statement is accepted otherwise it is rejected.
SELECT f_name, l_name, ‘is a class teacher’
FROM teacher
WHERE exists (SELECT *
FROM class
WHERE class.t_no = teacher.t_no)
2.2.2 Joins
Joins means retrieving data from more than one table in a single query. There are
several types of joins:
1) Equijoin – In this type of join, two or more tables are joined over common
columns and common values. For example:
Query 8: Display names of all the teachers who are class teachers.
44
DBMS Lab
SELECT f_name, l_name
FROM teacher t, class c
WHERE t.t_no = c.t_no;
2) Non-Equijoin - In this type of join, two or more tables do not have common
columns and common values but they are joined indirectly. For example:
Query 9: Display names, salaries and salary grades of all teachers.
SELECT f_name, l_name, salary, grade
FROM teacher, payscale
WHERE salary BETWEEN min_limit AND max_limit;
3) Outer join - In this type of join, two or more tables are joined over common
column but the records may or may not have common values. For example:
Query 10: Display names and class numbers of all the teachers. In addition
display the classes of those teachers who are class teachers. Thus, the result
should include names of teachers who are not class teachers.
SELECT f_name, l_name, class_no
FROM teacher t, class c
WHERE t.t_no = c.t_no (+) ;
4) Self join - In this type of join, the table is joined to itself. For example:
Query 11: Display teacher number and names of all teachers along with the
names of their supervisors and number. Please note that the supervisor of a
teacher is also a teacher. Therefore, the query requires a self-join.
SELECT t.f_name, t.l_name, t.supervisor, s.f_name, s.l_name
FROM teacher t, teacher s
WHERE t.supervisor = s.t_no;
5) Cartesian join – In this type of join, each record of one table is joined to each
record of the other table i.e., the join condition is not given. For example:
Query 12: Show all possible teacher – class values.
SELECT f_name, l_name, class_no
FROM teacher t, class c;
2.2.3 Exercise 1
1) Please attempt the following problems for the teacher, class and payscale
relations given in this section.
(a) Display the name of the teacher(s) who is (are) the youngest among all
the teachers.
(b) Display details of all the teachers who have the same job title as that of
‘Jaideep’
(c) Display the list of all the teachers who have joined after ‘10-Jul-95’ and
whose salary is equal to that of any of the teachers who joined before
‘10-Jul-95’.
(d) Use a correlated query to determine the teachers who are not class
teachers.
(e) Identify all those teachers who are in grade ‘B’.
(f) Display the names and numbers of all teachers who are class teachers and
are in grade ‘C’.
(g) Display the names of all teachers who are supervisors.
(h) Display the teacher id and salaries of all those teachers who are in grade
‘A’ or ‘C’ and who have at least two L’s in their names.
45
Lab Manual (i) Display details of all those teachers who are class teachers of classes 1 to
5.
(j) Display the names of all teachers along with their dates of birth whose
birthday is in the current month.
2) In an Open University a student’s data is to be maintained using relations. The
university maintains data of all the students, their batches, Regional Centres and
study centre details. Each batch of students has one or more representative
students. The batches are taught by same or different faculty.
(a) Design and implement the suitable relations for the University. Make and
state suitable assumptions.
(b) Write at least 15 queries (they must include at least one query of each
type given in this section 2.2) for the database. Implement these queries
using SQL. Also explain the purpose of each query.
3) Design a suitable database system for a bank along with 20 possible queries to
the database (the queries should be such that their solution involves subqueries
or joins or both). Implement the database and the queries in a commercial
DBMS using SQL.
46
Example 1: Create a view that displays teacher number, the names of teachers along DBMS Lab
with salary, job title, age and grade.
CREATE VIEW teacher_details
AS SELECT t_no, f_name||’ ‘||l_name as name, title, salary,
trunc(months_between(sysdate,birthdate)/12,0) age, grade
FROM teacher , payscale
WHERE salary BETWEEN min_limit AND max_limit;
Let us make a few queries on this view.
Query (a): Display teacher number, their names, age and grade of all PGT
teachers.
SELECT t_no, name, age, grade
FROM teacher_details
WHERE UPPER (title) = ‘PGT’;
Query (b): Display details of all the teachers who are more than 40 years old.
SELECT t_no, name, salary, title, age
FROM teacher_details
WHERE age > 40;
To remove a view, DROP statement is used. For example:
DROP VIEW teacher_details;
2.3.2 Indexes
Index is the Oracle object that reduces the record-retrieval time. An index contains the
Rowid and the values of the target columns. A rowid is a pointer that determines the
location of the record. Indexes can be based on one or more table columns. Two types
of indexes can be created:
1. Unique indexes - These indexes are created automatically whenever a
PRIMARY KEY or UNIQUE constraint is defined.
2. Non-unique indexes - These indexes are created explicitly by the user on non-
unique keys.
Syntax:
CREATE INDEX index_name
ON tablename (column1 , column2 ,………);
Example 2: Create an index on the relation teacher on the job title for fast access.
CREATE INDEX t_title_index
ON teacher(title);
To remove an index, drop statement is used. For example,
DROP INDEX t_title_index;
2.3.3 Exercise 2
1) Please attempt the following problems for the teacher, class and payscale
relations given in this section.
(a) Create a view named ‘supervisor_details’ that stores the names and
numbers of all the supervisors.
(b) Create a non-unique index on the foreign key column of the ‘class’ table.
(c) Modify the view created in (a) and add details like salary, job title,
joining date, birth date etc. of all supervisors.
(d) Using the view created in (c) display details of all supervisors who have
worked for more than 15 years.
(e) Create a view that stores the details of all the teachers who are TGT and
earning more than Rs.12000/-.
(f) Drop the view created in (e).
47
Lab Manual (g) Create a non-unique index on the names of teachers in the ‘teachers’
table.
(h) Drop the index created in (b).
(i) Create a view named ‘teacher_info’ that only allows users to view the
teacher id, name, salary and grade of the teachers. It should not allow any
user to change/update any information.
(j) Create a view that displays details of all teachers who are in grade ‘B’
and are more than 40 years old.
2) Design suitable views for the University database system (Exercise 1, question
2). For example, you can create a view for the faculty giving him/her details of
his/her students. Create at least 5 suitable queries on each of the views created
by you. Also create indexes for the University database system. For example,
you can create an index on student name, thus, allowing faster access to student
information in the order of student names. You must explain how the indexes
created by you would enhance the performance of the database system.
Implement the above in a commercial DBMS using SQL.
3) Design suitable views and indexes for the Bank database system (Exercise 1,
question 3). Create at least 5 suitable queries on each of the views. Explain how
the indexes created by you would enhance the performance of the database
system. Implement the above in a commercial DBMS using SQL.
48
BEGIN DBMS Lab
LOOP
i := i + 1;
IF i = 100 THEN
EXIT;
END IF;
END LOOP;
END;
This loop structure is an extension of the basic LOOP structure along with an
additional control statement tagged at the front of the LOOP keyword. By default the
loop increments the control variable starting from the lower index and going up to the
higher index value. The REVERSE clause is used to make the loop decrement the
control variable from highest to lowest index value. For example:
Example 5: In this example, the ‘counter’ will start from 100 and reach 1.
DECLARE
a NUMBER := 1;
lower_index := 1;
upper_index := 100
BEGIN
FOR counter IN REVERSE lower_index .. upper_index
LOOP
49
Lab Manual a := a + (counter * 5);
END LOOP;
END;
WHILE Loops
This loop structure is also an extension of basic LOOP and the statements are iterated
based upon a condition test. If condition is true then the loop is executed otherwise
not.
Example 6: A quantity can be issued if the total amount is below a sanctioned
amount.
DECLARE
qty NUMBER := 1;
sanctioned_amt NUMBER := 1000;
unit_price NUMBER := 10;
tot_amt NUMBER := 0;
BEGIN
WHILE tot_amt < sanctioned_amt
LOOP
tot_amt := unit_price * qty;
qty := qty + 1;
END LOOP;
END;
2.4.2 Procedures
PL/SQL procedure is a named program block i.e., logically grouped set of SQL and
PL/SQL statements that perform a specific task. They can be invoked or called by any
PL/SQL block. The syntax is:
CREATE OR REPLACE PROCEDURE name
(argument {IN, OUT, INOUT} data type, ……..)
IS
Variables declarations;
BEGIN
PL/SQL subprogram body
EXCEPTION
Exception PL/SQL block
END procedure name;
Replace: if procedure is already created then replace it.
IN : Indicates that the parameter will accept a value from the user.
OUT : Indicates that the parameter will return a value to the user.
INOUT : Indicates that the parameter will either accept from or return a value to the
user.
Example 7: Following procedure searches the name of a teacher in the relation
teacher
CREATE OR REPLACE PROCEDURE search_teacher
(o_t_no IN NUMBER,
o_f_name OUT VARCHAR2,
o_l_name OUT VARCHAR2)
IS
BEGIN
SELECT f_name, l_name
FROM teacher
WHERE t_no = o_t_no;
END search_teacher;
run; /* it is used to create the procedure */
50
To call this procedure: DBMS Lab
DECLARE
o_f_name teacher.f_name%TYPE;
o_l_name teacher.l_name%TYPE;
BEGIN
search_teacher( 113, o_f_name, o_l_name);
DBMS_OUTPUT.PUT_LINE(‘Employee : 113’);
DBMS_OUTPUT.PUT_LINE(‘Name : ’|| o_f_name || ‘ ‘ || o_l_name);
END;
Example 8: To demonstrate use of INOUT parameter
CREATE PROCEDURE bonus_calc
(o_t_no IN INTEGER,
bonus INOUT INTEGER)
IS
join_date DATE;
BEGIN
SELECT salary * 0.20, joiningdate INTO bonus, join_date
FROM teacher
WHERE t_no = o_t_no;
IF MONTHS_BETWEEN(SYSDATE, join_date) > 36 THEN
bonus := bonus + 1000;
END IF;
END;
Important Notes:
2.4.3 Exercise 3
1) Please perform the following using the following relations:
Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
(b) Using a simple LOOP structure, list the first 10 records of the ‘teachers’
table.
(c) Create a procedure that selects all teachers who get a salary of Rs.20, 000
and if less than 5 teachers are getting Rs.20, 000 then give an increment
of 5%.
51
Lab Manual (d) Create a procedure that finds whether a teacher given by user exists or
not and if not then display “teacher id not exists”.
(e) Using FOR loop, display name and id of all those teachers who are more
than 58 years old.
(f) Using while loop, display details of all those teachers who are in grade
‘A’.
(g) Create a procedure that displays the names of all those teachers whose
supervisor is ‘Suman’.
(h) Calculate the tax to be paid by all teachers depending on following
conditions:
I. if annual salary > 1,00,000 then no tax.
II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the
annual salary.
III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the
annual salary.
IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.
(i) Create a procedure that finds the names of all teachers with the job title
‘PRT’ and if the number of teachers returned is more than 10 than change
the job title to ‘TGT’ for the top 3 ‘PRT’ teachers based on their hiredate.
2) Identify the need of procedures for the University database system; for
example, you can create a procedure that awards 2% grace marks for those
students who have got 48% marks. Design at least 5 such procedures.
Implement these procedures using an embedded SQL.
3) Implement at least five procedures for the Bank Database system using
embedded SQL.
2. Explicit cursors
An explicit cursor is defined as a SELECT statement within PL/SQL block. The
general syntax is:
CURSOR cursorname IS
SELECT statement;
52
There are a number of actions performed on explicit cursors. They are: - DBMS Lab
ATTRIBUTE DESCRIPTION
%ROWCOUNT Returns the number of rows processed by an SQL statement.
%FOUND Returns TRUE if at least one row was processed.
%NOTFOUND Returns TRUE if no rows were processed.
Return TRUE if cursor is open or FALSE, if cursor has not
%ISOPEN been opened or has been closed. Only used with explicit
cursors.
Example 1: Implicit cursor
DECLARE
total_row_del NUMBER;
BEGIN
DELETE * FROM teacher WHERE salary < 10000;
total_row_del := SQL%ROWCOUNT;
END;
Example 2: Explicit Cursor
DECLARE
c_t_no teacher.t_no%TYPE;
c_f_name teacher.f_name%TYPE;
c_l_name teacher.l_name%TYPE;
c_salary teacher.salary%TYPE;
CURSOR c1 IS
SELECT t_no,f_name, l_name, salary
FROM teacher;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO c_t_no, c_f_name, c_l_name, c_salary ;
EXIT WHEN NOT c1%FOUND;
UPDATE teacher SET salary = salary * 1.10 WHERE salary > 20000;
END LOOP;
CLOSE c1;
END;
Example 3: Explicit Cursor using record name in FOR loop
DECLARE
CURSOR c2 IS
SELECT t_no,f_name, l_name, salary
FROM teacher ;
53
Lab Manual teacher_rec c2%ROWTYPE;
BEGIN
OPEN c2;
FOR teacher_rec IN c2
LOOP
IF teacher_rec.salary > 20000
Teacher_rec.title = “SUPERVISOR”;
ENDIF;
END LOOP;
CLOSE c2;
END;
2.5.2 Exercise 4
1) Please perform the following using the following relations:
Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)
Class(class_no, t_no, room_no)
Payscale(Min_limit, Max_limit, grade)
(a) Create a host language block to declare a cursor for displaying teacher
numbers and their names for all teachers having title ‘PGT’.
(b) Create a host language block using a cursor to calculate bonus for
teachers as 5% of their salary. Display on screen the teacher details along
with the bonus given.
(c) Write a host language block to delete all the rows from the ‘teacher’ table
where the salary is less than Rs.5000.
(d) Write a host language code to insert the supervisor information from
‘teacher’ table to another table called ‘supervisor’. The new table should
have only those records where the job title is ‘supervisor’.
(e) Write a block in host language that deletes all the rows from ‘teacher’
table if the teacher was hired for more than 10 years.
(f) Write a block in host language using cursor that displays the names of all
teachers who will attain the age of 60 years in the current year.
(g) Write a block in host language using cursors that display teacher details
along with the tax to be paid by that teacher. The tax is calculated
depending on following conditions:
I. if annual salary < 1,00,000 then no tax.
II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the
annual salary.
III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the
annual salary.
IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.
(h) Write a block in host language that displays the details of all those
teachers who have reached maximum limit of their grade.
2) Write at least four embedded SQL blocks having cursors for the University
database system; for example, you can create a cursor to update the examination
marks of a student that are given in a list to the student’s database. Implement
these procedures using an embedded SQL.
3) Implement at least five embedded SQL blocks having cursors for the Bank
Database system.
54
DBMS Lab
2.6 SESSION 5: ERROR HANDLING AND
TRANSACTION MANAGEMENT
Objectives
At the end of this session you should be able to:
• perform basic error handling
• use commit, rollback and save point specifications.
2.6.1 Error Handling
Exceptions are identifiers that are raised during the execution of a PL/SQL block to
terminate its action in case of a problem, error or abnormal condition. A block is
always terminated when PL/SQL raises an exception but we can also capture
exceptions by defining our own error handlers and perform some final actions before
quitting the block.
2) User-defined: These are defined by the user and raised when specifically
requested within a block. If an error occurs within a block PL/SQL passes
control to the EXCEPTION section of the block. If no EXCEPTION section
exists in the block or the EXCEPTION section cannot handle the error then the
block is terminated with an unhandled exception. Exceptions execute through
nested blocks until an exception handler is found that can handle the error. If no
exception handler is found in any block the error is passed out to the host
environment. Exceptions occur implicitly when either an Oracle error occurs or
you explicitly raise an error using the RAISE statement.
Example 1: Predefined Exception
DECLARE
C_id teacher.t_no%TYPE;
C_f_name teacher.f_name%TYPE;
want_id NUMBER := 110;
BEGIN
SELECT t_no, f_name INTO c_t_no, c_f_name from teacher
WHERE t_no = want_id;
DBMS_OUTPUT.PUTLINE ( “teacher : “|| c_t_no ||’ ‘||c_f_name)
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUTLINE(want_id || ‘ not a valid teacher id’);
END;
Example 2: User Defined Exception
DECLARE
C_title teacher.title%TYPE;
CURSOR c_teacher IS
SELECT t_no,f_name, l_name, title
FROM teacher;
55
Lab Manual C_teacher_row c_teacher%ROWTYPE;
BEGIN
C_title := ‘PGT’;
FOR c_teacher_row IN c_teacher
LOOP
EXIT WHEN c_teacher%NOTFOUND;
DECLARE
emptytitle EXCEPTION;
BEGIN
IF c_teacher_row IS NULL THEN
RAISE emptytitle;
ELSE
DBMS_OUTPUT.PUTLINE (c_teacher_row.f_name,
c_teacher_l_name, c_teacher_title);
ENDIF;
EXCEPTION
WHERE emptytitle THEN
DBMS_OUTPUT.PUTLINE(c_teacher_row.f_name);
END;
END LOOP;
CLOSE c_teacher;
END;
2.6.2 Transaction Management
A transaction is a logical unit of work that is composed of one or more Data
Manipulation Language (DML) or Data Definition Language (DDL) or Data Control
Language (DCL) statements. A transaction starts when an SQL statement is executed
and terminates when any of the following occurs:
• Any DDL or DML statement is executed.
• A COMMIT or ROLLBACK statement is given
• User exits SQL.
The transactions can be committed implicitly or explicitly. All DDL or DCL
statements are implicitly committed.
There are three explicit transaction specifications:
1) COMMIT: It ends the current transaction and saves permanently all pending
changes since last saved or COMMIT or ROLLBACK. The syntax is:
COMMIT;
2) SAVEPOINT: It marks and saves the current point of the transaction process. It
is useful to perform partial rollbacks. The syntax is:
SAVEPOINT name;
3) ROLLBACK: It ends the transaction but discards all pending changes since
last commit or save point. The syntax is:
ROLLBACK [ TO SAVEPOINT name];
Example:
SQL > UPDATE teacher SET title = ‘PGT’ WHERE salary > 15000;
SQL> COMMIT
/* Changes made by Update statement are saved */
SQL> INSERT INTO class(class_no, t_no, room_no) VALUES (10,127,226);
SQL> ROLLBACK;
56
/* values inserted into ‘class’ table are discarded */ DBMS Lab
SQL> UPDATE teacher SET title = ‘SUPERVISOR’ WHERE salary > 20000;
SQL> SAVEPOINT update_done;
/* savepoint created */
SQL> DELETE FROM teacher;
SQL> ROLLBACK TO SAVEPOINT update_done;
/* just delete statement is discarded */
2.6.3 Exercise 5
1) Write an embedded SQL block along with exceptions to select the name of the
teacher with a given salary. If more than one row is returned than display more
than one row retrieved. If no row is returned then display ‘no teacher with this
salary’.
2) Create a program that updates a record into the ‘teacher’ table. Trap and handle
the exception if the teacher id is not available in the ‘teacher’ table.
3) Write a program with exceptions that displays the details of all those teachers
who have reached maximum limit of their grade. If no row is retrieved then
raise the exception “no teacher reached max limit of grade”.
4) Insert at least 5 new rows in the ‘teacher’ table and then try to rollback last 3
rows inserted to the table. (Here, you are required to use save points).
5) Write a program with exceptions that displays the names of all teachers who
will attain the age of 60 years in the current year. If no row is retrieved than
display suitable exception.
6) Write a PL/SQL block that displays all the rows from ‘teacher’ table if the
teacher was hired for more than 10 years and still a ‘PRT’. If no result than
display suitable message.
7) In all the embedded SQL program segments that you have created so far for the
University and Bank database system, create suitable error handling features.
8) Experiment with DDL and DML commands along with COMMIT and
ROLLBACK for the Teacher, University and Banking databases.
57
Lab Manual 1) STATEMENT type - STATEMENT triggers fire BEFORE or AFTER the
execution of the statement that caused the trigger to fire.
2) ROW type - ROW triggers fire BEFORE or AFTER any affected row is
processed.
FORCE++ -Tells Oracle that you want to drop a type even if there are other objects
with dependencies on it. Even if you use FORCE, you can only drop a type if it has
not been implemented in a table; you must first drop the table(s) before dropping the
type.
Example 1: Declaring a point type consisting of two numbers:
CREATE TYPE pointtype AS OBJECT (
a NUMBER,
b NUMBER
);
/
This object type can be used like any other type in further declarations of object-types
or table-types.
Example 2: Defining a line type by using previously created object type.
CREATE TYPE linetype AS OBJECT (
x pointtype,
y pointtype
);
/
These objects can further be used to create a table that is a set of lines with ``line ID's''
a
Example 3: Create object table
Note: Before dropping a type, drop all tables and other types that use this type.
Constructing Object Values
Oracle provides built-in constructors for values of a declared type with the name of
the type.
Example 4 : Inserting a new row in the Object table ‘line’ for a line from co-ordinates
(0,0) to (4,5).
2.8.2 Exercise 7
1) Assuming that in the teacher relation an attribute of object type called
dependent is added. Make dependent a type that may consist of only one
dependent. Add few records in the tables and output them using a query on
teacher name. Find if you can search on a dependent name.
2) Create at least two object types in both the University and Bank database
systems. Use these object types in few relations and enter some data into these
relations. Query these databases.
61
Lab Manual • define and create nested tables
• initialize nested tables.
Example:
DBMS_OUTPUT.PUT_LINE('my_table(2) is '||my_table(2));
END;
/
The table can also be initialized as:
Functions Description
DELETE deletes one or more elements in the collection - an optional start and
end point specify which elements are to be deleted
EXISTS(n) determines if the specified element has been created and not deleted,
returns TRUE if the element exists, FALSE if not
FIRST returns the subscript of the first element in the nested table
LAST returns the subscript of the last element in the nested table
PRIOR returns the subscript of the previous element in the nested table
NEXT returns the subscript of the next element in the nested table
2.9.2 Exercise 8
1) Add a nested table in the teacher relation. Do some queries using nested tables?
2) Create at least two nested tables for both the University and Bank database
systems. Use these tables and enter some data into these relations. Query these
databases.
• Populated: A LOB instance with a locator and a value exists in the cell.
64
BEGIN DBMS Lab
These user accounts are of use when the privileges are given to them. There are two
types of privileges:
1) System privilege: This kind of privilege allows a user to use DDL Commands
like CREATE TABLE, DROP INDEX etc.
2) Object privilege: This kind of privilege allows a user to use DML Commands
like UPDATE, INSERT etc.
To give and take back the privileges to user accounts, we use GRANT and REVOKE
command respectively.
65
Lab Manual Example 2: Give CREATE and DROP privileges related to table/view to the user
account ‘manager’.
1) Create a user account “class” and give privileges related to table/view creation,
deletion, updating and dropping.
2) Create a student account and give permission to this account for only viewing
the information on the relation Class (class_no, t_no, room_no.
3) Create at least 3 to 4 different types of users for each of the database systems:
University and Bank. Design suitable access privileges for the users. Grant
these permissions to the users.
4) Consider when you have a large number of students and teachers in the
University databases that have different access rights. Is there any mechanism
in DBMS that allows defining an account type to some specific role? If yes,
then define such types for the University database system.
5) Define different types of users for the Bank database and provide them suitable
access rights.
2.12 SUMMARY
This section has tried to broadly cover about ten different aspects of a commercial
DBMS. We have covered practical sessions relating to sub-queries and join based
queries, creating views, indexes and performing queries on them, embedded SQL with
or without the use of cursors, error handling during the embedded SQL operations and
using COMMIT and ROLLBACK commands used for transactions. We have also
done sessions on triggers and functions, creating types, nested tables, BLOBs and user
management.
You should try to solve not only the problems given in these exercises, but also many
more problems during your practical sessions. You should consult online
help/reference manuals of the commercial DBMS you are using while solving the
problems. Practice is the key for achieving the basic objectives of the sessions.
Finally, please keep in mind the fact that the basic objective of this section is NOT to
make you an expert DBA, but it is to give you a feel of many different types of things
that you may be able to do with a DBMS. You should look forward to applying your
theoretical knowledge of MCS-023 and MCS-043 along with the skills obtained
during the practical sessions to create solutions with respect to the needs of various
business organisations.
66