0% found this document useful (0 votes)
10 views57 pages

DBMSLabManua_Final

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views57 pages

DBMSLabManua_Final

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

DEPARTMENT OF INFORMATION TECHNOLOGY

DBMS
LAB Manual

Prepared by

VIDYA SAGARA REDDY.T M.Tech


Asst Professor – IT

VAAGDEVI INSTITUTE OF TECHNOLOGY & SCIENCE


PEDDASETTIPALLI ,PRODDATUR,
KADAPA. PIN: 516 361.
Department of Information Technology DBMS Lab Manual

TABLE OF CONTENTS

S. No Topic Page No
1 LAB OBJECTIVES 3
2 INTRODUCTION 4
3 SQL INTRODUCTION 5
4 SQL COMMANDS 6
5 SYNTAX’S OF COMMAND 7
6 CREATE,INSERT,UPDATE, DELETE, RENAME, TRUNCATE, ON TABLES 9
7 CREATING AND DROPING OF VIEWS 18
8 TRIGGERS 20
9 INTRODUCTION TO PL/SQL 23
10 CREATION OF FORMS 31
11 GENERATING REPORTS 36
12 REFERRENCES 43
13 VIVA VOICE QUESTIONS AND ANSWERS 43

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 2


Department of Information Technology DBMS Lab Manual

LAB OBJECTIVES

A vast majority of the software applications being built use some kind of a data store mechanism
to permanently store the data generated/used by the software. Database management systems are
complex software systems that provide a wide variety of functionality for users to structure,
organize and access data quickly and efficiently. Database systems have been there since the early
1970’s but have grown in complexity and size. Relational database management systems use
relational algebra as the basis for representation of data. RDBMS as relational database
management systems are the most popular and widely used DBMS in the market place.

In this lab, you would be exposed to one popular RDBMS. The broad one line objective of the lab
is to get familiar with the functionality and support provided by commercially popular RDBMS
and understand how to use it to meet your data storage and organization requirements.

Detailed objectives of the lab are:

• You learn SQL (Structured Query Language) which would provide functionality to:
o Learn how to create tables which are fundamental storage blocks of data.
o Learn how to place constraints on data that is entered on tables to ensure data
integrity.
o Learn how to add, change and remove data from tables.
o Learn how to select a subset of the data you want to see from the collection of
tables and data.
o Learn how to combine table and group multiple rows of data in table.
• You learn PL/SQL which would provide the ability to do iterative programming at
database level to:
o Write programming blocks with conditionals, assignments, loops, etc
o Exception Handling.
o Transaction oriented programs
o Stored procedures, functions, packages.
o Cursors which would allow row wise access of data.
o Triggers which would allow you define pre and post actions when something
changes in the database tables.

At the end of the lab, you should be comfortable using any popular RDBMS for data access
and updating and should be comfortable writing PL/SQL programs at database level using
Oracle.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 3


Department of Information Technology DBMS Lab Manual

INTRODUCTION

RDBMS is one of the most widely used pluggable software components in most enterprise
software applications. Though RDBMS applications have been there since the early 1970s, they
have improved tremendously in terms of their features, the size of data they can hold, and the
complexity over the last 20 years.

Oracle is one of the very widely used commercial RDBMS systems and at this point is the market
leader as far as RDBMS is concerned. Oracle9i is RDBMS software which supports SQL – 1999.
It also supports programming language extension to SQL called PL/SQL which is Oracle
proprietary and is very popular to do program development at the database server level. Other
popular DBMS software like Sybase and SQL Server support their own programming extensions
to SQL – 1999.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 4


Department of Information Technology DBMS Lab Manual

SQL

SQL (Structured Query Language) is a standard supported by all the popular relational database
management systems in the market place. The basis data structure in RDBMS is a table. SQL
provides you the features to define tables, define constraints on tables, query for data in table, and
change the data in table by adding, modifying, and removing data. SQL also supports grouping of
data in multiple rows, combining tables and other features. All these put together, SQL is a high-
level query language standard to access and alter data in RDBMS.

Querying for Data:


The typical syntax to query for data is;

SELECT clause
FROM clause
WHERE clause

There are of course a few other additions to these standard clauses.

• GROUP BY
• HAVING

Querying can be used to: To retrieve existing data from database.


• Get all data from the table
• Get selected columns from the table.
• Get selected rows from the table.
• Get selected columns of selected rows from the table.
• Get computed columns using char, number, data functions, general functions, and
aggregating functions.
• Get data in multiple rows grouped on an aggregating function applied on one or more
columns.
• Select specific aggregating data on multiple rows using having clause.
• Apply set operations like Union and Intersection on data sets of the same cardinality and
type.
• Get data from multiple tables using Cartesian product, equality join, un-equal join, and
outer join.
• Create views on physical data.

Data Definition Language (DDL): To do with altering the structure of data base.
• Create tables.
• Create Indexes on tables.
• Alter tables
• Add constraints to tables.
• Drop tables.
• Truncate tables.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 5


Department of Information Technology DBMS Lab Manual

• Drop indexes.
• Create sequences.

Data Manipulation Language (DML): To do with adding, updating, and deleting data from tables.
• Insert Data
• Update Data
• Delete Data
• Merge Tables.

Data Control Language (DCL): To do with controlling access to data in tables.


• Grant Permissions
• Revoke Permissions
• Create and update roles.
• Add users to roles.

As you can see from above, SQL gives you all the tools needed to define your database in the form
of table, define integrity constraint rules on table to ensure data integrity, change the database as
needed and control permissions on tables at a very fine granular level.

SQL – 1999 is the standard which is supported by all commercial database vendors. If your
queries are using SQL – 1999 standard, they will run all RDBMS servers. In addition to the SQL –
1999 standard, most commercial databases have their own extensions to SQL supported by them.
In the interest of portability, it would be good if we stick with SQL – 1999 standard in our
querying no matter what RDBMS we are using unless we have a strong reason to go for additional
features not included in SQL – 1999 standard.

SQL COMMANDS

SQL Consisting of DDL,DML,DCL,TCL COMMANDS.

DDL

Data Definition Language (DDL) statements are used to define the database structure or schema.
DDL Commands: Create , Alter ,Drop , Rename, Truncate

CREATE - to create objects in the database


ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
RENAME - rename an object

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 6


Department of Information Technology DBMS Lab Manual

DML

Data Manipulation Language (DML) statements are used for managing data within schema objects

DML Commands: Insert ,Update, Delete, Select

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
SELECT - retrieve data from the a database

DCL

Data Control Language (DCL) statements is used to create roles, permissions, and referential
integrity as well it is used to control access to database by securing it.

DCL Commands: Grant, Revoke

GRANT - gives user's access privileges to database


REVOKE - withdraw access privileges given with the GRANT command

TCL

Transaction Control (TCL) statements are used to manage the changes made by DML statements.
It allows statements to be grouped together into logical transactions.

TCL Commands: Commit, Rollback, Save point

COMMIT - save work done


SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT

SYNTAX’S OF COMMANDS

CREATE TABLE

CREATE TABLE table_name


(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
);

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 7


Department of Information Technology DBMS Lab Manual

ALTER A TABLE

To add a column in a table

ALTER TABLE table_name


ADD column_name datatype;

To delete a column in a table

ALTER TABLE table_name


DROP COLUMN column_name;

DROP TABLE

DROP TABLE table_name;

TRUNCATE TABLE

TRUNCATE TABLE table_name;

INSERT

INSERT INTO table_name


VALUES (value1, value2, value3,...);

( OR )

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...);

UPDATE

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value;

DELETE

DELETE FROM table_name


WHERE some_column=some_value;

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 8


Department of Information Technology DBMS Lab Manual

SELECT

SELECT column_name(s)
FROM table_name;

CREATE,INSERT , UPDATE, DELETE, RENAME, TRUNCATE, ON TABLES

SQL>CREATE TABLE STUDENT(SNO NUMBER(5),SNAME VARCHAR2(15),DOJ DATE);

OUTPUT:-TABLE CREATED

SQL> INSERT INTO STUDENT100VALUES(&SNO,'&SNAME','&DOJ');

OUTPUT:-

Enter value for sno: 501


Enter value for sname: ABI
Enter value for doj: 12-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(501,'ABI','12-OCT-07')

1 row created.

SQL> /

Enter value for sno: 502


Enter value for sname: ASHOK
Enter value for doj: 03-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(502,'ASHOK','03-OCT-07')

1 row created.

SQL> /

Enter value for sno: 503


Enter value for sname: BHAVYA
Enter value for doj: 10-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(503,'BHAVYA','10-OCT-07')

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 9


Department of Information Technology DBMS Lab Manual

1 row created.
SQL> /

Enter value for sno: 504


Enter value for sname: AKASH
Enter value for doj: 05-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(504,'AKASH','05-OCT-07')

1 row created.
SQL> /

Enter value for sno: 505


Enter value for sname: NIKHIL
Enter value for doj: 08-OCT-07
old 1: INSERT INTO STUDENT100 VALUES(&SNO,'&SNAME','&DOJ')
new 1: INSERT INTO STUDENT100 VALUES(505,'NIKHIL','08-OCT-07')

1 row created.

SQL> RENAME STUDENT TO CSESTUDENT;

OUTPUT:-Table renamed.

SQL>SELECT * FROM CSESTUDENT;

OUTPUT:-

SNO SNAME DOJ


---------- --------------- ---------
501 ABI 12-OCT-07
502 ASHOK 03-OCT-07
503 BHAVYA 10-OCT-07
504 AKASH 05-OCT-07
505 NIKHIL 08-OCT-07

SQL> UPDATE CSESTUDENT SET SNAME='ABILASH' WHERE SNAME='ABI';

OUTPUT:-1 row updated.

SQL> ALTER TABLE CSESTUDENT ADD BRANCH VARCHAR2(6);

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 10


Department of Information Technology DBMS Lab Manual

OUTPUT:-Table altered.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=501;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=502;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=503;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=504;

OUTPUT:-1 row updated.

SQL> UPDATE CSESTUDENT SET BRANCH='CSE' WHERE SNO=505;

OUTPUT:-1 row updated.

SQL> SELECT * FROM CSESTUDENT;

SNO SNAME DOJ BRANCH


---------- --------------- --------- ------
501 ABILASH 12-OCT-07 CSE
502 ASHOK 03-OCT-07 CSE
503 BHAVYA 10-OCT-07 CSE
504 AKASH 05-OCT-07 CSE
505 NIKHIL 08-OCT-07 CSE

SQL> DELETE FROM CSESTUDENT WHERE SNO=501;

OUTPUT:-1 row deleted.

SQL> SELECT * FROM CSESTUDENT;

OUTPUT:-

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 11


Department of Information Technology DBMS Lab Manual

SNO SNAME DOJ BRANCH


---------- --------------- --------- ------
502 ASHOK 03-OCT-07 CSE
503 BHAVYA 10-OCT-07 CSE
504 AKASH 05-OCT-07 CSE
505 NIKHIL 08-OCT-07 CSE
502 ASHOK 03-OCT-07 CSE

SQL> DROP TABLE CSESTUDENT;

OUTPUT:-Table dropped.

CREATING TABLES WITH CONSTRAINTS

(NOT NULL)

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) NOT NULL,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> DESC STUD;


Name Null? Type
----------------------------------------- -------- ----------------------------
ROLLNO NOT NULL NUMBER(6)
NAME VARCHAR2(10)
BRANCH VARCHAR2(6)

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: ABHILASH
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'ABHILASH','CSE')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 12


Department of Information Technology DBMS Lab Manual

1 row created.

SQL> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ------
501 ABHILASH CSE
502 ABI CSE

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

(UNIQUE)

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) UNIQUE ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

1 row created.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 13


Department of Information Technology DBMS Lab Manual

SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated

(PRIMARY KEY)

SQL> CREATE TABLE STUD(ROLLNO NUMBER(6) PRIMARY KEY ,NAME


VARCHAR2(10),BRANCH VARCHAR2(6));

Table created.

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno: 501
Enter value for name: abhilash
Enter value for branch: cse
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')

1 row created.

SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 14


Department of Information Technology DBMS Lab Manual

new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')


INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated

SQL> INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH');


Enter value for rollno:
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(,'BHAVYA','CSE')
INSERT INTO STUD VALUES(,'BHAVYA','CSE')
*
ERROR:CANNOT INSERT NULL INTO("SCOTT",'STUD',ROLLNO)

SQL> SELECT * FROM STUD;

ROLLNO NAME BRANCH


---------- ---------- ------
501 ABHILASH CSE
502 ABI CSE

(CHECK)

SQL> create table stud(rno number(5),name varchar2(10),sal number(10) constraint no_ck


check(sal between 10000 and 30000));

Table created.

SQL> insert into stud values(&rno,'&name',&sal);


Enter value for rno: 567
Enter value for name: sachin
Enter value for sal: 29000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(567,'sachin',29000)

1 row created.

SQL> /
Enter value for rno: 565
Enter value for name: rohit
Enter value for sal: 35000
old 1: insert into stud values(&rno,'&name',&sal)

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 15


Department of Information Technology DBMS Lab Manual

new 1: insert into stud values(565,'rohit',35000)


insert into stud values(565,'rohit',35000)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.NO_CK) violated

( FOREIGN KEY )
SOL>create table adm(stuid number(6) constraint stuid_pk primary key,sname varchar2(15),per
number(5));

Table created.

SQL> insert into adm values(&stuid,'&sname',&per);


Enter value for stuid: 1
Enter value for sname: abi
Enter value for per: 80
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(1,'abi',80)

1 row created.

SQL> /
Enter value for stuid: 2
Enter value for sname: rohit
Enter value for per: 89
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(2,'rohit',89)

1 row created.

SQL> /
Enter value for stuid: 3
Enter value for sname: sachin
Enter value for per: 99
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(3,'sachin',99)

1 row created.

SQL> /
Enter value for stuid: 4
Enter value for sname: naveen
Enter value for per: 70
old 1: insert into adm values(&stuid,'&sname',&per)

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 16


Department of Information Technology DBMS Lab Manual

new 1: insert into adm values(4,'naveen',70)

1 row created.

SQL> select * from adm;

STUID SNAME PER


---------- --------------- ----------
1 abi 80
2 rohit 89
3 sachin 99
4 naveen 70

SQL> create table course(stuid number(6) constraint sid_fk references adm(stuid),branch


varchar2(5),sec varchar2(10));

Table created.

SQL> insert into course values(&stuid,'&branch','&sec');


Enter value for stuid: 1
Enter value for branch: cse
Enter value for sec: a
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(1,'cse','a')

1 row created.

SQL> /
Enter value for stuid: 5
Enter value for branch: cse
Enter value for sec: b
old 1: insert into course values(&stuid,'&branch','&sec')
new 1: insert into course values(5,'cse','b')
insert into course values(5,'cse','b')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SID_FK) violated - parent key not found

SQL> delete from adm where stuid=1;


*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.SID_FK) violated - child record found

SQL> delete from course where stuid=1;

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 17


Department of Information Technology DBMS Lab Manual

1 row deleted.

SQL> delete from adm where stuid=1;

1 row deleted.

SQL>select * from adm;

STUID SNAME PER


----- --------------- - ----------
2 rohit 89
3 sachin 99
4 naveen 70

CREATING AND DROPING OF VIEWS

SQL> select * from emp2;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hollywood
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> create view emp22 as select * from emp2;

OUTPUT:-

View created.

SQL> select * from emp22;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hollywood
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> update emp22 set city='hyd' where ename='coyote';

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 18


Department of Information Technology DBMS Lab Manual

OUTPUT:-

1 row updated.

SQL> select * from emp2;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hyd
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> select * from emp22;

OUTPUT:-

ENAME STREET CITY


-------------------- -------------------- --------------------
coyote toon hyd
rabbit tunnel carrot ville
smith revolver death valley
williams sea view sea attle

SQL> drop table emp2;

OUTPUT:-
Table dropped.

SQL> select * from emp22;

OUTPUT:-

select * from emp22

ERROR at line 1:
ORA-04063: view "SCOTT.EMP22" has errors

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 19


Department of Information Technology DBMS Lab Manual

TRIGGERS

What are triggers?


A trigger is a PL/SQL block or a PL/SQL procedure associated with a table, view, schema, of the
database. It executes implicitly whenever a particular event takes place. It can either be:

1. Application trigger: Fires whenever an event occurs with a particular application.


2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.

When should we use triggers?


Triggers are to be used when we want to perform related actions and when we want to centralize
global operations. Create stored procedures and invoke them in a trigger, if the PL/SQL code is
very lengthy. The excessive use of triggers can result in complex interdependencies, which may be
difficult to maintain in large applications. Triggers should not be used where functionality needed
is already built into the Oracle server or when it is duplicating what is done by other triggers.

Example:
A trigger called check_sal which runs every time a new employee is getting inserted to enforce
some rules on what should be the minimum salary.

Elements in a Trigger:
• Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
• Trigger event: INSERT, UPDATE, OR DELETE
• Table name: On table, view
• Trigger Type: Row or statement
• When clause: Restricting condition
• Trigger body: PL/SQL block

“Before triggers” execute the trigger body before the triggering DML event on a table. These are
frequently used to determine whether that triggering statement should be allowed to complete.
This situation enables you to eliminate unnecessary processing of the triggering statement and it
eventual rollback in cases where an exception is raised in the triggering action.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 20


Department of Information Technology DBMS Lab Manual

“After triggers” are used when the triggering statement is to be completed before the triggering
action and to perform a different action on the same triggering statement if a BEFORE trigger is
already present.

“Instead of Triggers” are used to provide a transparent way of modifying views that cannot be
modified directly through SQL DML statements because the view is not inherently modifiable.
You can write INSERT, UPDATE, and DELETE statements against the view. The INSTEAD OF
trigger works invisibly in the background performing the action coded in the trigger body directly
on the underlying tables.

Triggering user events:


o INSERT
o UPDATE
o DELETE

Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering event. A row
trigger is not executed if the triggering event affects no rows.

Trigger Body:
The trigger body is a PL/SQL block or a call to a procedure.

Syntax:

CREATE [OR REPLACE] TRIGGER trigger_name


Timing
Event1 [OR event2 OR event3]
ON table_name
Trigger_body

Example: To write a TRIGGER to ensure that DEPT TABLE does not contain duplicate of
null values in DEPTNO column.
INPUT
CREATE OR RELPLACE TRIGGER trig1 before insert on dept for each row
DECLARE
a number;
BEGIN
if(:new.deptno is Null) then
raise_application_error(-20001,'error::deptno cannot be null');
else
select count(*) into a from dept where deptno=:new.deptno;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate deptno');
end if;

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 21


Department of Information Technology DBMS Lab Manual

end if;
END;
RESULT:
SQL> @trigger
Trigger created.
SQL> select * from dept;
DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> insert into dept values(&deptnp,'&dname','&loc');
Enter value for deptnp: null
Enter value for dname: marketing
Enter value for loc: hyd
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(null,'marketing','hyd')
insert into dept values(null,'marketing','hyd')

ERROR at line 1:
ORA-20001: error::deptno cannot be null
ORA-06512: at "SCOTT.TRIG1", line 5
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 10
Enter value for dname: manager
Enter value for loc: hyd
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(10,'manager','hyd')
insert into dept values(10,'manager','hyd')

ERROR at line 1:
ORA-20002: error:: cannot have duplicate deptno
ORA-06512: at "SCOTT.TRIG1", line 9
ORA-04088: error during execution of trigger 'SCOTT.TRIG1'
SQL> /
Enter value for deptnp: 50
Enter value for dname: MARKETING
Enter value for loc: HYDERABAD
old 1: insert into dept values(&deptnp,'&dname','&loc')
new 1: insert into dept values(50,'MARKETING','HYDERABAD')
1 row created.
SQL> select * from dept;
DEPTNO DNAME LOC
--------- -------------- -------------

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 22


Department of Information Technology DBMS Lab Manual

10 ACCOUNTING NEW YORK


20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

INTRODUCTION TO PL/SQL

PL/SQL is the procedural extension to SQL with design features of programming languages. Data
manipulation and query statements of SQL are included within procedural units of code.

Benefits of PL/SQL:

PL/SQL can improve the performance of an application. The benefits differ depending on the
execution environment:

• PL/SQL can be used to group SQL statements together within a single block and to send
the entire block to the server in a single call thereby reducing networking traffic. Without
PL/SQL, the SQL statements are sent to the Oracle server one at a time. Each SQL
statement results in another call to the Oracle server and higher performance overhead. In a
network environment, the overhead can become significant.
• PL/SQL can also operate with Oracle server application development tools such as Oracle
forms and Oracle reports.

PL/SQL Block Structure:

Every unit of PL/SQL comprises one or more blocks. These blocks can be entirely separate or
nested one within another. The basic units (procedures, functions, and anonymous blocks) that
make up a PL/SQL program are logical blocks which can contain any number of nested sub-
blocks. Therefore one block can represent a small part of another block, which in turn can be part
of the whole unit of code.

Modularized program development:


• Group logically related statements within blocks.
• Nest sub-blocks inside larger blocks to build powerful programs.
• Break down a complex problem into a set of manageable well defined logical modules and
implement the modules with blocks.
• Place reusable PL/SQL code in libraries to be shared between Oracle forms and Oracle
reports, applications, or store it in a Oracle server to make it accessible to any application
that can interact with an Oracle database.

Identifiers/Variables:
In PL/SQL, you can use identifiers to do the following:

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 23


Department of Information Technology DBMS Lab Manual

• Declare variables, cursors, constants and exceptions and then use them in SQL and
procedural statements.
• Declare variables belonging to scalar, reference, composite and large object (LOB) data
types.
• Declare variables dynamically based on the data structure of tables and columns in the
database.

Procedural Language Control Structures:


• Execute a sequence of statements conditionally.
• Execute a sequence of statements iteratively in a loop.
• Process individually the rows returned by a multiple row query with a cursor.

Errors:
• Process Oracle server error with exception-handling routines.
• Declare user-defined error conditions and process them with exception-handling routines.

PL/SQL Block Syntax:


DECLARE [Optional]
Variables, cursors, user defined exceptions
BEGIN [Mandatory]
- SQL Statements –
- PL/SQL Statements –
Exception [Optional]
-- Actions to be performed when errors occur ----
END [Mandatory];

Example:
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT column_name
INTO v_variable
FROM table_name;
EXCEPTION
WHEN exception_name THEN
-
-
-
END;

Anonymous, procedure and function blocks:

Anonymous:
- No name.
- Starts with DECLARE statement.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 24


Department of Information Technology DBMS Lab Manual

Procedure:
- No return.
- PROCEDURE name IS

Function:
- Returns a value
- FUNCTION name RETURN data-type IS

Programming Constructs:
- Declaring Variables:
o Identifier [CONSTANT] data-type [NOT NULL]
[:= | DEFAULT expr];

- Assignment:
o Identifier := expr;

- IF Statement:
o IF condition THEN
Statements;
[ELSE IF condition THEN
Statements;]
[ELSE
Statements;]
END IF;

- CASE Statement:
o CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
.
.
.
WHEN expression THEN resultn
[ELSE resultn1;]
END;
- BASIC Loops:
o LOOP
Statement 1;
.
.
.
EXIT [WHEN condition];
END LOOP;

- WHILE Statement:
o WHILE condition LOOP

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 25


Department of Information Technology DBMS Lab Manual

Statement1;
.
.
.
END LOOP;

- FOR Statement:
o FOR counter IN [REVERSE]
Lower_bound..upper_bound LOOP
Statement1;
.
.
.
END LOOP;

WRITE A PL/SQL PROGRAM TO FIND THE SUM OF DIGITS IN A GIVEN NUMBER

declare
a number;
d number:=0;
sum1 number:=0;
begin
a:=&a;
while a>0
loop
d:=mod(a,10);
sum1:=sum1+d;
a:=trunc(a/10);
end loop;
dbms_output.put_line('sum is'|| sum1);
end;

OUTPUT:

SQL> @ SUMOFDIGITS.sql
16 /
Enter value for a: 564
old 7: a:=&a;
new 7: a:=564;
sum is15

PL/SQL procedure successfully completed.

WRITE A PL/SQL PROGRAM TO SWAP TWO NUMBERS WITH OUT TAKING


THIRD VARIABLE

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 26


Department of Information Technology DBMS Lab Manual

declare
a number(10);
b number(10);
begin
a:=&a;
b:=&b;
dbms_output.put_line('THE PREV VALUES OF A AND B WERE');
dbms_output.put_line(a);
dbms_output.put_line(b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line('THE VALUES OF A AND B ARE');
dbms_output.put_line(a);
dbms_output.put_line(b);
end;

OUTPUT:

SQL> @ SWAPPING.SQL
17 /
Enter value for a: 5
old 5: a:=&a;
new 5: a:=5;
Enter value for b: 3
old 6: b:=&b;
new 6: b:=3;
THE PREV VALUES OF A AND B WERE
5
3
THE VALUES OF A AND B ARE
3
5

PL/SQL procedure successfully completed.

WRITE A PL/SQL PROGRAM TO FIND THE LARGEST OF THREE NUMBERS

declare
a number;
b number;
c number;
begin
a:=&a;

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 27


Department of Information Technology DBMS Lab Manual

b:=&b;
c:=&c;
if a=b and b=c and c=a then
dbms_output.put_line('ALL ARE EQUAL');
elsif a>b and a>c then
dbms_output.put_line('A IS GREATER');
elsif b>c then
dbms_output.put_line('B IS GREATER');
else
dbms_output.put_line('C IS GREATER');
end if;
end;

OUTPUT:

SQL> @ GREATESTOF3.sql
17 /
Enter value for a: 8
old 6: a:=&a;
new 6: a:=8;
Enter value for b: 9
old 7: b:=&b;
new 7: b:=9;
Enter value for c: 7
old 8: c:=&c;
new 8: c:=7;
B IS GREATER

PL/SQL procedure successfully completed.

WRITE A PL/SQL PROGRAM TO FIND THE TOTAL AND AVERAGE OF 6 SUBJECTS


AND DISPLAY THE GRADE

declare
java number(10);
dbms number(10);
co number(10);
se number(10);
es number(10);

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 28


Department of Information Technology DBMS Lab Manual

ppl number(10);
total number(10);
avgs number(10);
per number(10);
begin
dbms_output.put_line('ENTER THE MARKS');
java:=&java;
dbms:=&dbms;
co:=&co;
se:=&se;
es:=&es;
ppl:=&ppl;
total:=(java+dbms+co+se+es+ppl);
per:=(total/600)*100;
if java<40 or dbms<40 or co<40 or se<40 or es<40 or ppl<40 then
dbms_output.put_line('FAIL');
if per>75 then
dbms_output.put_line('GRADE A');
elsif per>65 and per<75 then
dbms_output.put_line('GRADE B');
elsif per>55 and per<65 then
dbms_output.put_line('GRADE C');
else
dbms_output.put_line('INVALID INPUT');
end if;
dbms_output.put_line('PERCENTAGE IS '||per);
dbms_output.put_line('TOTAL IS '||total);
end;

OUTPUT:

SQL> @ GRADE.sql
31 /
Enter value for java: 80
old 12: java:=&java;
new 12: java:=80;
Enter value for dbms: 70
old 13: dbms:=&dbms;
new 13: dbms:=70;
Enter value for co: 89
old 14: co:=&co;
new 14: co:=89;
Enter value for se: 72
old 15: se:=&se;
new 15: se:=72;

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 29


Department of Information Technology DBMS Lab Manual

Enter value for es: 76


old 16: es:=&es;
new 16: es:=76;
Enter value for ppl: 71
old 17: ppl:=&ppl;
new 17: ppl:=71;
GRADE A
PERCENTAGE IS 76
TOTAL IS 458
PL/SQL procedure successfully completed.

WRITE A PL/SQL PROGRAM TO CHECK WHETHER THE GIVEN NUMBER IS AN


ARMSTRONG NUMBER OR NOT

declare
a number;
t number;
arm number;
d number;
begin
a:=&a;
t:=a;
arm:=0;
while t>0
loop
d:=mod(t,10);
arm:=arm+power(d,3);
t:=trunc(t/10);
end loop;
if arm=a then
dbms_output.put_line('given no is an armstrong no'|| a);
else
dbms_output.put_line('given no is not an armstrong no');
end if;
end;

OUTPUT:

SQL> @ ARMSTRONGNUM.sql
Enter value for a: 407
old 7: a:=&a;
new 7: a:=407;
given no is an armstrong no407

PL/SQL procedure successfully completed.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 30


Department of Information Technology DBMS Lab Manual

SQL> /
Enter value for a: 406
old 7: a:=&a;
new 7: a:=406;
given no is not an armstrong no

PL/SQL procedure successfully completed.

Creation of FORMS using ORACLE FORM BUILDER


To design a form using Oracle Developer 2000

Introduction
Use Form Builder to simplify for the creation of data-entry screens, also known as Forms.
Forms are the applications that connect to a database, retrieve information requested by the
user, present it in a layout specified by Form designer, and allow the user to modify or add
information. Form Builder allows you to build forms quickly and easily.
In this Hands-On, you learn how to: Create a Data block for the “Customer” table, Create a
layout, Use “content” canvas, Use “execute query”, Navigate a table, Use next, previous
record, Enter query, Manipulate table’s record, Insert, Update, Delete and Save record.
Form Builder Tool
Open the "Form Builder" tool.
Welcome window
You will get the ‘Welcome to the Form Builder’ window. If you don’t want to get this
window anymore uncheck the ‘Display at startup’ box. You can start your work with any of
the following options:
· Use the data Block Wizard
· Build a new form manually
· Open an existing form
· Build a form based on a template
The default is ‘Use the data Block Wizard.’ If you want to build a new form manually, click
on "Cancel” or check ‘Build a new form manually’ and click ‘OK.’
Connect to database
In the ‘Object Navigator’ window, highlight "Database Objects." Go to the Main menu and
choose "File," then "Connect."
In the ‘Connect’ window, login in as “scott” password “tiger,” then click “CONNECT.”
Notice that the box next to ‘Database Objects’ is not empty anymore and it has a ‘+’ sign in
it. That will indicate that this item is expandable and you are able to see its entire objects.
Click on the ‘+’ sign next to the ‘Database Objects’ to expand all database schemas.
Create a Module
In the ‘Object Navigator’ window, highlight module1. This is a default name. Go to the Main
menu and choose “File,” select “Save as” to store the new object in the “iself” folder and
save it as customer data entry. "c:_de." In this example the ‘DE’ abbreviation stands for Data
Entry.
Create a Data Block
In the ‘Object Navigator’ window, highlight "Data Blocks,” and click on the "create” icon.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 31


Department of Information Technology DBMS Lab Manual

The ‘Create’ icon is in the vertical tool bar in the ‘Object Navigator’ window. It is a green ‘+’
sign. If you drag your cursor on the icon a tooltip will show ‘Create.’
New Data Block
In the ‘New Data Block’ window, choose the default option “Data Block Wizard” and click "OK."
Welcome Data Block
In the ‘Welcome Data Block Wizard’ window click on the “NEXT” icon.
Type of Data Block
Select the type of data block you would like to create by clicking on a radio button. Select the
default option ‘Table or View’ and then click “NEXT” again.
Selecting Tables
Click on “browse.” In the ‘Tables’ window, highlight the "cust11” table; then click "OK."
Selecting columns for the Data Block Wizard
To choose all columns, click on the two arrow signs in the ‘Data Block Wizard’ window. To
choose selected columns, click on the one arrow sign. And then select all columns, and click
“next.”
Layout Wizard
End of the Data Block Wizard and beginning of the Layout Wizard In the ‘Congratulations’
screen, use the default checkmark radio button (Create the data block, then call the Layout
Wizard), and click "Finish." You can also use the Data Block Wizard to modify your existing data
block. Simply select the data block in the Object Navigator and click the Data Block Wizard
toolbar button, or choose ‘Data Block wizard’ from the ‘Tools’ menu.
Welcome screen
In the ‘Welcome to the Layout Wizard’ window, click ”Next.”
Selecting canvas
In the ‘Layout Wizard’ window, select the "new canvas" option. Canvas is a place that you will
have your objects such as columns, titles, pictures, etc. If you have already had your canvas, select
the canvas and then click on the next. The following are different types of canvases: Content,
Stacked, Vertical Toolbar, Horizontal Toolbar, and Tab.
Think of the ‘Content’ canvas as one flat place to have all your objects. In the stacked canvas,you
can have multiple layers of objects and it is the same as the tab canvas. You use the vertical or
horizontal toolbar canvases for your push buttons. Check the different types of canvases by
clicking on the ‘down arrow’ box next to the ‘Type’ field. Select "content," then click “Next.”

Selecting Columns for the Layout Wizard


In the ‘Layout Wizard’ window, select all the columns. These are the columns that you want to be
displayed on the canvas. Then click “Next.”
Change your objects appearances
Change size or prompt if needed. In this window, you can enter a prompt, width, and height for
each item on the canvas. You can change the measurement units. As a default the default units for
item width and height are points. You can change it to inch or centimeter. When you change size,
click “Next.”
Selecting a layout style
Select a layout style for your frame by clicking a radio button. Select "Form," if you want one
record at a time to be displayed. Select “Tabular,” if you want more than one record at a time to be
displayed. Select "Forms," and then click “next.”

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 32


Department of Information Technology DBMS Lab Manual

Record layout
Type the "Frame Title" and click "next." Checkmark the ‘Display Scrollbar’ box when you use
multiple records or the ‘Tabular’ option.
Congratulation Screen
In the ‘Congratulations’ window, click "Finish." You will see the output layout screen. Make some
window adjustments and then run the form. To run the form, click on the ‘Run’ icon. The ‘Run’
icon is on the horizontal toolbar in the ‘CUSTOMER_DE’ canvas. The object module should be
compiled successfully before executing the Form.
Execute Query
Click on the "Execute Query" icon below the main menu. If you drag the cursor on the toolbar in
the ‘Forms Runtime’ window, a tooltip will be displayed and you see ‘Execute Query.’ So to
know all your option, drag your cursor to view all the icon descriptions.
Next Record
Click on the "Next Record" icon to navigate to the next record.
Previous Record
Click on the "Previous Record" icon to navigate to the previous record. This is an easy way to
navigate through the “Customer” table.
Enter Query
Click on the "Enter Query" icon to query selected records.
Insert Record
Click "Insert Record" to add new customer. All items on the forms will be blanked. You can either
type all the customer information or duplicate it from pervious record.
Duplicate Record
To duplicate the previous record, go to the main menu and select the ‘Record’ sub-menu. A drop
down menu will be displayed. Select the ‘Duplicate’ option in the sub-menu. Apply the changes.
Remember in this stage, your record was inserted but not committed yet.
Next and Previous Record
Click "next record" and "previous record" to navigate through the records and the one was added.
Save transactions
Click "Save" to commit the insert statement.
Delete Record
Click "Remove Record" to delete the record.
Lock a Record
You can also lock the record.
Exit from Form Runtime
Exit the FORM Runtime. If you have not committed any transaction, you will be prompted to
save changes. Click “YES” to save changes.
Click “OK” for acknowledgement.
Don’t forget to save the Form.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 33


Department of Information Technology DBMS Lab Manual

Selecting the type of form to create

Object wizard

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 34


Department of Information Technology DBMS Lab Manual

Selecting the canvas on which data block can be displayed

Form showing the Employee details

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 35


Department of Information Technology DBMS Lab Manual

Generating REPORTS using Oracle Developer 2000


AIM: To design reports using Oracle Developer 2000
Introduction
Tabular report shows data in a table format. It is similar in concept to the idea of an Oracle
table. Oracle, by default, returns output from your select statement in tabular format.
Hands-on
In this Hands-On, your client is a stock broker that keeps track of its customer stock
transactions. You have been assigned to write the reports based on their reports layout
requirements.
Your client wants you to create a simple listing report to show list of the stock trades by
using stocks table for their brokerage company
Your tasks are:
1- Write a tabular report.
2- Apply user layout Format mask.
3- Run the report.
4- Test the repot.
You will learn how to: use report wizard, object navigator, report builder, “date model”,
property palette, work on query and group box, see report style, use tabular style, navigating
through report’s record, change the format mask for dollar, numeric and date items.
Open Report Builder tool
Open the "Report Builder" tool.
Connect to database
In the Object Navigator, highlight "Database Objects,” choose "File," then select the
"Connect" option.
In the ‘Connect’ window, login as “iself” password schooling, then click “CONNECT.”
Save a report
In the Object Navigator, highlight the "untitled" report, choose “File,” and select the “Save
as” option.
In the ‘Save as’ window, make sure to save the report in the ISELF folder and name it
"rpt01_stock_history,” report number 1 stock history.
Data Model

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 36


Department of Information Technology DBMS Lab Manual

In the Object Navigator, double click on the "Data Model" icon.


Create SQL box
In the Data Model window, click on the "SQL Query" icon. Then drag the plus sign cursor
and click it anywhere in the “Data Model” screen where you wish your object to be.
In the ‘SQL Query Statement’ window, write a query to read all the stocks record sorted by
their symbol.
(SQL Query Statement)
SELECT * FROM stocks
ORDER BY symbol
Click “OK.”
Change SQL box’s name
In the Data Model window, in the “SQL” box, right click on the ‘Q_1’ and open its property
palette.
In its property palette, change the name to Q_STOCKS. Then close the window.
Change GROUP box’s name
In the Data Model, right click on the group box (G_SYMBOL) and open its property palette.
In the Group property palette, change the name to ‘G_STOCKS,’ and close the window.
Open Report Wizard
In the Data Model, click on the ‘Report Wizard’ icon on the horizontal tool bar.
In the Style tab, on the Report Wizard window, type ‘Stock History’ in the Title box and
choose the report style as ‘Tabular.’
Notice that when you change the report style a layout of that report will be displayed on the
screen.
Choose a different style to display its layout of its report style.
Data, Fields, Totals, Labels and Template tabs
Click “NEXT” to go to the Data tab. In the ‘SQL Query Statement’ verify your query.
Click “NEXT” to navigate to the Fields tab, select the fields that you would like to be display
in your report. Select all the columns to be display.
Click “NEXT” to navigate to Totals tab, select the fields for which you would like to
calculate totals. We have none in this hands-on exercise.
Click “NEXT” to open the Labels tab, modify the labels and widths for your fields and totals

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 37


Department of Information Technology DBMS Lab Manual

as desired.
Click “NEXT” again to go to the Template tab, and choose a template for your report. Your
report will inherit the template’s colors, fonts, line widths, and structure.
Use the default template and click “finish.”
Running a report
Now, you should have your output report on the screen.
Resize an object
Maximize the output report and format the report layout. To resize an object , select it and
drag its handler to the preferred size.
Move an object
To move an object, select and drag it while the cursor is on the object.
This is a simple report.
Navigate through the output
To navigate through the output report in the Report Editor - Live Pre-viewer, click on the
"next page" or "previous page" icon on the horizontal toolbar.
Do the same with the "first page" or "last page" icon.
Use the “zoom in” and “zoom out” icon to preview the report.
Know report’s functions
To know each icon functionalities, drag your cursor on it and a tooltip will display its
function.
Change Format Mask
To change the "format mask" of a column, the column should be selected. Then go to the
toolbar and click on the “$” icon, "add decimal place," and the “right justify” format to the all
currency columns (Todays Low, Todays High, and current price)
Select the “traded today” column, and click on the ‘,0’ icon (apply commas), and make it
right justify.
Also, you can change any attributes of field by opening its property palette. To open an
object’s property palette, right click on it and select the Property Palette option.
Right click on the "trade date" column and open its "property palette."
Change the date "Format Mask" property and make it “year 2000 complaint (MM-DD-RR).”

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 38


Department of Information Technology DBMS Lab Manual

Selecting type of report

Creating reports

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 39


Department of Information Technology DBMS Lab Manual

Selecting the format of reports

Selecting the Table in database

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 40


Department of Information Technology DBMS Lab Manual

Selecting the columns in the report

Modify the labels in a table

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 41


Department of Information Technology DBMS Lab Manual

Choose a template to represent the report

To specify the completion of report generation

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 42


Department of Information Technology DBMS Lab Manual

REFERENCES

Web-Sites:
www.otn.oracle.com

Database Systems Instructor: Prof. Samuel Madden Source: MIT Open Courseware
(http://ocw.mit.edu)

An A-Z Index of Oracle SQL Commands (version 9.2)


http://www.ss64.com/ora/.

Books:
1. Database Management Systems, Korth & Sudharshan.
2. Database Management Systems, Raghuram Krishnan.
3. Database Management Systems, Elmasri & Navathe.

VIVA VOICE QUESTIONS AND ANSWERS

1. What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with data
for a specific purpose.
2. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
3. What is a Database system?
The database and DBMS software together is called as Database system.
4. Advantages of DBMS?
-> Redundancy is controlled.
-> Unauthorised access is restricted.
-> Providing multiple user interfaces.
-> Enforcing integrity constraints.
-> Providing backup and recovery.
5. Disadvantage in File Processing System?
-> Data redundancy & inconsistency.
-> Difficult in accessing data.
-> Data isolation.
-> Data integrity.
-> Concurrent access is not possible.
-> Security Problems.
6. Describe the three levels of data abstraction?
The are three levels of abstraction:
-> Physical level: The lowest level of abstraction describes how data are stored.
-> Logical level: The next higher level of abstraction, describes what data are stored in

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 43


Department of Information Technology DBMS Lab Manual

database and what relationship among those data.


-> View level: The highest level of abstraction describes only part of entire database.
7. Define the "integrity rules"
There are two Integrity rules.
-> Entity Integrity: States that “Primary key cannot have NULL value”
-> Referential Integrity: States that “Foreign Key can be either a NULL value or should be
Primary Key value of other relation.
8. What is extension and intension?
Extension -
It is the number of tuples present in a table at any instance. This is time dependent.
Intension -
It is a constant value that gives the name, structure of table and the constraints laid on it.
9. What is System R? What are its two major subsystems?
System R was designed and developed over a period of 1974-79 at IBM San Jose Research
Center. It is a prototype and its purpose was to demonstrate that it is possible to build a
Relational System that can be used in a real life environment to solve real life problems, with
performance at least comparable to that of existing system.
Its two subsystems are
-> Research Storage
-> System Relational Data System.
10. How is the data structure of System R different from the relational structure?
Unlike Relational systems in System R
-> Domains are not supported
-> Enforcement of candidate key uniqueness is optional
-> Enforcement of entity integrity is optional
-> Referential integrity is not enforced
11. What is Data Independence?
Data independence means that “the application is independent of the storage structure and
access strategy of data”. In other words, The ability to modify the schema definition in one
level should not affect the schema definition in the next higher level.
Two types of Data Independence:
-> Physical Data Independence: Modification in physical level should not affect the logical
level.
-> Logical Data Independence: Modification in logical level should affect the view level.
NOTE: Logical Data Independence is more difficult to achieve
12. What is a view? How it is related to data independence?
A view may be thought of as a virtual table, that is, a table that does not really exist in its
own right but is instead derived from one or more underlying base table. In other words,
there is no stored file that direct represents the view instead a definition of view is stored in
data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate
users from the effects of restructuring and growth in the database. Hence accounts for logical
data independence.
13. What is Data Model?
A collection of conceptual tools for describing data, data relationships data semantics and
constraints.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 44


Department of Information Technology DBMS Lab Manual

14. What is E-R model?


This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.
15. What is Object Oriented model?
This model is based on collection of objects. An object contains values stored in instance
variables with in the object. An object also contains bodies of code that operate on the object.
These bodies of code are called methods. Objects that contain same types of values and the
same methods are grouped together into classes.
16. What is an Entity?
It is a 'thing' in the real world with an independent existence.
17. What is an Entity type?
It is a collection (set) of entities that have same attributes.
18. What is an Entity set?
It is a collection of all entities of particular entity type in the database.
19. What is an Extension of entity type?
The collections of entities of a particular entity type are grouped together into an entity set.
20. What is Weak Entity set?
An entity set may not have sufficient attributes to form a primary key, and its primary key
compromises of its partial key and primary key of its parent entity, then it is said to be Weak
Entity set.
21. What is an attribute?
It is a particular property, which describes the entity.
22. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the
list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation
which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2,
..., vn).
23. What is degree of a Relation?
It is the number of attribute of its relation schema.
24. What is Relationship?
It is an association among two or more entities.
25. What is Relationship set?
The collection (or set) of similar relationships.
26. What is Relationship type?
Relationship type defines a set of associations or a relationship set among a given set of
entity types.
27. What is degree of Relationship type?
It is the number of entity type participating.
28. What is DDL (Data Definition Language)?
A data base schema is specifies by a set of definitions expressed by a special language called
DDL.
29. What is VDL (View Definition Language)?
It specifies user views and their mappings to the conceptual schema.
30. What is SDL (Storage Definition Language)?
This language is to specify the internal schema. This language may specify the mapping
between two schemas.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 45


Department of Information Technology DBMS Lab Manual

31. What is Data Storage - Definition Language?


The storage structures and access methods used by database system are specified by a set of
definition in a special type of DDL called data storage-definition language.
32. What is DML (Data Manipulation Language)?
This language that enable user to access or manipulate data as organised by appropriate data
model.
-> Procedural DML or Low level: DML requires a user to specify what data are needed and
how to get those data.
-> Non-Procedural DML or High level: DML requires a user to specify what data are needed
without specifying how to get those data.
33. What is DML Compiler?
It translates DML statements in a query language into low-level instruction that the query
evaluation engine can understand.
34. What is Query evaluation engine?
It executes low-level instruction generated by compiler.
35. What is DDL Interpreter?
It interprets DDL statements and record them in tables containing metadata.
36. What is Record-at-a-time?
The Low level or Procedural DML can specify and retrieve each record from a set of records.
This retrieve of a record is said to be Record-at-a-time.
37. What is Set-at-a-time or Set-oriented?
The High level or Non-procedural DML can specify and retrieve many records in a single
DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.
38. What is Relational Algebra?
It is procedural query language. It consists of a set of operations that take one or two relations
as input and produce a new relation.
39. What is Relational Calculus?
It is an applied predicate calculus specifically tailored for relational databases proposed by
66
E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL.
40. How does Tuple-oriented relational calculus differ from domain-oriented relational
calculus
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values
are tuples of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the
underlying domains instead of over relation. E.g. ILL, DEDUCE.
41. 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
-> Minimizing redundancy
-> Minimizing insertion, deletion and update anomalies.
42. 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.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 46


Department of Information Technology DBMS Lab Manual

43. When is a functional dependency F said to be minimal?


-> Every dependency in F has a single attribute for its right hand side.
-> We cannot replace any dependency X A in F with a dependency Y A where Y is a proper
subset of X and still have a set of dependency that is equivalent to F.
-> We cannot remove any dependency from F and still have set of dependency that is
equivalent to F.
44. What is Multivalued dependency?
Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are
both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1
and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the
following properties
-> t3[x] = t4[X] = t1[X] = t2[X]
-> t3[Y] = t1[Y] and t4[Y] = t2[Y]
-> t3[Z] = t2[Z] and t4[Z] = t1[Z]
where [Z = (R-(X U Y)) ]
45. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation
schemas after decomposition.
46. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values.
47. What is Fully Functional dependency?
67
It is based on concept of full functional dependency. A functional dependency X Y is full
functional dependency if removal of any attribute A from X means that the dependency does
not hold any more.
48. What is 2NF?
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.
49. What is 3NF?
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is
true
-> X is a Super-key of R.
-> A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
50. What is BCNF (Boyce-Codd Normal Form)?
A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for
every FD X A, X must be a candidate key.
51. What is 4NF?
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds
over R, one of following is true
-> X is subset or equal to (or) XY = R.
-> X is a super key.
52. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that
holds R, one the following is true
-> Ri = R for some i.
-> The join dependency is implied by the set of FD, over R in which the left side is key of R.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 47


Department of Information Technology DBMS Lab Manual

53. What is Domain-Key Normal Form?


A relation is said to be in DKNF if all constraints and dependencies that should hold on the
the constraint can be enforced by simply enforcing the domain constraint and key constraint
on the relation.
54. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same
owner entity. It is sometime called as Discriminator.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key, either stand alone or compound is available, then the last resort is to
simply create a key, by assigning a unique number to each record or occurrence. Then this is
known as developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining
multiple elements to create a unique identifier for the construct is known as creating a
compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it
is called the natural key.
55. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
-> Binary search style indexing
-> B-Tree indexing
-> Inverted list indexing
-> Memory resident table
-> Table indexing
56. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every
relation and index that it contains. This information is stored in a collection of relations
maintained by the system called metadata. It is also called data dictionary.
57. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the least
estimated cost is referred to as query optimization.
58. What is join dependency and inclusion dependency?
Join Dependency:
A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is
said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R .
There is no set of sound and complete inference rules for JD.
Inclusion Dependency:
An Inclusion Dependency is a statement of the form that some columns of a relation are
contained in other columns. A foreign key constraint is an example of inclusion dependency.
59. What is durability in DBMS?
Once the DBMS informs the user that a transaction has successfully completed, its effects

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 48


Department of Information Technology DBMS Lab Manual

should persist even if the system crashes before all its changes are reflected on disk. This
property is called durability.
60. What do you mean by atomicity and aggregation?
Atomicity:
Either all actions are carried out or none are. Users should not have to worry about the effect
of incomplete transactions. DBMS ensures this by undoing the actions of incomplete
transactions.
Aggregation:
A concept which is used to model a relationship between a collection of entities and
relationships. It is used when we need to express a relationship among relationships.
61. What is a Phantom Deadlock?
In distributed deadlock detection, the delay in propagating local information might cause the
deadlock detection algorithms to identify deadlocks that do not really exist. Such situations
are called phantom deadlocks and they lead to unnecessary aborts.
62. What is a checkpoint and When does it occur?
A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can
reduce the amount of work to be done during restart in the event of subsequent crashes.
63. What are the different phases of transaction?
Different phases are
-> Analysis phase
-> Redo Phase
-> Undo phase
64. What do you mean by flat file database?
It is a database in which there are no programs or user access languages. It has no cross-file
capabilities but is user-friendly and provides user-interface management.
65. What is "transparent DBMS"?
It is one, which keeps its Physical Structure hidden from user.
66. Brief theory of Network, Hierarchical schemas and their properties
Network schema uses a graph data structure to organize records example for such a database
management system is CTCG while a hierarchical schema uses a tree data structure example
for such a system is IMS.
67. What is a query?
A query with respect to DBMS relates to user commands that are used to interact with a data
base. The query language can be classified into data definition language and data
manipulation language.
68. What do you mean by Correlated subquery?
Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent
query. Depending on how the subquery is written, it can be executed once for the parent
query or it can be executed once for each row returned by the parent query. If the subquery is
executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent
subquery columns in its WHERE clause. Columns from the subquery cannot be referenced
anywhere else in the parent query. The following example demonstrates a non-correlated
subquery.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where
CUST.CNUM = ORDER.CNUM)

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 49


Department of Information Technology DBMS Lab Manual

69. What are the primitive operations common to all record management systems?
Addition, deletion and modification.
70. Name the buffer in which all the commands that are typed in are stored
‘Edit’ Buffer
71. What are the unary operations in Relational Algebra?
PROJECTION and SELECTION.
72. Are the resulting relations of PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
73. What is RDBMS KERNEL?
Two important pieces of RDBMS architecture are the kernel, which is the software, and the
data dictionary, which consists of the system-level data structures used by the kernel to
manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed
specifically for controlling data access; its primary functions are storing, retrieving, and
securing data. An RDBMS maintains its own list of authorized users and their associated
privileges; manages memory caches and paging; controls locking for concurrent resource
usage; dispatches and schedules user requests; and manages space usage within its tablespace
structures.
74. Name the sub-systems of a RDBMS
I/O, Security, Language Processing, Process Control, Storage Management, Logging and
Recovery, Distribution Control, Transaction Control, Memory Management, Lock
Management
75. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of the
database and maintained exclusively by the kernel.
76. What is the job of the information stored in data-dictionary?
The information in the data dictionary validates the existence of the objects, provides access
to them, and maps the actual physical storage location.
77. Not only RDBMS takes care of locating data it also
determines an optimal access path to store or retrieve the data
76. How do you communicate with an RDBMS?
You communicate with an RDBMS using Structured Query Language (SQL)
78. Define SQL and state the differences between SQL and other conventional
programming Languages
SQL is a nonprocedural language that is designed specifically for data access operations on
normalized relational database structures. The primary difference between SQL and other
conventional programming languages is that SQL statements specify what data operations
should be performed rather than how to perform them.
79. 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

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 50


Department of Information Technology DBMS Lab Manual

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.
80. What is an Oracle Instance?
The Oracle system processes, also known as Oracle background processes, provide functions
for the user processes—functions that would otherwise be done by the user processes
themselves
Oracle database-wide system memory is known as the SGA, the system global area or shared
global area. The data and control structures in the SGA are shareable, and all the Oracle
background processes and user processes can use them.
The combination of the SGA and the Oracle background processes is known as an Oracle
instance
81. What are the four Oracle system processes that must always be up and running for
the database to be useable
The four Oracle system processes that must always be up and running for the database to be
useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor),
and PMON (Process Monitor).
82. What are database files, control files and log files. How many of these files should a
database have at least? Why?
Database Files
The database files hold the actual data and are typically the largest in size. Depending on
their sizes, the tables (and other objects) for all the user accounts can go in one database file —but
that's not an ideal situation because it does not make the database structure very
flexible for controlling access to storage for different users, putting the database on different
disk drives, or backing up and restoring just part of the database.
You must have at least one database file but usually, more than one files are used. In terms of
accessing and using the data in the tables and other objects, the number (or location) of the
files is immaterial.
The database files are fixed in size and never grow bigger than the size at which they were
created Control Files
The control files and redo logs support the rest of the architecture. Any database must have at
least one control file, although you typically have more than one to guard against loss. The
control file records the name of the database, the date and time it was created, the location of
the database and redo logs, and the synchronization information to ensure that all three sets
of files are always in step. Every time you add a new database or redo log file to the
database, the information is recorded in the control files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the database; the
redo logs record all changes to the user objects or system objects. If any type of failure
occurs, the changes recorded in the redo logs can be used to bring the database to a consistent
state without losing any committed transactions. In the case of non-data loss failure, Oracle
can apply the information in the redo logs automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at which they

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 51


Department of Information Technology DBMS Lab Manual

were created.
83. What is ROWID?
The ROWID is a unique database-wide physical address for every row on every table. Once
assigned (when the row is first inserted into the database), it never changes until the row is
deleted or the table is dropped.
The ROWID consists of the following three components, the combination of which uniquely
identifies the physical storage location of the row.
-> Oracle database file number, which contains the block with the rows
-> Oracle block address, which contains the row
-> The row within the block (because each block can hold many rows)
The ROWID is used internally in indexes as a quick means of retrieving rows with a
particular key value. Application developers also use it in SQL statements as a quick way to
access a row once they know the ROWID
84. What is Oracle Block? Can two Oracle Blocks have the same address?
Oracle "formats" the database files into a number of Oracle blocks when they are first created
—making it easier for the RDBMS software to manage the files and easier to read data into
the memory areas.
The block size should be a multiple of the operating system block size. Regardless of the
block size, the entire block is not available for holding data; Oracle takes up some space to
manage the contents of the block. This block header has a minimum size, but it can grow.
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can
improve performance, but it should be done only when the database is first created.
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks
can have the same block address if they are in different database files.
85. What is database Trigger?
A database trigger is a PL/SQL block that can defined to automatically execute for insert,
update, and delete statements against a table. The trigger can e defined to execute once for
the entire statement or once for every row that is inserted, updated, or deleted. For any one
table, there are twelve events for which you can define database triggers. A database trigger
can call database procedures that are also written in PL/SQL.
86. Name two utilities that Oracle provides, which are use for backup and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use to back up
and restore the database. These utilities are Export and Import.
The Export utility dumps the definitions and data for the specified part of the database to an
operating system binary file. The Import utility reads the file produced by an export,
recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the
changes made to the database cannot be recovered since the export was performed. The best
you can do is recover the database to the time when the export was last performed.
87. What are stored-procedures? And what are the advantages of using them.
Stored procedures are database objects that perform a user defined operation. A stored
procedure can have a set of compound SQL statements. A stored procedure executes the SQL
commands and returns the result to the client. Stored procedures are used to reduce network
traffic.
88. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name
PL/SQL exception handling is a mechanism for dealing with run-time errors encountered

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 52


Department of Information Technology DBMS Lab Manual

during procedure execution. Use of this mechanism enables execution to continue if the error
is not severe enough to cause procedure termination.
The exception handler must be defined within a subprogram specification. Errors cause the
program to raise an exception with a transfer of control to the exception-handler block. After
the exception handler executes, control returns to the block in which the handler was defined.
If there are no more executable statements in the block, control returns to the caller.
User-Defined Exceptions
PL/SQL enables the user to define exception handlers in the declarations area of subprogram
specifications. User accomplishes this by naming an exception as in the following example:
ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler is written in
the EXCEPTION specification area as follows:
EXCEPTION
when OT_FAILURE then
out_status_code := g_out_status_code;
out_msg := g_out_msg;
The following is an example of a subprogram exception:
EXCEPTION
when NO_DATA_FOUND then
g_out_status_code := 'FAIL';
RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the ot_failure
exception handler. This technique of raising the exception is used to invoke all user-defined
exceptions.
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a
system-defined exception. Table below gives a complete list of internal exceptions.
PL/SQL internal exceptions.
PL/SQL internal exceptions.
Exception Name Oracle Error
CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
STORAGE_ERROR ORA-06500
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
TRANSACTION_BACKED_OUT ORA-00061
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476
In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps
all errors for which specific error handling has not been established.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 53


Department of Information Technology DBMS Lab Manual

89. Does PL/SQL support "overloading"? Explain


The concept of overloading in PL/SQL relates to the idea that you can define procedures and
functions with the same name. PL/SQL does not look only at the referenced name, however,
to resolve a procedure or function call. The count and data types of formal parameters are
also considered.
PL/SQL also attempts to resolve any procedure or function calls in locally defined packages
before looking at globally defined packages or internal functions. To further ensure calling
the proper procedure, you can use the dot notation. Prefacing a procedure or function name
with the package name fully qualifies any procedure or function reference.
90. Tables derived from the ERD
a) Are totally unnormalised
b) Are always in 1NF
c) Can be further denormalised
d) May have multi-valued attributes
(b) Are always in 1NF
91. Spurious tuples may occur due to
i. Bad normalization
ii. Theta joins
iii. Updating tables from join
a) i & ii b) ii & iii
c) i & iii d) ii & iii
(a) i & iii because theta joins are joins made on keys that are not primary keys.
92. A B C is a set of attributes. The functional dependency is as follows
AB -> B
AC -> C
C -> B
a) is in 1NF
b) is in 2NF
c) is in 3NF
d) is in BCNF
(a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD
given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is
not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF.
93. In mapping of ERD to DFD
a) entities in ERD should correspond to an existing entity/store in DFD
b) entity in DFD is converted to attributes of an entity in ERD
c) relations in ERD has 1 to 1 correspondence to processes in DFD
d) relationships in ERD has 1 to 1 correspondence to flows in DFD
(a) entities in ERD should correspond to an existing entity/store in DFD
94. A dominant entity is the entity
a) on the N side in a 1 : N relationship
b) on the 1 side in a 1 : N relationship
c) on either side in a 1 : 1 relationship
d) nothing to do with 1 : 1 or 1 : N relationship
(b) on the 1 side in a 1 : N relationship
95. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 54


Department of Information Technology DBMS Lab Manual

CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION


= 'E' Order By CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause
(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS
96. What is Storage Manager?
It is a program module that provides the interface between the low-level data stored in
database, application programs and queries submitted to the system.
97. What is Buffer Manager?
It is a program module, which is responsible for fetching data from disk storage into main
memory and deciding what data to be cache in memory.
98. What is Transaction Manager?
It is a program module, which ensures that database, remains in a consistent state despite
system failures and concurrent transaction execution proceeds without conflicting.
99. What is File Manager?
It is a program module, which manages the allocation of space on disk storage and data
structure used to represent information stored on a disk.
100. What is Authorization and Integrity manager?
It is the program module, which tests for the satisfaction of integrity constraint and checks
the authority of user to access data.
101. What are stand-alone procedures?
Procedures that are not part of a package are known as stand-alone because they
independently defined. A good example of a stand-alone procedure is one written in a
SQL*Forms application. These types of procedures are not available for reference from other
Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run
time, which slows execution.
102. What are cursors give different types of cursors.
PL/SQL uses cursors for all database information accesses statements. The language supports
the use two types of cursors
-> Implicit
-> Explicit
103. What is cold backup and hot backup (in case of Oracle)?
-> Cold Backup:
It is copying the three sets of files (database files, redo logs, and control file) when the
instance is shut down. This is a straight file copy, usually from the disk directly to tape. You
must shut down the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is
restoring all the files from the latest backup. All work performed on the database since the
last backup is lost.
-> Hot Backup:
Some sites (such as worldwide airline reservations systems) cannot shut down the database
while making a backup copy of the files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 55


Department of Information Technology DBMS Lab Manual

command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the


tablespace are to backed up. The users can continue to make full use of the files, including
making changes to the data. Once the user has indicated that he/she wants to back up the
tablespace files, he/she can use the operating system to copy those files to the desired backup
destination.
The database must be running in ARCHIVELOG mode for the hot backup option.
If a data loss failure does occur, the lost database files can be restored using the hot backup
and the online and offline redo logs created since the backup was done. The database is
restored to the most consistent state without any loss of committed transactions.
104. What are Armstrong rules? How do we say that they are complete and/or sound
The well-known inference rules for FDs
-> Reflexive rule :
If Y is subset or equal to X then X Y.
-> Augmentation rule:
If X Y then XZ YZ.
-> Transitive rule:
If {X Y, Y Z} then X Z.
-> Decomposition rule :
If X YZ then X Y.
-> Union or Additive rule:
If {X Y, X Z} then X YZ.
-> Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it is enough if
a set of FDs satisfy these three. They are called complete because using these three rules we
can generate the rest all inference rules.
105. How can you find the minimal key of relational schema?
Minimal key is one which can identify each tuple of the given relation schema uniquely. For
finding the minimal key it is required to find the closure that is the set of all attributes that are
dependent on any given set of attributes under the given set of functional dependency.
Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+
Algo.II Determining minimal K for relation schema R, given set of FDs F
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K
a. Compute (K – A)+ with respect to F
b. If (K – A)+ = R then set K = (K – A)+
106. What do you understand by dependency preservation?
Given a relation R and a set of FDs F, dependency preservation states that the closure of the
union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e.,
((PR1(F)) U … U (PRn(F)))+ = F+
if decomposition is not dependency preserving, then some dependency is lost in the
decomposition.

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 56


Department of Information Technology DBMS Lab Manual

107. What is meant by Proactive, Retroactive and Simultaneous Update.


Proactive Update:
The updates that are applied to database before it becomes effective in real world .
Retroactive Update:
The updates that are applied to database after it becomes effective in real world .
Simulatneous Update:
The updates that are applied to database at the same time when it becomes effective in real
world .
108. What are the different types of JOIN operations?
Equi Join: This is the most common type of join which involves only equality comparisions.
The disadvantage in this type of join is that there

VAAGDEVI INSTITUTE OF TECHNOLOGY AND SCIENCE Page 57

You might also like