You are on page 1of 96

Plsql

Why we use pl/sql?


Plsql has several advantages for example using SQL*plus we can
send sql statement to the oracle server one at a time. Each sql
statement results in another call to the oracle server hence
multiple select statements will result in multiple round hence
there is network traffic .
When there sql statement are combined into a plsql block there
are send to the oracle server as a single unit. The sql statement in
plsql block are executed at the server. The server sends the
results of these sql statement back to the client also as a single
unit. So number of rounds are reduced and improve the
performance.
We can move the plsql program to any host environment that
supports oracle and plsql . plsql program can run anywhere in the
oracle server.
Plsql supports:
Plsql supports error handling, to define composite data types,
conditional constructs, iterative control statements, object
oriented program, web applications and pages.

. Tell some tips to avoid performance problems in PL/SQL.


- Use FORALL instead of FOR, and use BULK COLLECT to avoid
looping many times.
- Tune SQL statements to avoid CPU overhead
- Use NOCOPY for OUT and IN OUT if the original value need not
be retained. Overhead of keeping a copy of OUT is avoided.
- Minimize data type conversions => Assign data to exact same
type variables.
1

Plsql
EXECUTE IMMEDIATE is faster than DBMS_SQL

How can you generate debugging output from PL/SQL?


answer: Use the DBMS_OUTPUT package. Another possible
method is to just use the SHOW ERROR command, but this only
shows errors. The DBMS_OUTPUT package can be used to show
intermediate results from loops and the status of variables as the
procedure is executed. The new package UTL_FILE can also be
used.
What steps are included in the compilation process of a
PL/SQL block?
The compilation process includes syntax checking, binding, and pcode generation.
Syntax checking involves checking PL/SQL code for compilation
errors. After syntax errors have been corrected, a storage address
is assigned to the variables that are used to hold data for Oracle.
This process is called binding.
Next, pcode is generated for the PL/SQL block. Pcode is a list of
instructions to the PL/SQL engine. For named blocks, pcode is
stored in the database, and it is used the next time the program is
executed.

Plsql blocks:
Plsql blocks are two types
Anonymous block: The block contains any name that is
anonymous block. We cannot call in another programs. But
named blocks can be calls in anonymous blocks.
2

Plsql
Named block: This block contains named PL/SQL programs which
are stored physically in the database as schema objects.
Plsql structure:
Declaration: This is an optional section which is used for
declaration of local variables, cursors, and local subprograms. The
DECLARE keyword indicates the beginning of the declaration
section.
Execution: This is the mandatory section of a PL/SQL block which
contains the executable statements. These statements are parsed
by the PL/SQL engine and executed on the block. The BEGIN and
END keywords
indicate the beginning and end of an executable section.
Exception: This is the optional section of the block which contains
the exception handlers. The EXCEPTION keyword indicates the
start of the exception section.
What are the Plsql variables?
Plsql variables can be used for temporary storage, reusablility,
easy of maintenance.
The scope of a variable is the portion of the program in which the
variable can be accessed, or where the
Variable is visible. It usually extends from the moment of
declaration until the end of the block in which
the variable was declared.
What are the different types of datatypes available in
plsql?
Scalar: Holds a single value and does not contain any internal
components. Ex: timestamp, varchar2,char,
Number,Long,Int,Integer

Plsql
Composite: Contains the internal datatypes. Which can be
manuplated individually. It is known as collection. Ex.: TABLE,
RECORD, NESTED TABLE..
Reference: Holds the values called pointers, which designates to
the other objects. Ex: REF CURSOR, REF object_datatype.
Lob: Holds the values, which specifies the location of large
objects, such as images and vedios clips. It can stored 4GB of
unstrucrted data. Ex: BLOB,CLOB, BFILE NCLOB.
Can a variable be assigned a value from database? If yes,
then how?
Yes, a variable can be assigned a value from a database. You can
fetch the value from the database and assign it to the variable
using the into keyword, as shown in the following code:
select emp_sal * 0.20 into var_increment from t_employee where
emp_no = emp_id.
Does a NOT NULL constraint of a database column apply to
%TYPE variables?
No, a NOT NULL constraint does not apply to variables declared
using the %TYPE attribute. These variables can be assigned a null
value in a PL/SQL block, as shown in the following code snippet:
DECLARE
var_emp_code t_employee.emp_code%TYPE;
.....
BEGIN
var_emp_code := NULL;

Plsql
Can SQL group functions be used within the procedural
statements?
The SQL group functions, such as AVG, MIN, MAX, COUNT, SUM,
STDDEV, and VARIANCE, cannot be directly used within PL/SQL.
However, they can be embedded within SQL statements and then
can be utilized in the procedural statements.

What is difference b/w sql and plsql?


Sql is the non procedural language that is interact with the
database, and used for data manuplation using the DDL and
DML. Control statement cannot be used in sql.
Where as the plsql is the procedural language, it allows the usage
of cursor control statements and transaction control language.
Control statements:
1.conditional statements: Simple if, if then else, multi if,
nested if.
2.iterative statements:
simple loop: A simple loop repeats a set of statements in the
plsql code block at least once before the loop terminates when
the exit condition is sastified the process exists from the loop.
While loop: First the condition is checked and then the loop is
started. The loop is continuous until the conditi -on remains true.
If the condition becomes false, the loop is completed.
For loop: A for loop is used to execute a set of statements for a
predetermine number of times. The iteration occurs b/w the
given start and end integer values. The counter is always
increme -nted by 1. The loop exists when the counter reaches the
value of the end integer.
5

Plsql
GOTO statement helps to shifting the control from one block of
code to some other block of code within plsql.
Case statement syntax:
CASE SELECTOR
WHEN EXP1 THEN STATMENT1;

WHEN EXP2 THEN STATMENT2; ELSE


STATEMENT N;
END CASE;
Searched case:
CASE
WHEN COND1 THEN STATMENT1;

WHEN COND2 THEN STATMENT2; ELSE


STATEMENT N;
END CASE;
The difference b/w case and searched
case:
CASE statements execution is based on selector in searched CASE
statement execution is based on condition. CASE condition is
based on the = operator . searched CASE condition is based on
otherthan the = operator .
What is the difference b/w decode and case?
Case:
Case is statement. We can use relational operators. It can be used
in subqueries. It can be used in plsql block. It cannot compare the
null values.
6

Plsql
Decode:
Where decode is function. We cannot use relational operators. It
cannot be used in subqueries. It cannot be used in plsql block. It
compare the null values.

CONTINUE Statement:
Similar to the EXIT statement, the CONTINUE statement controls
loop iteration. Whereas the EXIT statement causes a loop to
terminate and passes control of the execution outside the loop,
the CONTINUE statement causes a loop to terminate its current
iteration and passes control to the next iteration of the loop
Describe the use of %ROWTYPE and %TYPE in PL/SQL
Ans: %ROWTYPE allows you to associate a variable with an entire
table row. The %TYPE associates a variable with a single column
type.
Difference between NO DATA FOUND and %NOTFOUND?
NO DATA FOUND is an exception raised only for the SELECT....INTO
statements when the where clause of the querydoes not match
any rows. When the where clause of the explicit cursor does not
match any rows the %NOTFOUND attribute is set to TRUE instead.

Plsql

CURSORS
What Is Cursor?Types Of Cursor? And Diff B/W Cursors?
Ans: The Oracle Engine uses a work area for its internal
processing in order to execute an SQL statement. This work area
is private to SQL operation and is called Cursor .Through the
cursor plsql program can control the context area.
Types of Cursor:
Implicit Cursor: Any given PL/SQL block issues an implicit cursor
when ever a SQL statement is executed, as long as an explicit
cursor does not exist for that SQL statement. The implicit cursor is
used to process INSERT, UPDATE, DELETE, and SELECT INTO
statements. During the processing of an implicit cursor, Oracle
automatically performs the OPEN, FETCH, and CLOSE operations.
Explicit Cursor: The only means of generating an explicit cursor is
to name the cursor in the DECLARE section of the PL/SQL block.
The advantage of declaring an explicit cursor over an indirect
implicit cursor is that the explicit cursor gives the programmer
more programmatic control. Also, implicit cursors are less efficient
than explicit cursors, so it is harder to trap data errors.
The process of working with an explicit cursor consists of the
following steps:
8

Plsql
1. Declaring the cursor. This initializes the cursor into memory.
2. Opening the cursor. The declared cursor is opened, and
memory is allotted.
3. Fetching the cursor. The declared and opened cursor can now
retrieve data.
4. Closing the cursor. The declared, opened, and fetched cursor
must be closed to release the memory allocation Attributes Of a
Implicit Cursor:
%ISOPEN returns TRUE if cursor is open else FALSE. Syntax is
SQL%ISOPEN
%ROWCOUNT--- returns number of records fetched from cursor. if
the cursor has not been opened, a reference to the %ROW
COUNT raises the INVALID CURSOR exception.
syntax is SQL
%ROWCOUNT
%FOUND---- returns TRUE if record is fetched successfully else
FALSE, syntax is SQL%FOUND.
%NOTFOUND-- returns TRUE if record is not fetched successfully
else FALSE syntax is SQL%NOTFOUND
Q.State the advantage and disadvantage of Cursor?
Advantage :
In pl/sql if you want perform some actions more than one records
you should user these cursors only. bye using these cursors you
process the query records. you can easily move the records and
you can exit from procedure when you required by using cursor
attributes.
disadvantage:
using implicit/explicit cursors are depended by sutiation. if the
result set is less than 50 or 100 records it is better to go for
implicit cursors. if the result set is large then you should use
exlicit cursors. other wise it will put burdon on cpu

Plsql

How an Implicit cursor works?


1. Any given PL/SQL block issues an implicit cursor whenever a
SQL
statement is executed, as long as an explicit cursor does not exist
for that
SQL statement.
2. A cursor is automatically associated with every DML (data
manipulation)
statement (UPDATE, DELETE, INSERT).
3. All UPDATE and DELETE statements have cursors that identify
the set of
rows that will be affected by the operation.
4. An INSERT statement needs a place to receive the data that is
to be
inserted into the database the implicit cursor fulfills this need.
5. The most recently opened cursor is called the SQL cursor.

How an Explicit cursor works?


The process of working with an explicit cursor consists of the
following steps:
1. Declaring the cursor. This initializes the cursor into memory.
2. Opening the cursor. The declared cursor is opened, and
memory is allotted.

10

Plsql
3. Fetching the cursor. The declared and opened cursor can now
retrieve data.
4. Closing the cursor. The declared, opened, and fetched cursor
must be closed to
release the memory allocation
What is Ref Cursor?
Ans: A REF CURSOR is basically a data type. A variable created
based on such a data type is generally called a cursor variable. A
cursor variable can be associated with different queries at runtime. The primary advantage of using cursor variables is their
capability to pass result sets between stored procedures.
There are the two types of cursor variables
STRONG: A REF cursor is declared with RETURN type is called.
WEAK : A REF cursor is declared with out RETURN type is called.

Difference b/w cursor and cursor variable:


cursor is static a cursor variable is dynamic. Cursor always point
to the same work area but cursor variable can point to the
different work areas..
What is WHERE CURRENT OF clause?
Use WHERE CURRENT OF clause for both UPDATE AND DELETE
statements inside a cursor. This is used to make changes to the
most recently fetched row of data. The advantage of the WHERE
CURRENT OF clause is that it enables you to eliminate the WHERE
clause in the UPDATE statement:
SQL%IS OPEN always evalutes to false as oracle closes the
implicit cursor as soon as it executes the query.
11

Plsql

INLINE CURSOR:
The for loop allows defining an inline cursor. An inline cursosr is a
cursor that is not declared in the DECLARE section but the cursor
definition is included in the FOR loop.

PARAMATERIZED CURSOR:
A cursor can be declared with parameters. This enables a cursor
to generate a specific result set
that is narrow but also reusable.
. Cursor parameters make the cursor more reusable.
. Cursor parameters can be assigned default values.
. The scope of the cursor parameters is local to the cursor.
CURSOR FOR LOOP:
The cursor FOR loop specifies a sequence of statements to be
repeated once for each row returned by the cursor. Use the cursor
FOR loop if you need to FETCH and PROCESS every record from a
cursor until you want to stop processing and exit the loop.
What is FOR UPDATE clause?
The cursor FOR UPDATE clause is used only with a cursor when
you want to update tables in the database. Generally, when you
execute a SELECT statement, we are not locking any rows. The
purpose of using the FOR UPDATE clause is to lock the rows of the
tables we want to update so that another user cannot perform an
update until we perform our update and release the lock. The next
COMMIT or ROLLBACK statement releases the lock.
Using the FOR UPDATE clause locks these rows that have been
identified in the active set.
If the FOR UPDATE clause is used, rows may not be fetched from
the cursor until a COMMIT has been issued.
12

Plsql

RULES FOR USING CURSOR VARIABLES:


. Cursor variables cannot be defined in a package specification.
. You cannot use cursor variables with remote subprograms on
another server, so you cannot pass cursor variables to a
procedure that is called through a database link.
. Do not use FOR UPDATE with OPEN FOR in processing a cursor
variable.
.You cannot use comparison operators to test cursor variables for
equality, inequality, or nullity.
. A cursor variable cannot be assigned a null value.
. A REF CURSOR type cannot be used in a CREATE TABLE or VIEW
statement, because there is no equivalent data type for a
database column.
. A stored procedure that uses a cursor variable can be used only
as a query block data source;
it cannot be used for a DML block data source. Using a REF
CURSOR is ideal for queries that are dependent only on variations
in SQL statements, not PL/SQL.
. You cannot store cursor variables in an associative array, nested
table, or varray.
. If you pass a host cursor variable to PL/SQL, you cannot fetch
from it on the server side unless
you also open it there on the same server call.
State the advantage and disadvantage of Cursor?
Advantage :
In pl/sql if you want perform some actions more than one records
you should user these cursors only. By using these cursors you
process the query records. you can easily move the records and
13

Plsql
you can exit from procedure when you required by using cursor
attributes.
Disadvantage:
using implicit/explicit cursors are depended by sutiation. if the
result set is les than 50 or 100 records it is better to go for implicit
cursors. if the result set is large then you should use exlicit
cursors. other wise it will put burdon on cpu
What is difference between a Cursor declared in a
procedure and Cursor declared in a package
specification ?
A cursor declared in a package specification is global and can be
accessed by other procedures or procedures in a package. A
cursor declared in a procedure is local to the procedure that can
not be accessed by other procedures.

14

Plsql

TRIGGERS
What is the triggers? Types of triggers?
A database trigger is a named PL/SQL block stored in a database
and executed implicitly when a triggering event occurs. The act of
executing a trigger is called firing the trigger.
DML statements executed against a database table. Such a
trigger can fire before or after a triggering event.
A DDL statement executed either by a particular user against a
schema or by any user.
A system event such as startup or shutdown of the database.
Compound triggers These triggers act as both statement- and
row-level triggers when we insert, update, or delete data from a
table.

1. Row level Triggers:


1.Row level triggers are executed for each record affected by the
DML operations.
2.To make the triggers as row level trigger, declare with FOR
EACH ROW option.
3. if FOR EACH ROW option is not specified to a statement and
the trigger is executed at a statement level.
2.Statement level Triggers:

15

Plsql
1.statement level trigger is executed once per the DML operation,
irrespective of number of records affected by DML operation.
2.it is used when a triggering statement affects rows in a table
but the processing required is completely independent of the
number of rows affected.
What are the uses of triggers?
Enforcing complex business rules that cannot be defined by using
integrity constraints. It Preventing invalid transactions.
What are the Advantages of Triggers?
1) Triggers can be used as an alternative method for
implementing referential integrity constraints
2) By using triggers, business rules and transactions are easy to
store in database
3) It controls on which updates are allowed in a database.
4) When a change happens in a database a trigger can adjust
the change to the entire database.
5) Triggers are used for calling stored procedures.
What are the Disadvantages of Triggers?
1.Triggers can executed every time some fields in database is
updated.
2. Decrease in performance of the database: By the complex
nature of the database programs take more time to execute and
there can be hidden performance downtimes.
What is the difference b/w Triggers and Integrity
constraints?
16

Plsql
INTEGRITY CONSTRAINTS

TRIGGERS

1.It evaludates existing data and 1 .It evaludates only future


future data.
data.
2.I.c behaviour cannot change
because they are predefined
programs.

2.we can change the triggers


behaviour because they are
user created programs.
3.we can drop.

3.W e may not drop the I.C when


they have a dependent data are 4.we can disable all the
constraint
triggers of the table at a time.
4.we cannot disable more than
one constraint at a time.

What is the difference b/w Triggers and stored


procedures?
1. stored procedures can accept parameters while triggers cannot
accept.
2. Triggers cannot return any value while stored procedures can.
3.Triggers is executed automatically on some event while a stored
procedure needs to be explicitly called.
4.Triggers are used for insertions, update and deletions on tables
while stored procedures are often using independently in the
database.
5.Triggers cannot be written in a stored procedures. however, the
reverse is not possible.
17

Plsql
What is the syntax of trigger:
CREATE [OR REPLACE] TRIGGER Ttrigger_name
{BEFORE|AFTER} Triggering_event ON table_name
[FOR EACH ROW]
[FOLLOWS another_trigger] [ENABLE/DISABLE]
[WHEN condition]
DECLARE
declaration statements
BEGIN
executable statements
EXCEPTION
exception-handling statements
END;.
What are the restrictions on triggers when trigger
created?
we need to know about several restrictions before creating a
trigger:
A trigger may not issue a transactional control statement such as
COMMIT, SAVEPOINT, or ROLLBACK. When the trigger fires, all
operations performed become part of a transaction.
When this transaction is committed or rolled back, the operations
performed by the trigger are committed or rolled back as well. An
exception to this rule is a trigger that contains an autonomous
transaction.
Any function or procedure called by a trigger may not issue a
transactional control statement unless it contains an autonomous
transaction.
It is not permissible to declare LONG or LONG RAW variables in
the body of a trigger.
Row-level triggers cannot use a :new or :old pseudo-record, or row
of data, when the column is declared as a LONG or LONG RAW
datatype.
18

Plsql
FOR EACH ROW:
The clause FOR EACH ROW specifies that a trigger is a row trigger
and fires once for each row that is inserted, updated, or deleted.
What is Autonomous transaction ? Where do we use it?
Ans: An autonomous transaction is an independent transaction
that is initiated by another transaction. It must contain at least
one SQL statement.
Autonomous transactions allow a single transaction to be
subdivided into multiple commit/rollback transactions, each of
which will be tracked for auditing purposes.
When an autonomous transaction is called, the original
transaction (calling transaction) is temporarily suspended. The
autonomous transaction must commit or roll back before it
returns control to the calling transaction.
Once changes have been made by an autonomous transaction,
those changes are visible to other transact --tions in the
database. Autonomous transactions can be nested. That is, an
autonomous transaction can operate as a calling transaction,
initializing other autonomous transactions within itself.
What are Transactional Triggers ? Give the uses of
Transactional Trigger ?
Ans: Transactional Triggers fire in response to transaction
processing events. These events represent points during
application processing at which Oracle Forms needs to interact
with the data source. Examples of such events include updating
records, rolling back to save points, and committing transactions.
What is the difference b/w statement level trigger and row
level trigger?
19

Plsql
A trigger if specified FOR EACH ROW; it is fired for each of the
table being affected by the triggering statement. For example if a
trigger needs to be fired when rows of a table are deleted, it will
be fired as many times the rows are deleted.
If FOR EACH ROW is not specified, it is application to a statement
and the trigger is executed at a statement level.
Row-level: - They get fired once for each row in a table affected
by the statements.
Statement: - They get fired once for each triggering statement.
Row Level Trigger Row Level Trigger is fired each time row is
affected by Insert, Update or Delete command. If statement
doesnt affect any row, no trigger action happens.
Statement Level Trigger
This kind of trigger fires when a SQL statement affects the rows of
the table. The trigger activates and performs its activity
irrespective of number of rows affected due to SQL statement.

What is the INSTEAD OF triggers?


views can be manipulated via INSERT, UPDATE, or DELETE
statements, with
some restrictions.
view cannot be modified by an UPDATE, INSERT, or DELETE
statement:
. Set operations such as UNION, UNION ALL, INTERSECT, and
MINUS
. Group functions such as AVG, COUNT, MAX, MIN, and SUM
. GROUP BY or HAVING clauses
. CONNECT BY or START WITH clauses
. The DISTINCT operator
. The ROWNUM pseudo column
.Case statement and decode functions

20

Plsql
PL/SQL provides a special kind of trigger that can be defined on
database views. This trigger is called an INSTEAD OF trigger and
is created as a row trigger.
An INSTEAD OF trigger fires instead of the triggering statement
(INSERT, UPDATE, DELETE) that has been
issued against a view and directly modifies the underlying tables.
What is :old and :new in triggers?
There are two pseudo-records when you use the FOR EACH ROW
clause in a row-level trigger.
They both refer to the columns referenced in the DML statement.
The pseudo-records are composite
variables; new or old are the pseudo-record variable names in the
WHEN clause, and :new and :old
are the bind variables in the trigger body. They differ because the
trigger declaration and body are
separate PL/SQL blocks. The new and old pseudo-records are
declared in scope by the row-level trigger declaration.
The trigger declaration is the calling block, and the trigger body is
the called block. Bind variables are passed by reference between
PL/SQL blocks when an event fires a trigger in a database session.
The elements of the pseudo-record are pseudo-fields.
The new or old pseudo-records are session-level composite
variables. Theyre implicitly declared in the scope of the triggering
event, which is the DML statement.
15.What is FOLLOWS clause triggers?
Suppose you have multiple trigger on the same event on the
same table, for instance when you have a packaged application
where you are not allowed to change any of the code. But you
want to add your own code.
If you add a trigger to an event that already has a trigger on it,
there is no way of knowing when this is executed, before or after
the existing trigger. If you rely on values that may be changed in
21

Plsql
the first trigger there was no way to be sure this trigger had been
fired before your code is executed.
Syntax:
CREATE [ OR REPLACE ] TRIGGER [schema.] trigger
{ simple_dml_trigger
| compound_dml_trigger
| non_dml_trigger
}
[ FOLLOWS [schema.] trigger [[schema.] trigger]...]
[ ENABLE | DISABLE ]
[ WHEN (condition) ]
trigger_body
if you have two (or more) triggers that follow a single trigger. One
table with three triggers in place. Trigger 2 follows trigger 1 and
trigger 3 follows trigger 1 too. Which one gets fired first? lowest
physical number will be fired first.
What is the mutating table and mutating error?( ORA-04091)
Mutating error normally occurs when we are performing some
DML operations and we are trying to select the affected record
from the same trigger. So basically we are trying to select records
in the trigger from the table that owns the trigger. This creates
inconsistency and Oracle throws a mutating error.
Mutation will not occur if a single record is inserted in the table
(using VALUES clause). If bulk insertion is done or data is inserted
from another table mutation will occur.
we can use different ways to handle mutating table errors.
22

Plsql
create statement level trigger instead of row level. If we omit the
for each row clause from above trigger, it will become statement
level trigger.
triggering statement on the table, cannot query the same table
so that trigger cannot see inconsistent data. This restriction
applies to all the row level triggers and hence we run into
mutating table error.
By defining row level trigger as an autonomous transaction, we
can solve mutating table error but result is not correct. The latest
updates are not getting reflected in our result set as oppose to
statement level trigger. So one has to be very careful when using
this approach.
In version 11g, Oracle made it much easier with introduction of
compound triggers.Let us see in this case how a compound
trigger can resolve mutating table error.

Why this is a problem when we are using FOR EACH ROW


clause/statement level trigger?
As per Oracle documentation, the session, which issues a
triggering statement on the table, cannot query the same table so
that trigger cannot see inconsistent data. This restriction applies
to all the row level triggers and hence we run into mutating table
error.

What is the compound triggers?


Compound triggers acts as both statement- and row-level triggers
when you insert, update, or delete data from a table. You can use
a compound trigger to capture information at four timing
points:
(a) before the firing statement;
23

Plsql
(b) before each row change from the firing statement;
(c) after each row change from the firing statement;
(d) after the firing statement.
Compound triggers dont
support filtering actions with the WHEN clause or the use of the
autonomous transaction PRAGMA.
3. Two popular reasons to use compound trigger are:
1.

To accumulate rows for bulk-insertion. We will later see an


example for this.
2.
To avoid the infamous ORA-04091: mutating-table error.
Syntax:
CREATE OR REPLACE TRIGGER compound_trigger_name
FOR [INSERT|DELETE]UPDATE [OF column] ON table
COMPOUND TRIGGER
-- Declarative Section (optional)
-- Variables declared here have firing-statement duration.
--Executed before DML statement
BEFORE STATEMENT IS
BEGIN
NULL;
END BEFORE STATEMENT;
--Executed before each row change- :NEW, :OLD are available
BEFORE EACH ROW IS
BEGIN
NULL;
END BEFORE EACH ROW;
--Executed aftereach row change- :NEW, :OLD are available
AFTER EACH ROW IS
BEGIN
NULL;
24

Plsql
END AFTER EACH ROW;
--Executed after DML statement
AFTER STATEMENT IS
BEGIN
NULL;
END AFTER STATEMENT;
END compound_trigger_name;
Q. Which trigger is more efficient : AFTER or BEFORE ?
A.AFTER row triggers are slightly more efficient than BEFORE row
triggers. With BEFORE row triggers, affected data blocks must be
read (logical read, not physical read) once for the trigger and then
again for the triggering statement. Alternatively, with AFTER row
triggers, the data blocks need only be read once for both the
triggering statement and the trigger.

7.What are the Parts of Triggers ?


A triggers has three basic parts
1.Trigger Event:
1. Triggers fires automatically when an INSERT ,
UPDATE or DELETE statement on a specific table or view.
2. A CREATE, ALTER or DROP statement on
any schema object.
3.A database startup or
instance shutdown

25

Plsql
2.Triggers Restriction:
A trigger constraint specific a boolean expression
that must be TRUE for the trigger to fire. A trigger restriction is
specified using a WHEN clause.
3.Trigger Action:
The trigger action is a pl/sql block that contains the
code specification to be executed when the trigger fires. The
pl/sql code block can hold sql and plsql statements , can define
pl/sql language constructs and call stored procedures.
Can a view be mutating ?if yes, then how?
NO, view cannot be mutating like a table. If an UPDAE
statement fires an INSTEAD OF triggers on a view, the view is not
considered to be mutating. If the UPDATE statement had been
executing on a table, the table would have been considered as
mutating.
What are schema-level triggers/DDL triggers ?
Schema-level triggers are created on schemalevel operations, such as create table, alter table, drop table,
rename, and revoke. These triggers prevent DDL statements,
provide security and monitor the DDL operations.
What is cascading trigger?
When a statement in a trigger body causes another
trigger to be fired, the triggers are said to be cascading. Max = 32

What are two virtual tables available during database


trigger execution?

26

Plsql
The table columns are referred as OLD.column_name and
NEW.column_name. For triggers related to INSERT only
NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name
NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only
available.
What is the DML ERROR log table?
By default, all rows in a single transaction either succeed or fail. If
you insert a large volume of rows in a single insert as select, an
error in one row will force the whole insert to fail.
You can override this behavior via the use of an error log table,
along with special syntax within your commands to tell the
database how to process the errors. Oracle will then automatically
log the entries that failed and the reasons why each row failed
while the transaction itself will succeed.
In a sense this is a multitable insertthe rows that can be
inserted are added to the targeted table whereas the rows that
fail are inserted into the error log table.

27

Plsql

EXCEPTION HANDLING

What is exception handling? What is the types of


exceptions?
Run time errors are called exception. If at any time an error occurs
in the pl/sql block at that point plsql block execution is stopped
and oracle returns an error message. To continue the program
execution and to display user friendly message needs to be
handled, to handle exception include exception block in the plsql
program.
There are the 3 types of exceptions:
1.Pre-defined exceptions
2.Non-predefined exceptions
3.User defined exceptions

1.Pre-defined exceptions:
NO_DATA_FOUND (ORA-01403) When a SELECTINTO clause
does not return any row from a table.
TOO_MANY_ROWS (ORA-01422) When you SELECT or fetch
more than one row into a record or variable.
ZERO_DIVIDE (ORA-01476) When you attempt to divide a
number by zero.
CURSOR_ALREADY_OPEN (ORA-06511) You tried to open a
cursor that is already open.
28

Plsql
INVALID_CURSOR (ORA-01001) Illegal cursor operation
occurred. You tried to reference a cursor that does not yet exist.
This may have happened because youve executed a FETCH
cursor or CLOSE cursor before Opening the cursor.
INVALID_NUMBER (ORA-01722) You tried to execute an SQL
statement that tried to convert a string to a number, but it was
unsuccessful.
DUP_VAL_ON_INDEX (ORA-00001) Attempted to insert a
duplicate value.
LOGIN_DENIED (ORA-01017) You tried to log into Oracle with an
invalid username/password combination.
NOT_LOGGED_ON (ORA-01012) You tried to execute a call to
Oracle before logging in.
VALUE_ERROR (ORA-06502) You tried to perform an operation
and there was an error on a conversion, truncation, or invalid
constraining of numeric or character data.

2.Non-predefined/unnamed exceptions
Those system exception for which oracle does not provide a name
is known as unnamed system exception. These exceptions do not
occur frequently. These Exceptions have a code and an associated
message.
There are two ways to handle unnamed system exceptions:
1. By using the WHEN OTHERS exception handler,
2. By associating the exception code to a name and using it as a
named exception.
We can assign a name to unnamed system exceptions using a
Pragma called EXCEPTION_INIT.EXCEPTION_INIT will associate a

29

Plsql
predefined Oracle error number to a programmer defined
exception name.
Pragma exception_init(err msg, err number);

Steps to be followed to use unnamed system exceptions are


They are raised implicitly.
If they are not handled in WHEN Others they must be handled
explicitly.
To handle the exception explicitly, they must be declared using
Pragma EXCEPTION_INIT as given above and handled referencing
the user-defined exception name in the exception section.
The general syntax to declare unnamed system exception using
EXCEPTION_INIT is:
DECLARE
exception_name EXCEPTION;
PRAGMA
EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
Handle the exception
END;

Functions for Trapping Exceptions:


When an exception occurs, you can identify the associated error
code or error message by using two functions. Based on the
30

Plsql
values of the code or message, you can decide which subsequent
action to take based on the error.
SQLCODE: Returns the numeric value for the error code.
SQLERRM: Returns the message associated with the error
number.
They can be used in exception handling to report or store in error
log table.
These are useful for WHEN OTHERS clause.
You cannot use SQLCODE or SQLERRM directly in a SQL
statement. Instead, you must assign their values to local
variables, then use the variables in the SQL statement, as shown
in the following example:

WHEN OTHERS THEN


err_num := SQLCODE;
err_msg := SUBSTR(SQLERRM, 1, 100);
INSERT INTO errors VALUES (err_num, err_msg);

3.User defined exceptions:


RAISE STATEMENT:
Exception must be declared in declaration section.
Raise<exception name>
RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to
display the user-defined error messages along with the error number whose range is
in between -20000 and -20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all
previous transactions which are not committed within the PL/SQL Block are rolled
back automatically (i.e. change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
31

Plsql
RAISE_APPLICATION_ERROR is used for the following reasons,
a) to create a unique id for an user-defined exception.
b) to make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:
RAISE_APPLICATION_ERROR (error_number, error_message);

The Error number must be between -20000 and -20999


The Error_message is the message you want to display when the error occurs.
RAISE_APPLICATION_ERROR can be used in either (or both) the executable
section and the exception section of a PL/SQL program. The returned error is
consistent with how the Oracle server produces a predefined, nonpredefined, or
user-defined error. The error number and message is displayed to the user.

What is Exception propagation in Oracle?


Exceptions which are not handled in a sub block get propagated to the outer block.
When an exception occurs, it terminates from the line where the exception occurs
and the control goes to the calling program or the next outer block. If not handled in
the outer block, it terminates that block and propagates to the next outer block and
so on. And, if exception occurs in the outermost block, then the whole program gets
terminated.

What is the WHEN OTHERS clause in oracle?


The WHEN OTHERS clause is used to trap all remaining exceptions
that have not been handled by your Named System Exceptions
and Named Programmer-Defined Exceptions.
EXCEPTION
32

Plsql
WHEN exception_name1 THEN
[statements]
WHEN exception_name2 THEN
[statements]
WHEN exception_name_n THEN
[statements]
WHEN OTHERS THEN
[statements]

33

Plsql

PROCEDURES
What is procedure? What is advantages and
disadvantages?
1.

Stored procedures:
a. Stored procedures represent named blocks (as opposed to
anonymous blocks) that are capable of accepting parameters
and work on them.
b. Stored procedures do not have to return a value. Hence,
they cannot be called from inside an SQL statement. Stored
procedures must be executed from a PL/SQL block- named or
anonymous.
d. Merits:

A procedure does not have to return a value (This can


be a demerit too).

Can be used to perform a series of DML or DDL (yes,


this is possible through dynamic SQL with a few restrictions)
operations.

Can be simply called as an independent statement from


a PL/SQL block. e.g. myProcedure (x, y);

e. Demerits:

34

Plsql

Cannot be called from an SQL query - DML or


a SELECT statement.

Cannot be used in indexes.


Advantages
* Reduce network usage between clients and servers stored
procedures perform intermediate processing on the database
server reducing unnecessary data transfer across the network.
*Improved security database administrator can control the
users who access the stored procedure
*Reduced development cost and increased reliability
*Stored procedures are tunable to improve the performance.
When same stored procedure executed again, it can use the
previously cached execution plans
Disadvantages
*Writing and maintaining stored procedures requires more
specialized skills.
*There are no debuggers available for stored procedures
* Stored procedure language may differ from one database
system to another.
* Poor exception handling
* Sometimes it is hard to understand the logic written in dynamic
SQL.
Procedure and function overloading is available only within
database packages or as PL/SQL sub-blocks. Database stored
procedures cannot be overloaded.

What is the difference between Procedures and Functions?


35

Plsql
PROCEDURES V FUNCTIONS
1. Function is mainly used in the case where it must return a
value. Where as a procedure may or may not return a value or
may return more than one value using the OUT parameter.
2. Function can be called from SQL statements where as
procedure can not be called from the sql statements
3. Functions are normally used for computations where as
procedures are normally used for executing business logic.
4. You can have DML (insert,update, delete) statements in a
function. But, you cannot call such a function in a SQL query.
5. A Function returns 1 value as return type ( If you want more
return values you can declare OUT parameters). Procedure can
return multiple values (max 1024).

1.Procedures may return through out and in out parameters


where as function must return.
2.Procedures may or may not return value where as functions
must.
3.We can use call statement directly for executing procedure
where as we need to declare a variable in case of functions.
4.Functions can use in select statements where as procedures
cannot.
5.Functions can call from reports environment where as
procedures cannot.
6.We can use exec for executing procedures where as functions
cannot.

36

Plsql
7.Function can be used in dbms_output where as procedure
cannot.
8.Procedure call is a standalone executable statement where as
function call is a part of an executable statement.

What is the difference b/w stored procedure and local


procedure?
1.The stored subprogram is stored in compiled p-code in the
database, when the procedure is called it does not have to be
compiled.
2.The local subprogram is compiled as part of its containing block.
If the containing block is anonymous and is run multiple times,
the subprogram has to be compiled each time.
3.Standalone stored subprograms cannot be overloaded, but
packaged subprograms can be overloaded within the same
package.
4.Local subprograms can be overloaded within the same block.
What is the AUTHID property? Define invoker and definer?
A stored program executes under the authority of its owner, or
definer. By default it is definer rights. Whenever we run a program
compiled with the definer rights model, its SQL executes under
the authority of the schema that owns the program.
Although direct grants are needed to compile a program, you
can grant EXECUTE authority to give other schemas and roles the
ability to run our program.
Advantages of definer rights
Application performance improves dramatically because the
PL/SQL engine does
not have to perform checks at runtime to determine if you have
the appropriate
37

Plsql
privileges or not.
Disadvantages of definer rights
But there are problems with the definer rights model as well.
These are explored in the next sections.
Sometimes, your programs should execute using the privileges of
the person running
the program and not the owner of the program. In such cases, you
should choose the invoker rights model.
Rules and restrictions on invoker rights:
Invoker rights resolution of external references will work for the
following kinds
of statements:
SELECT, INSERT, UPDATE, MERGE, and DELETE data
manipulation
Statements.
LOCK TABLE transaction control statement
OPEN and OPEN FOR cursor control statements
EXECUTE IMMEDIATE and OPEN FOR USING dynamic SQL
statements
SQL statements parsed using DBMS_SQL.PARSE
Pass by value, Pass by reference
Whenever we are using modular programming, all languages
supports two types of passing parameter pass-by-value, pass-byreference.
when we are modifying formal parameters, the actual
parameters will be effected or not. In pass-by-value mechanism,
passing values does not change because copy of values are
passed into called program.
If you want to change actual parameters, we are using pass-byreference method. Internally when we are using pass-by-value,
different memory locations are created for corresponding actual,
38

Plsql
formal parameters and also copy of values are passed from actual
to formal parameters.
Whereas in pass-by reference method, a single memory location
is allocated and also only address is passed into formal
parameters.
Oracle also supports these mechanisms when we are using
procedure parameters. By default IN mode is pass-by-reference
and OUT, IN OUT modes are pass-by-value.
Whenever we are returning large amount of data through the OUT
parameter again copy of values are created because internally
this is pass-by-value. To overcome this problem Oracle 8.1
introduced nocopy hint in OUT, IN OUT parameters.

1) IN parameter:
We can pass values to the stored procedure through these
parameters or variables. This type of parameter is a read only
parameter. We can assign the value of IN type parameter to a
variable or use it in a query, but we cannot change its value
inside the procedure.
2) OUT Parameter:
The OUT parameters are used to send the OUTPUT from a
procedure or a function. This is a write-only parameter i.e, we
cannot pass values to OUT parameters while executing the stored
procedure, but we can assign values to OUT parameter inside the
stored procedure and the calling program can recieve this output
value.

39

Plsql
3) IN OUT Parameter:
The IN OUT parameter allows us to pass values into a procedure
and get output values from the procedure. This parameter is used
if the value of the IN parameter can be changed in the calling
program.
By using IN OUT parameter we can pass values into a parameter
and return a value to the calling program using the same
parameter. But this is possible only if the value passed to the
procedure and output value have a same datatype. This
parameter is used if the value of the parameter will be changed in
the procedure.

What is a forward declaration ? What is its use ?


Ans: PL/SQL requires declare an identifier before using it. We
must declare a subprogram before calling it. This declaration at
the start of a subprogram is called forward declaration. A forward
declaration consists of a subprogram specification terminated by
a semicolon.
Forward declaration can be used to define subprograms in logical
or alphabetical order. And define mutually recursive subprograms.
Why do stored procedures reduce network traffic ?
When a stored procedure is called, only the procedure call is sent
to the server and not the statements that the procedure contains.

Why should I use packages instead if standalone


procedures or functions?

We only need to grant EXECUTE on a package rather than on several


procedures.
40

Plsql

What is difference between a formal and an actual


parameter
The variables declared in the procedure and which are passed, as
arguments are called actual, the parameters in the procedure
declaration. Actual parameters contain the values that are passed
to a procedure and receive results. Formal parameters are the
placeholders for the values of actual parameters
Methods for Passing Parameters
Actual parameters could be passed in three ways:

Positional notation

Named notation

Mixed notation

POSITIONAL NOTATION
In positional notation, you can call the procedure as:
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for
the first formal parameter; the second actual parameter is
substituted for the second formal parameter, and so on. So, a is
substituted for x, b is substituted for y, c is substituted for z and d
is substituted for m.
NAMED NOTATION
In named notation, the actual parameter is associated with the
formal parameter using the arrow symbol ( => ). So the
procedure call would look like:
41

Plsql
findMin(x=>a, y=>b, z=>c, m=>d);
MIXED NOTATION
In mixed notation, you can mix both notations in procedure call;
however, the positional notation should precede the named
notation.
The following call is legal:
findMin(a, b, c, m=>d);
But this is not legal:
findMin(x=>a, b, c, d);

What is NOCOPY hint? What is advantages?


NOCOPY is a hint to the PL/SQL compiler to pass OUT and IN OUT
parameters by reference instead of by value. The use of NOCOPY
saves on the processing and memory overhead of copying data
from subprogram to calling program.
OUT and IN OUT parameters using NOCOPY, parameter values
may get modified even if the subprogram exits with error, since
any changes made to the parameters inside the subprogram are
immediately copied to actual parameters of the calling program.
To complicate things further, because NOCOPY is only a hint, one
cannot know for certain if NOCOPY passed parameters to the
subprogram by value or by reference. If the subprogram exits with
error, the values of the parameters become unpredictable.
Use NOCOPY when both of these conditions are true:
the OUT or IN OUT parameters of a subprogram use large data
structures causing performance issues in parameter passing

42

Plsql
the calling program can ignore the parameter values returned by
the subprogram if the subprogram exits with error.
Why is NOCOPY called a hint, not a command?
NOCOPY is called a hint because unlike with a command, it is not
mandatory for the PL/SQL compiler to honor the hint all the time.
How to find out the exact error line number?
If we use SQLERRM in EXCEPTION block than it can show what
exception was raised. We will never know in which line exception
was thrown.
Best approach will be to use combination of SQLERRM and
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE()
Ex:
EXCEPTION WHEN OTHERS THEN
.
vr_sqlerrm := SUBSTR( SQLERRM||
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(),0,999);
raise_application_error(-20003,EXCEPTION is --> 'vr_sqlerrm);

43

Plsql

44

Plsql

FUNCTIONS
What is a Function in PL/SQL?
A function is a named PL/SQL Block which is similar to a
procedure. The major difference between a procedure and a
function is, a function must always return a value, but a procedure
may or may not return a value.
Advantages of Functions:
The ability to store functions within the Oracle database allows
you to reach great heights in modularity, maintainability, and
performance improvement. Using functions to accomplish specific
tasks improves the reliability of other modules and reduces
development time.
Disadvantages of Funcitons:
You can have DML(insert, update, delete) statements in a
function. But, you cannot call such a function in a SQL query. *Eg:
If you have a function that is updating a table, you can't call that
function in any SQL query.
General Syntax to create a function is
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
45

Plsql
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
PL/SQL Recursive Functions
We have seen that a program or subprogram may call another
subprogram. When a subprogram calls itself, it is referred to as a
recursive call and the process is known as recursion.

What are Requirements for calling functions in SQL?


All of the functions parameters must use the IN mode. Neither
IN OUT nor OUT parameters are allowed in SQL stored functions.
The function must be stored in the database. A function defined
in a client-side
PL/SQL environment cannot be called from within SQL; there
would be no way
for SQL to resolve the reference to the function.

2.What are the restrictions for using a function within


PL/SQL?

46

Plsql
Answer: Here are some function restrictions for all PL/SQL userdefined functions:
1.Deterministic function required: A function must have the
deterministic key word if used with SQL.
2.No updates inserts or deletes from inside DML: A PL/SQL
function is restricted against writing to the database with DML if
the function resides within a DML.
3.No DDL allowed: A function called from inside a SQL statement
is restricted against DDL because DDL issues an implicit commit.
You cannot issue any DDL statements from within a PL/SQL
function.
4.Restrictions against constraints: You cannot use a function in
the check constraint of a create table DDL statement.
5.No commits or IN, OUT parms: When called from within a SQL
query, a function cannot have OUT or IN parameters, and the
function is restricted against using a commit.
1.DETERMINISTIC:
DETERMINISTIC to indicate that the function returns the same
result value whenever it is called with the same values for its
parameters.
We can declare a package-level subprogram DETERMINISTIC in
the package specification but not in the package body.
We cannot declare DETERMINISTIC a private subprogram
(declared inside another subprogram or inside a package body).
2.PIPELINED { IS | USING }:
PIPELINED to instruct the database to return the results of a table
function iteratively. A table function returns a collection type (a
nested table or varray). You query table functions by using the
47

Plsql
TABLE keyword before the function name in the FROM clause of
the query.
If you specify the keyword PIPELINED alone (PIPELINED IS ...), then
the PL/SQL function body should use the PIPE keyword. This
keyword instructs the database to return single elements of the
collection out of the function, instead of returning the whole
collection as a single value.

Parallel Enabled
Parallel enabled table functions can improve performance by
sharing their workload between slave processes. To parallel
enable a function, it must internally define a method for
partitioning the workload, and the following conditions must be
met:
The function must include a PARALLEL_ENABLE clause.
A single REF CURSOR must be specified with a PARTITION BY
clause. Only strongly typed REF CURSORs can be specified in a
PARTITION BY clause that specifies a partition column, but weakly
typed REF CURSORs can be used with the PARTITION BY ANY
clause.

Result cache:
To enable result caching for a function, use the RESULT_CACHE
clause. When a result-cached function is invoked, the system
checks the cache.
If the cache contains the result from a previous call to the
function with the same parameter values, the system returns the
cache result to the invoker and does not re-execute the function
body.
48

Plsql
If the cache not contain the result, the system executes the
function body and adds the result to the cache before returning
control to the invoker.
If function execution results in an unhandled exception, the
exception result is not stored in the cache.
How to use the result cache?
Oracle notes that the result_cache functionality can be enabled in
two ways:
Alter session - you can issue the command "alter session cache
results;" to cache your session data.
PL/SQL - You can create a PL/SQL function using the result_cache
keyword to store the result, and use the new relies_on keyword
to tell Oracle what tables will trigger an invalidation (should the
rows become out-of-date with the current table data).
SQL - You can add the /*+ result_cache */ hint to any SQL
statement, and invoking the result_cache hint is far easier than
creating a PL/SQL array or materialized view because the syntax
is very straightforward:
select /*+ result_cache */
stuff
from tab1 natural join tab2;
Result Cache: Unsupported
EX:
/* File on web: 11g_frc_simple_demo.sql */
FUNCTION betwnstr (
string_in IN VARCHAR2, start_in IN INTEGER, end_in IN INTEGER)
49

Plsql
RETURN VARCHAR2 RESULT_CACHE
Being one of the trump features of Oracle 11g, result cache still
provides no support for

Temporary tables

Sequences

Pseudo columns

Date/Time functions

Table Functions
A table function is a function that can be called from within the
FROM clause of a query.
Perform very complex transformations of data, requiring the use
of PL/SQL, but
need to access that data from within an SQL statement.
Pass complex result sets back to the host (that is, non-PLSQL)
environment. You
can open a cursor variable for a query based on a table function,
and let the host
environment fetch through the cursor variable.
There are two kinds of table functions that merit special mention
and attention in our
50

Plsql
examples:
Streaming table functions
Data streaming means that you can pass from one process or
stage to another
without having to rely on intermediate structures.
Pipelined table functions
These functions return a result set in pipelined fashion, meaning
that data is returned while the function is still executing. Add the
PARALLEL_ENABLE to a
pipelined functions header, and you have a function that will
execute in parallel
within a parallel query.

PACKAGES
What is package specification and package body?
A Package is a database object that groups logically related
PL/SQL types, objects and subprograms. Packages usually have 2
parts - specification & body.
The specification is the interface to our applications; it declares
the types, variables, constants, exceptions, cursors and
subprograms available for use.
51

Plsql
The Body fully defines cursors and subprograms, and so
implements the Specification. Unlike subprograms, packages
cannot be called, passed parameters, or nested.
A Package might include a collection of procedures. Once written,
general-purpose package is compiled, and then stored in an
ORACLE database,

Advantages of Packages:
Modularity: Modularization is the process by which you break up
large blocks of code into smaller pieces (modules) that can be
called by other modules.
Easier Application design: Initially once the Specification has
been compiled, the Body need not be fully defined until one is
ready to complete the application.
Information hiding: Certain procedures can be made as Public
(visible and accessible) and others as Private (hidden and
inaccessible).
Added Functionality: Packaged public variables and cursors
persist for the duration of a session. So, they can be shared by all
procedures that execute in the environment. Also, they allow we
to maintain data across transactions without having to store it in
the database.
Better Performance: When we call a package for the first time,
the whole package is loaded into memory. Therefore, subsequent
calls to related procedures in the package require no disk I/O.

Disadvantages:

52

Plsql
More memory may be required on the Oracle database server
when using Oracle PL/SQL packages as the whole package is
loaded into memory as soon as any object in the package is
accessed.
Updating one of the functions/procedures will invalid other objects
which use different function/procedures since whole package
need to be compiled.
What is the difference b/w public procedure and private
procedure?
Any procedure that is declared and defined ONLY in the package
body is a private procedure. This procedure is local to the
package and other procs cannot call any
private procedure.
if the procedure is declared in the package specification and
defined in the package body it is a public procedure, this is
accessible to other procs also.
Global Variables: The variable defined inside Package
Specification are treated as Global variables, that can be
referenced outside the package and is visible to external users.
Global package items must be declared in the package
specification.
What packages (if any) has Oracle provided for use by
developers?
Oracle provides the DBMS_ series of packages. There are many
which developers should be aware of such as DBMS_SQL,
DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK, DBMS_ALERT,
DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL,UTL_FILE.
Local modules can be called only from within the block in which
they are defined; package modules can at a minimum be called
53

Plsql
from anywhere in the package. If the package modules are also
listed in the package specification, they can be called by other
program units from schemas that have EXECUTE authority on that
package.
Question: I have a PL/SQL procedure and I cannot understand
why my output is wrong. How do I debug a PL/SQL program?
Does Oracle have a PL/SQL debugging tool? How can I manually
perform PL/SQL debugging?
Answer: PL/SQL an interpreted language and syntax and
semantic errors are discovered at compile time, and execution
errors are encountered at run time. You may see these types of
PL/SQL errors:
Syntax errors: These are indicated by the "Warning: Procedure
created with compilation errors" message. You can display the
error with the "show errors" SQL*Plus command).
Semantic errors: These are invalid table or column names.
Run time errors: This is a a non-zero Oracle database error
code.
PL/SQL is just like any other procedural language and you can
insert display statements (using dbms_output.put_line) and step
through the code and see exactly how the values of variables are
changing. This is the easiest form of PL/SQL debugging.
Syntax errors: Use the "show errors" command
Use display statements
we can
insert dbms_output.put_line andutl_file.put_line statements to
display variable states. But advanced PL/SQL can be
problematic. The display components of PL/SQL
(dbms_output and utl_file) provide limited PL/SQL debugging
capabilities.
54

Plsql
Use dbms_debug - More complex instrumenting of PL/SQL can
also be accomplished using the dbms_debug online debugging.
Use dbms_profiler - The dbms_profiler package can aid in
PL/SQL debugging.
Conditional Compilation - In Oracle10g, PL/SQL conditional
compilationis ideal for debugging PL/SQL.
PL/SQL debugger - You can use Oracle's PL/SQL debugger (part
of the free SQL Developer suite) to step through the PL/SQL code,
one line at a time, and find any error.
Is it possible to write a package specification without a
package body?
Yes, it is possible to write a package specification without a
package body but not the vice versa. This is specifically used if
there is a package, which is only used for the declaration of public
variables, types, constants, and exceptions. In such case, there is
no need for a package body and only package specification is
enough.
Can a complete package be called?
No, a complete package is not possible to call, invoke, or
parametrize, however, any construct from the package can be
called or invoked.
Is it possible to write a package specification without a
package body? | PL SQL
Yes, it is possible to write a package specification without a
package body but not the vice versa. This is specifically used if
there is a package, which is only used for the declaration of public
variables, types, constants, and exceptions. In such case, there is
55

Plsql
no need for a package body and only package specification is
enough.

what is a One-Time-Only procedure and how is it declared


within a package A One-Time-Only procedure is executed only
once, when the package is called for the first time. While
declaring a One-Time-Only procedure the keyword END is not
used at the end of the one-time-only procedure however, the
procedure uses the package body's END clause, as the
procedure's code is placed at the bottom of the package body.

When does a subprogram need recompilation?


When any database object associated with the subprogram
changes, the program needs to be recompiled. When the program
is executed the next time, after the object is changed, the system
will automatically perform runtime recompilation.
To avoid this performance overhead, it is better to explicitly
recompile the subprogram using the ALTER [PROCEDURE |
FUCNTION] command, as shown in the following statement: ALTER
PROCEDURE proc_get_marks compile;

56

Plsql

ORACLE SUPPLIED PACKAGES:


1.DBMS_ALERT
The DBMS_ALERT package provides support for the asynchronous
notification of database events (alerts). By appropriate use of this
package and database triggers, an application can cause itself to
be notified whenever values of interest in the database are
changed. Alerts are transaction-based. This means that the
waiting session does not get alerted until the transaction
signalling the alert commits. There can be any number of
concurrent signallers of a given alert, and there can be any
number of concurrent waiters on a given alert.

Table 13-3 DBMS_ALERT


Package Subprograms
Subprogram
REGISTER Procedure
REMOVE Procedure
REMOVEALL Procedure
SET_DEFAULTS Procedure

Description
Receives messages from
an alert
Disables notification from
an alert
Removes all alerts for this
session from the
registration list
Sets the polling interval

57

Plsql
SIGNAL Procedure
WAITANY Procedure

WAITONE Procedure

Signals an alert (send


message to registered
sessions)
Waits timeout seconds to
receive alert message
from an alert registered
for session
Waits timeout seconds to
receive message from
named alert

2.DBMS_PIPE
The DBMS_PIPE package lets two or more sessions in the same
instance communicate. Oracle pipes are similar in concept to the
pipes used in UNIX, but Oracle pipes are not implemented using
the operating system pipe mechanisms.
Information sent through Oracle pipes is buffered in the system
global area (SGA). All information in pipes is lost when the
instance is shut down.

Table 70-2 DBMS_PIPE Package


Subprograms
Subprogram
CREATE_PIPE Function

Description
Creates a pipe (necessary
for private pipes)
Returns datatype of next
item in buffer
Builds message in local
buffer

NEXT_ITEM_TYPE Function
PACK_MESSAGE Procedures
58

Plsql
PURGE Procedure

Purges contents of named


pipe
Copies message from
named pipe into local buffer
Removes the named pipe
Purges contents of local
buffer
Sends message on named
pipe: This implicitly creates
a public pipe if the named
pipe does not exist

RECEIVE_MESSAGE Function
REMOVE_PIPE Function
RESET_BUFFER Procedure
SEND_MESSAGE Function

UNIQUE_SESSION_NAME Function
UNPACK_MESSAGE Procedures

Returns unique session


name
Accesses next item in buffer

Difference b/w Dbms_Alert & Dbms_Pipe.


The DBMS_ALERT package provides support for the asynchronous
notification of database events (alerts). By appropriate use of this
package and database triggers, an application can cause itself to
be notified whenever values of interest in the database are
changed. Alerts are transaction-based. This means that the
waiting session does not get alerted until the transaction
signalling the alert commits. There can be any number of
concurrent signallers of a given alert, and there can be any
number of concurrent waiters on a given alert.
The DBMS_PIPE package lets two or more sessions in the same
instance communicate. Oracle pipes are similar in concept to the
pipes used in UNIX, but Oracle pipes are not implemented using
the operating system pipe mechanisms.

59

Plsql
Information sent through Oracle pipes is buffered in the system
global area (SGA). All information in pipes is lost when the
instance is shut down.
Depending upon wer security requirements, we may choose to
use either a public or a private pipe.

3.DBMS_DEBUG
In order to debug server-side code, it is necessary to have two
database sessions: one session to run the code in debug-mode
(the target session), and a second session to supervise the target
session (the debug session).
ALTER SESSION SET PLSQL_DEBUG = true;
ALTER [PROCEDURE | FUNCTION | PACKAGE | TRIGGER | TYPE]
<name> COMPILE DEBUG;

Table 30-5 DBMS_DEBUG


Package Subprograms
Subprogram
ATTACH_SESSION Procedure

Description
Notifies the debug session
about the target debugID
CONTINUE Function
Continues execution of the
target program
DEBUG_OFF Procedure
Turns debug-mode off
DEBUG_ON Procedure
Turns debug-mode on
DELETE_BREAKPOINT Function Deletes a breakpoint
DELETE_OER_BREAKPOINT
Deletes an OER breakpoint
Function
60

Plsql
DETACH_SESSION Procedure
DISABLE_BREAKPOINT
Function
ENABLE_BREAKPOINT
Function
EXECUTE Procedure
GET_INDEXES Function
GET_MORE_SOURCE
Procedure
GET_LINE_MAP Function
GET_RUNTIME_INFO Function
GET_TIMEOUT_BEHAVIOUR
Function
GET_VALUE Function
INITIALIZE Function
PING Procedure
PRINT_BACKTRACE Procedure
PRINT_INSTANTIATIONS
Procedure
PROBE_VERSION Procedure
SELF_CHECK Procedure
SET_BREAKPOINT Function
SET_OER_BREAKPOINT
Function
SET_TIMEOUT Function

Stops debugging the target


program
Disables a breakpoint
Activates an existing
breakpoint
Executes SQL or PL/SQL in
the target session
Returns the set of indexes for
an indexed table
Provides additional source in
the event of buffer overflow
when using SHOW_SOURCE
Returns information about
line numbers in a program
unit
Returns information about
the current program
Returns the current timeout
behavior
Gets a value from the
currently-running program
Sets debugID in target
session
Pings the target session to
prevent it from timing out
Prints a stack backtrace
Prints a stack backtrace
Returns the version number
of DBMS_DEBUG on the
server
Performs an internal
consistency check
Sets a breakpoint in a
program unit
Sets an OER breakpoint
Sets the timeout value
61

Plsql
SET_TIMEOUT_BEHAVIOUR
Procedure
SET_VALUE Function
SHOW_BREAKPOINTS
Procedures
SHOW_FRAME_SOURCE
Procedure
SHOW_SOURCE Procedures
SYNCHRONIZE Function
TARGET_PROGRAM_RUNNING
Procedure

Tells Probe what to do with


the target session when a
timeout occurs
Sets a value in the currentlyrunning program
Returns a listing of the
current breakpoints
Fetches the frame source
Fetches program source
Waits for program to start
running
Returns TRUE if the target
session is currently executing
a stored procedure,
or FALSE if it is not

4.UTL_FILE
UTL_FILE is available for both client-side and server-side PL/SQL.
Both the client (text I/O) and server implementations are subject
to server-side file system permission checking.
UTL_FILE
Subprograms
Subprogram
FCLOSE Procedure
FCLOSE_ALL Procedure
FCOPY Procedure
FFLUSH Procedure
FGETATTR Procedure
FGETPOS Function

Description
Closes a file
Closes all open file handles
Copies a contiguous portion of a file to
a newly created file
Physically writes all pending output to
a file
Reads and returns the attributes of a
disk file
Returns the current relative offset
62

Plsql
FOPEN Function
FOPEN_NCHAR Function
FREMOVE Procedure
FRENAME Procedure
GET_LINE Procedure
GET_LINE_NCHAR
Procedure
GET_RAW Function
IS_OPEN Function
NEW_LINE Procedure
PUT Procedure
PUT_LINE Procedure
PUT_LINE_NCHAR
Procedure
PUT_NCHAR Procedure

position within a file, in bytes


Opens a file for input or output
Opens a file in Unicode for input or
output
Deletes a disk file, assuming that you
have sufficient privileges
Renames an existing file to a new
name, similar to the UNIX mv function
Reads text from an open file
Reads text in Unicode from an open
file
Reads a RAW string value from a file
and adjusts the file pointer ahead by
the number of bytes read
Determines if a file handle refers to an
open file
Writes one or more operating systemspecific line terminators to a file
Writes a string to a file
Writes a line to a file, and so appends
an operating system-specific line
terminator
Writes a Unicode line to a file
Writes a Unicode string to a file

5. DBMS_UTILITY
DBMS_UTILITY Package
Subprograms
Subprogram
ACTIVE_INSTANCES
Procedure
ANALYZE_DATABASE
Procedure

Description
Returns the active instance
Analyzes all the tables, clusters,
and indexes in a database [see
also Deprecated Subprograms]
63

Plsql
ANALYZE_PART_OBJECT
Procedure
ANALYZE_SCHEMA Procedure

Analyzes the given tables and


indexes
Analyzes all the tables, clusters,
and indexes in a schema [see
also Deprecated Subprograms]
CANONICALIZE Procedure
Canonicalizes a given string
COMMA_TO_TABLE
Converts a comma-delimited list
Procedures
of names into a PL/SQL table of
names
COMPILE_SCHEMA Procedure Compiles all procedures,
functions, packages, and triggers
in the specified schema
CREATE_ALTER_TYPE_ERROR_ Creates an error table to be used
TABLE Procedure
in theEXCEPTION clause of
the ALTER TYPE statement
CURRENT_INSTANCE Function Returns the current connected
instance number
DATA_BLOCK_ADDRESS_BLO Gets the block number part of a
CK Function
data block address
DATA_BLOCK_ADDRESS_FILE Gets the file number part of a
Function
data block address
DB_VERSION Procedure
Returns version information for
the database
EXEC_DDL_STATEMENT
Executes the DDL statement
Procedure
in parse_string
FORMAT_CALL_STACK
Formats the current call stack
Function
FORMAT_ERROR_BACKTRACE Formats the backtrace from the
Function
point of the current error to the
exception handler where the
error has been caught
FORMAT_ERROR_STACK
Formats the current error stack
Function
GET_CPU_TIME Function
Returns the current CPU time in
100th's of a second
GET_DEPENDENCY Procedure Shows the dependencies on the
object passed in.
GET_HASH_VALUE Function
Computes a hash value for the
given string
64

Plsql
GET_PARAMETER_VALUE
Function

Gets the value of specified


init.ora parameter

6.DBMS_JOB:
DBMS_JOB supports multi-instance execution of jobs. By default
jobs can be executed on any instance, but only one single
instance will execute the job. In addition, you can force instance
binding by binding the job to a particular instance. You implement
instance binding by specifying an instance number to the instance
affinity parameter.

DBMS_JOB Package
Subprograms
Subprogram
BROKEN Procedure
CHANGE Procedure
INSTANCE Procedure
INTERVAL Procedure
NEXT_DATE Procedure
REMOVE Procedure
RUN Procedure
SUBMIT Procedure
USER_EXPORT
Procedures
WHAT Procedure

Description
Disables job execution
Alters any of the user-definable
parameters associated with a job
Assigns a job to be run by a instance
Alters the interval between executions
for a specified job
Alters the next execution time for a
specified job
Removes specified job from the job
queue
Forces a specified job to run
Submits a new job to the job queue
Re-creates a given job for export, or
re-creates a given job for export with
instance affinity
Alters the job description for a
specified job

65

Plsql

7.DBMS_OUTPUT
DBMS_OUTPUT
Package
Subprograms
Subprogram
DISABLE Procedure
ENABLE Procedure
GET_LINE Procedure
GET_LINES Procedure
NEW_LINE Procedure
PUT Procedure
PUT_LINE Procedure

Description
Disables message output
Enables message output
Retrieves one line from buffer
Retrieves an array of lines from
buffer
Terminates a line created
with PUT
Places a line in the buffer
Places partial line in buffer

8.DBMS_DDL:
DBMS_DDL Package
Subprograms
Subprogram
ALTER_COMPILE
Procedure
ALTER_TABLE_NOT_REFER
ENCEABLE Procedure
ALTER_TABLE_REFERENCE
ABLE Procedure

Description
Compiles the PL/SQL object
Reorganizes object tables
Reorganizes object tables

66

Plsql
CREATE_WRAPPED
Procedures

IS_TRIGGER_FIRE_ONCE
Function
SET_TRIGGER_FIRING_PR
OPERTY Procedure

Takes as input a
single CREATE OR REPLAC
Estatement that specifies
creation of a PL/SQL package
specification, package body,
function, procedure, type
specification or type body,
generates
a CREATE OR REPLACE stat
ement with the PL/SQL
source text obfuscated and
executes the generated
statement
Returns TRUE if the
specified DML or DDL trigger
is set to fire once. Otherwise,
returns FALSE
Sets the specified DML or
DDL trigger's firing property

9.DBMS_TRANSCATION:
DBMS_TRANSACT
ION Package
Subprograms
Subprogram
ADVISE_COMMIT
Procedure
ADVISE_NOTHING
Procedure
ADVISE_ROLLBACK
Procedure

Description
Equivalent to the SQL statement:
ALTER SESSION ADVISE COMMIT
Equivalent to the SQL statement:
ALTER SESSION ADVISE NOTHING
Equivalent to the SQL statement:
ALTER SESSION ADVISE
ROLLBACK

67

Plsql
BEGIN_DISCRETE_T
RANSACTION
Procedure
COMMIT Procedure
COMMIT_COMMENT
Procedure
COMMIT_FORCE
Procedure
LOCAL_TRANSACTI
ON_ID Function
PURGE_LOST_DB_E
NTRY Procedure
PURGE_MIXED
Procedure
READ_ONLY
Procedure
READ_WRITE
Procedure
ROLLBACK
Procedure
ROLLBACK_FORCE
Procedure

Sets "discrete transaction mode" for


this transaction
Equivalent to the SQL statement:
COMMIT
Equivalent to the SQL statement:
COMMIT COMMENT <text>
Equivalent to the SQL statement:
COMMIT FORCE <text>,
<number>"
Returns the local (to instance) unique
identifier for the current transaction
Enables removal of incomplete
transactions from the local site when
the remote database is destroyed or
re-created before recovery completes
Deletes information about a given
mixed outcome transaction
Equivalent to the SQL statement:
SET TRANSACTION READ ONLY
equivalent to the SQL statement:
SET TRANSACTION READ WRITE
Equivalent to the SQL statement:
ROLLBACK
Equivalent to the SQL statement:

ROLLBACK FORCE <text>


ROLLBACK_SAVEPOI Equivalent to the SQL statement:
NT Procedure
ROLLBACK TO SAVEPOINT <savep
oint_name>
SAVEPOINT
Equivalent to the SQL statement:
68

Plsql
Procedure
STEP_ID Function
USE_ROLLBACK_SE
GMENT Procedure

SAVEPOINT <savepoint_name>
Returns local (to local transaction)
unique positive integer that orders
the DML operations of a transaction
Equivalent to the SQL statement:
SET TRANSACTION USE ROLLBAC
K SEGMENT<rb_seg_name>

10.DBMS_LOCK:
DBMS_MVIEW
Package
Subprograms
Subprogram
Description
BEGIN_TABLE_REORGAN Performs a process to
IZATION Procedure
preserve materialized view
data needed for refresh
END_TABLE_REORGANIZ Ensures that the materialized
ATION Procedure
view data for the master table
is valid and that the master
table is in the proper state
ESTIMATE_MVIEW_SIZE
Estimates the size of a
Procedure
materialized view that you
might create, in bytes and
rows
EXPLAIN_MVIEW
Explains what is possible with
Procedure
a materialized view or
potential materialized view

69

Plsql
EXPLAIN_REWRITE
Procedure

I_AM_A_REFRESH
Function
PMARKER Function

PURGE_DIRECT_LOAD_L
OG Procedure

PURGE_LOG Procedure
PURGE_MVIEW_FROM_L
OG Procedure
REFRESH Procedures

REFRESH_ALL_MVIEWS
Procedure
REFRESH_DEPENDENT
Procedures

REGISTER_MVIEW
Procedure

Explains why a query failed to


rewrite or why the optimizer
chose to rewrite a query with
a particular materialized view
or materialized views
Returns the value of
the I_AM_REFRESH package
state
Returns a partition marker
from a rowid, and is used for
Partition Change Tracking
(PCT)
Purges rows from the direct
loader log after they are no
longer needed by any
materialized views (used with
data warehousing)
Purges rows from the
materialized view log
Purges rows from the
materialized view log
Refreshes one or more
materialized views that are
not members of the same
refresh group
Refreshes all materialized
views that do not reflect
changes to their master table
or master materialized view
Refreshes all table-based
materialized views that
depend on a specified master
table or master materialized
view, or list of master tables
or master materialized views
Enables the administration of
individual materialized views

70

Plsql
UNREGISTER_MVIEW
Procedure

Enables the administration of


individual materialized views
once invoked at a master site
or master materialized view
site to unregister a
materialized view

71

Plsql

COLLECTIONS
1.What is collections? What are the types of collections?
A collection is an ordered group of elements having the same
data type. Each element is identified by a unique subscript that
represents its position in the collection.
PL/SQL provides three collection types:
72

Plsql
Index-by tables or Associative array
Nested table
Variable-size array or Varray

Varrays:
1. In varrays, elements are the same type and use a sequential
numeric index. This means the index of VARRAY variables is
dense, it means the collection has no gaps between elements.
Before declaring the variable, we know the number of items in
the collection.
2.VARRAY cannot increase in size after it is declared.
3.There are two prototypes for a VARRAY because you can define
it in SQL or PL/SQL also.
4.They are similar to PL/SQL table, and each element in a varray
is assigned a
subscript/index starting with 1.
5.These are dense and Not sparse, which means there is no way
to delete individual elements of a Varray.
The following is the SQL prototype to define a VARRAY of scalar variables:
CREATE OR REPLACE TYPE varray_name AS VARRAY(maximum_size)
OF sql_datatype [NOT NULL];
/
The following prototype defines a VARRAY of any datatype in a PL/SQL block:
TYPE varray_name IS VARRAY(maximum_size) OF [sql_datatype | plsql_datatype]
[NOT NULL];
DECLARE
TYPE number_varray IS VARRAY(10) OF NUMBER;
list NUMBER_VARRAY := number_varray(1,2,3,4,5,6,7,8,NULL,NULL);
BEGIN
FOR i IN 1..list.LIMIT LOOP
dbms_output.put('['||list(i)||']');
END LOOP;
dbms_output.new_line;
END;
/
The program prints the following to the console:
[1][2][3][4][5][6][7][8][][]

73

Plsql
Nested tables:
1.Nested tables are similar to index by table but these can be
stored in database columns but index by tables cannot be stored
in database columns.
2.A Nested table can be considered as a single column table that
can either be in
memory, or as a column in a database table.
3.A nested table is quite similar to a VARRAY with the exception
that the order of the elements is not static.
4.Elements can be deleted or added anywhere in the nested table
where as a VARRAY can only add or delete elements from the end
of the array.
5.Nested Table is known as a sparse collection because a nested
table can contain empty elements.
6.we need to delete or update some elements, but not all the
elements at once.
The index values are not consecutive.
7.We dont have any predefined upper bound for index values.
The following is the SQL prototype to define a nested table of scalar variables:
CREATE OR REPLACE TYPE table_name AS TABLE
OF sql_datatype [NOT NULL];
/
The following prototype defines a nested table of any defined datatype in a PL/SQL block:
TYPE table_name IS TABLE OF [sql_datatype | plsql_datatype]
[NOT NULL];
DECLARE
TYPE number_table IS TABLE OF NUMBER;
list NUMBER_TABLE := number_table(1,2,3,4,5,6,7,8);
BEGIN
list.DELETE(2);
FOR i IN 1..list.COUNT LOOP
IF list.EXISTS(i) THEN
dbms_output.put('['||list(i)||']');
END IF;
END LOOP;

74

Plsql
dbms_output.new_line;
END;
/
The program prints the following to the console: [1][3][4][5][6][7][8]

Associative arrays(index by tables):


1.An associtative array is also called as index by table) . It is a set
of key-value pairs. Each key is unique, and is used to locate the
corresponding value.
2.The key can be either an interger or a string. To use index by
table in pl/sql block.
An associative cannot be stored in the database.
3.A relatively small lookup table, where the collection can be
constructed in memory each time a subprogram is invoked or a
package is initialized.
Passing the collections from database server.
4.Pl/sql automatically converts between host array and
associative array that use numeric key values. The most efficient
way to pass collections to and from the database server is to set
up data values in associative arrays and then use those
associative arrays with bulk constructs (FORALL OR BULK
COLLECT).
When you choose the varrays:
1.The number of elements are known.
2.The elements are usually accessed by sequentially.
3.when stored in database, varrays keep their ordering and
subscripts.
4. A vary is stored as a single object. If varray is less than 4kb, it
is stored inside the table of which it is a column, otherwise it is
stored outside the table but in the same tablespace.
When you choose the nested tables:
1.Index values are not consecutive.
2.we must delete or update some elements, but not all elements
at once.
75

Plsql
3.Nested table data is stored in a separate store table, a system
generated database table. When we access a nested table , the
database joins the nested table with its store table. This makes
nested tables suitable for queries and updates that only affects
some elements of the collection.
When you choose the associative arrays:
1.A relatively small lookup table, where the collection can be
constructed in memory each time a subprogram is invoked or a
package is initialized.
Passing the collections from database server.
2.Pl/sql automatically converts between host array and
associative array that use numeric key values. The most efficient
way to pass collections to and from the database server is to set
up data values in associative arrays and then use those
associative arrays with bulk constructs (FORALL OR BULK
COLLECT).
What is the difference b/w Nested tables and varrays and
associative arrays?
Differences Between Nested Tables and Varrays
1.Nested tables are unbounded, where as varrays have a
maximum size.
2.Individual elements can be deleted from a nested table, but not
from a varray. Therefore, nested tables can be sparse, whereas
varrays are always dense.
3.Varrays are stored by Oracle in-line (in the same tablespace),
whereas nested table data is stored out-of-line in a store table,
which is a system-generated database table associated with the
nested table.
4.When stored in the database, nested tables do not retain their
ordering and subscripts, whereas varrays do.

76

Plsql
5.Nested tables support indexes while varrays do not support
indexes.

DIFFERENCES AMONG COLLECTIONS


1 Varrays has limit, nested tables and index-by tables has no limit.
2 Varrays and nested tables must be initialized before assignment
of elements, in index-by tables we can directly assign elements.
3 Varrays and nested tables stored in database, but index-by
tables can not.
4 Nested tables and index-by tables are PL/SQL tables, but
varrays can not.
5 Keys must be positive in case of nested tables and varrays, in
case of index-by tables keys can be positive or negative.
6
Referencing
nonexistent
elements
raises
SUBSCRIPT_BEYOND_COUNT in both nested tables and varrays,
but in case of index-by tables NO_DATA_FOUND raises.
7 Keys are sequential in both nested tables and varrays, nonsequential in index-by tables.
8 Individual indexes can be deleted in both nested tables and
index-by tables, but in varrays cannot.
9 Individual indexes can be trimmed in both nested tables and
varrays, but in index-by tables cannot.
10 Individual indexes can be extended in both nested tables and
varrays, but in index-by tables cannot.
Table 19.2: Comparing
Characteristi Index-By
c
Table
Usable in
No

Oracle Collection Types


Nested
Table
VARRAY
Yes
Yes
77

Plsql
SQL?
Usable as
column
datatype in a
table?
Uninitialized
state

Initialization

No

Empty
(cannot be
null);
elements
undefined
Automatic,
when
declared

Sparse?

Yes

Bounded?

No

Can assign
value to any
element at
any time?

Yes

Means of
extending

Assign
value to
element
with a new
subscript

Yes; data
stored "out of
line" (in
separate
table)
Atomically
null; illegal to
reference
elements

Yes; data
stored "in
line" (in same
table)

Via
constructor,
fetch,
assignment

Via
constructor,
fetch,
assignment

Initially, no;
after
deletions, yes
Can be
extended
No; may need
to EXTEND
first

No

Use built-in
EXTEND
procedure (or
TRIM to
condense),
with no
predefined
maximum

78

Atomically
null; illegal to
reference
elements

Yes
No; may need
to EXTEND
first, and
cannot
EXTEND past
upper bound
EXTEND (or
TRIM), but
only up to
declared
maximum
size

Plsql
Collection set operators:
They act and function like SQL set operators in select statements.
The difference is that they are used in assignments between
collections of matching signature types.
They only work with varrays and nested tables because they
require numeric index values.
1.CARDINALITY
The CARDINALITY operator counts the number of elements in a
collection. It makes no attempt to count only unique elements,
but we can combine it with the SET operator to count unique
elements.
The prototype is: CARDINALITY(collection)
Ex:
DECLARE
a LIST := list(1,2,3,3,4,4);
BEGIN
dbms_output.put_line(CARDINALITY(SET(a)));
END;
/
The program now prints the number 4 because there are four unique
elements in the set
derived from the six-element collection.

2. EMPTY
The EMPTY operator acts as an operand, as you would check
whether a variable is null or is not null.
The comparative syntax is: variable_name IS [NOT] EMPTY
3. MEMBER OF
The MEMBER OF operator lets we check if the left operand is a
member of the collection used as the right operand.
Thecomparative syntax is:
variable_name MEMBER OF collection_name
Ex:
DECLARE
TYPE list IS TABLE OF VARCHAR2(10);
n VARCHAR2(10) := 'One';
79

Plsql
a LIST := list('One','Two','Three');
BEGIN
IF n MEMBER OF a THEN
dbms_output.put_line('n is member.');
END IF;
END;
/
The MEMBER OF operator compares and returns a Boolean true type when it
finds the left
operand value in the right operand collection. The left operand datatype
must match the base
datatype of the scalar collection.

4. MULTISET EXCEPT :
The MULTISET EXCEPT operator removes one set from another. It
works like the SQL MINUS set operator.
The prototype is:
collection MULTISET EXCEPT collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET EXCEPT b));
END;
/
Only the element 4 exists in both sets. The operation therefore removes 4
from the first set.
The following output is generated by the block:
(1, 2, 3)

5. MULTISET INTERSECT
The MULTISET INTERSECT operator evaluates two sets and returns
one set. The return set contains elements that were found in both
original sets. It works like the SQL INTERSECT set
operator.
The prototype is: collection MULTISET INTERSECT collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET INTERSECT b));
END;
/

80

Plsql
Only one element from both sets matches, and thats the number 4. The
following output is
generated by the block:
(1, 2, 3)

6.MULTISET UNION:
The MULTISET UNION operator evaluates two sets and returns
one set. The return set contains all elements of both sets. Where
duplicate elements are found, they are returned. It functions like
the SQL UNION ALL set operator.
You may use the DISTINCT operator to eliminate duplicates.
The DISTINCT operator follows the MULTISET UNION operator rule.
It functions like the SQL UNION operator.
The prototype is: collection MULTISET UNION collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(a MULTISET UNION b));
END;
/
o/p: (1, 2, 3, 4, 4, 5, 6, 7)
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(SET(a MULTISET UNION b)));
END;
/
Both the DISTINCT and SET operators produce the following output:
(1, 2, 3, 4, 5, 6, 7)

7. SET
The SET operator removes duplicates from a collection, and
thereby creates a set of unique values. It acts like a DISTINCT
operator sorting out duplicates in a SQL statement.
The operator prototype is:
SET(collection)
we can also use the SET operator as an operand, as you would
check whether a variable is null or is not null.
The comparative
81

Plsql
syntax is:

variable_name IS [NOT] A SET

DECLARE
a LIST := list(1,2,3,3,4,4,5,6,6,7);
BEGIN
dbms_output.put_line(format_list(SET(a)));
END;
/
The original set contains ten elements, but three are duplicated. The SET
operator removes all
duplicates and generates a new set with seven unique elements.
(1, 2, 3, 4, 5, 6, 7)
You can also use SET as an operand in comparison statements:
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(1,2,3,3,4,4);
c LIST := list();
FUNCTION isset (set_in LIST) RETURN VARCHAR2 IS
BEGIN
IF set_in IS A SET THEN
IF set_in IS NOT EMPTY THEN
RETURN 'Yes - a unique collection.';
ELSE
RETURN 'Yes - an empty collection.';
END IF;
ELSE
RETURN 'No - a non-unique collection.';
END IF;
END isset;
BEGIN
dbms_output.put_line(isset(a));
dbms_output.put_line(isset(b));
dbms_output.put_line(isset(c));
END;

8.SUBMULTISET
The SUBMULTISET operator identifies if a set is a subset of
another set. It returns true when the left operand is a subset of
the right operand. The true can be misleading if youre looking for
a proper subset, which contains at least one element less than
the superset.
82

Plsql
The function returns true because any set is a subset of itself.
There is no test for a proper subset without also using the
CARDINALITY operator to compare whether the element counts of
both sets are unequal.
The prototype is: collection SUBMULTISET OF collection
DECLARE
a LIST := list(1,2,3,4);
b LIST := list(1,2,3,3,4,5);
c LIST := list(1,2,3,3,4,4);
BEGIN
IF a SUBMULTISET c THEN
dbms_output.put_line('[a] is a subset of [c]');
END IF;
IF NOT b SUBMULTISET c THEN
dbms_output.put_line('[b] is not a subset of [c]');
END IF;
END;
/
It prints
[a] is a subset of [c]
[b] is not a subset of [c]

Collection methods
1.COUNT
The COUNT method returns the number of elements with
allocated space in VARRAYand NESTED TABLE datatypes.
The COUNT method returns all elements in associativearrays. The
return value of the COUNT method can be smaller than the return
value of LIMIT for the VARRAY datatypes.
It has the following prototype: pls_integer COUNT
2.DELETE
The DELETE method lets you delete members from the collection.
It has two formal parameters; one is mandatory and the other is
optional. Both parameters accept PLS_INTEGER, VARCHAR2, and
LONG variable types.
Only one actual parameter, n, is interpreted as the index value to
delete from the collection. When you supply two actual
parameters, the function deletes everything from the parameter n
to m, inclusively.
83

Plsql
It has the following prototypes:
void DELETE(n)
void DELETE(n,m)
3.EXISTS
The EXISTS method checks to find an element with the supplied
index in a
collection. It returns true when the element is found and false
otherwise. The
element may contain a value or a null value. It has one
mandatory parameter, and the parameter can be a PLS_INTEGER,
VARCHAR2, or LONG type. It has the following
prototype:
boolean EXISTS(n)
4.EXTEND
The EXTEND method allocates space for one or more new
elements in a VARRAY
or NESTED TABLE collection. It has two optional parameters. It
adds space for
one element by default without any actual parameter. A single
optional parameter designates how many physical spaces should
be allocated, but it is constrained by
the LIMIT value for VARRAY datatypes. When two optional
parameters are provided, the first designates how many elements
should be allocated space and the second designates the index it
should use to copy the value to the newly allocated space. It
has the following prototypes:
void EXTEND
void EXTEND(n)
void EXTEND(n,i)
5.FIRST
The FIRST method returns the lowest subscript value in a
collection. It can return a PLS_INTEGER, VARCHAR2, or LONG
type.
It has the following prototype: mixed FIRST
6.LAST
84

Plsql
The LAST method returns the highest subscript value in a
collection. It can return a PLS_INTEGER, VARCHAR2, or LONG type.
It has the following prototype: mixed LAST
7.LIMIT
The LIMIT method returns the highest possible subscript value in
a collection. It can only return a PLS_INTEGER type and can only
be used by a VARRAY datatype. It has the following prototype:
mixed LIMIT
8.NEXT(n)
The NEXT method returns the next higher subscript value in a
collection when
successful or a false. The return value is a PLS_INTEGER,
VARCHAR2, or LONG type.
It requires a valid index value as an actual parameter.
It has the following prototype: mixed NEXT(n)
9.PRIOR(n)
The PRIOR method returns the next lower subscript value in a
collection when
successful or a false. The return value is a PLS_INTEGER,
VARCHAR2, or LONG type.
It requires a valid index value as an actual parameter.
It has the following prototype: mixed PRIOR(n)
10.TRIM
The TRIM method removes a subscripted value from a collection.
It has one optional parameter. Without an actual parameter, it
removes the highest element form the array.
An actual parameter is interpreted as the number of elements
removed from the end of the collection.
It has the following prototypes:
void TRIM
void TRIM(n)
Collection Exceptions:

85

Plsql
1.COLLECTION_IS_NULL: An attempt to use a null collection.
2.NO_DATA_FOUND: An attempt to use a subscript that has
been deleted or is a
nonexistent unique string index value in an associative array.
3.SUBSCRIPT_BEYOND_COUNT:
An attempt to use a numeric index value that is higher than the
current maximum number value. This error applies only to varrays
and nested tables. Associative arrays are not bound by the
COUNT return value when adding new elements.
4.SUBSCRIPT_OUTSIDE_LIMIT:
An attempt to use a numeric index value outside of the LIMIT
return value. This error only applies to varrays and nested tables.
The LIMIT value is defined one of two ways. Varrays set the
maximum size, which becomes their limit value. Nested tables
and associative arrays have no fixed maximum size, so the limit
value is set by the space allocated by the EXTEND method.
5.VALUE_ERROR:
An attempt is made to use a type that cannot be converted to a
PLS_INTEGER, which is the datatype for numeric subscripts.
Functions can be used in collections?
EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, and NEXT are
functions that check the properties of a collection or individual
collection elements. EXTEND, TRIM, and DELETE are procedures
that modify a collection.

What is Bulk Binds?


The assigning of values to PL/SQL variables in SQL statements is
called binding.
. The binding of an entire collection at once is called bulk binding
86

Plsql
. Bulk binds improve performance by minimizing the number of
context switches between the PL/SQL and SQL engines. With bulk
binds, entire collections, not just individual elements, are passed
back and forth.
The keyword FORALL instructs the PL/SQL engine to bulk-bind
input collections before sending them to the SQL engine. Although
the FORALL statement contains an iteration scheme.
In a FORALL statement, if any execution of the SQL statement
raises an unhandled exception, all database changes made during
previous executions are rolled back. However, if a raised
exception is caught and handled, changes are rolled back to an
implicit save point marked before each execution of the SQL
statement. Changes made during previous executions are not
rolled back. The following restrictions apply to the FORALL
statement:
You can use the FORALL statement only in server-side programs
(not in client-side programs).Otherwise, you get the error this
feature is not supported in client-side programs.
The INSERT, UPDATE, or DELETE statement must reference at
least one collection.
What is Bulk Collect?
The keywords BULK COLLECT tell the SQL engine to bulk-bind
output collections before returning them to the PL/SQL engine.
We can use these keywords in the SELECT INTO, FETCH INTO, and
RETURNING INTO clauses. The FORALL statement is specifically
used for processing DML (INSERT, DELETE, and UPDATE)
statements to improve performance by reducing the overhead of
SQL processing.

87

Plsql
The PL/SQL interpreter executes all procedural statements.
However, all SQL statements in the PL/SQL block are sent to the
SQL engine, which parses and executes them.
The PL/SQL-to-SQL context switch adds some overhead, which
could become significant when SQL statements are nested in
loops.
Context-Switching:
Context-switching is an almost-irreducible cost of computing that
occurs in CPUs, operating systems, and software.
we specifically refer to the exchange of processing control
between the SQL and PL/SQL engines. These two engines are
separate and distinct but we use them interchangeably. This
means that when we call SQL from PL/SQL or vice versa, the
calling context needs to store its process state and hand over
control and data to its counterpart engine (which may or may not
be picking up from an earlier switch). This switching cycle is
computationally intensive and can
typically be repeated so many times that its effects on response
times can become quite noticeable.
BULK BIND USING FORALL LOOP:
The FORALL systax allows us to bind the contents of collection to
a single DML statement, allowing the DML to be run for each row
in the collection without requiring a context switch each time.
FORALL loop improves performance of BULK INSERT, BULK
UPDATE, BULK DELETE.
FORALL loop allows only statement and that must be DML
statement.
Systax:
FORALL <VAR> IN <LOWER BOUND>..<UPPER BOUND>
DML STATEMENT
SQL%BULK ROW COUNT:
88

Plsql
The SQL%BULK ROW COUNT cursor attributes gives information
about the rows affected by each iteration of the FORALL
statement.
SAVE EXCEPTIONS AND SQL%BULK EXCEPTIONS:
1.FORALL loop improves the performance of BULK INSERT, BULK
UPDATE, BULK DELETE. If there no exception handler, all the work
done by the current bulk operation is rolled back.
2.If there is an exception handler, the work done prior to the
exception is kept, but no more processing is done.
3.Neither of these situations is very sastifactory, so instead we
should use the SAVE EXCEPTION clause to capture the exception
and allow us to continue past them. We can use the SQL
%BULKEXCEPTION in exception part.

CURSOR FOR LOOP

VS

BULK COLLECT

Lets take a closer look at these five cursor FOR loop


recommendations.
1.Never use a cursor FOR loop when writing new code. Using the
cursor FOR loop construct is a declarative way of asking Oracle
Database to fetch each of the rows specified by our cursor and
then execute the loop body for that row. You dont have to
explicitly open the cursor, code the fetch, check to see if the
cursor is closed.
2.The problem with using a cursor FOR loop is that either it isnt
the appropriate construct for querying data (as is the case for a
single-row fetch) or it isnt the most efficient approach (BULK
COLLECT offers a faster way of querying data).
Having said that, I can identify two circumstances in which using a
cursor FOR loop would do little harm.
89

Plsql
3.First, if you expect to retrieve a relatively small number of rows
(in the hundreds at most), a cursor FOR loops performance in
Oracle Database 10g and above will likely meet your
requirements. Oracle Database automatically optimizes cursor
FOR loops to execute similarly to BULK COLLECT, so you get most
of the advantages of that approach.
4.Next, if youre writing a program that is run only occasionally
and is not in the critical path of operations, you may want to
choose the simplicity and readability of the cursor FOR loop over
the incremental improvement in performance (and additional
complexity of code) that BULK COLLECT offers.
Use an implicit SELECT INTO for single-row fetches. Developers
often tell me that they write a cursor FOR loop to fetch a single
row. Why not? Oracle Database does so much of the work for you,
saving several lines of code and several minutes of typing.
But theres a problem with using a cursor FOR loop for a singlerow fetch: the resulting code is very misleading. It looks like you
expect to retrieve multiple rows, yet you get just one.
If you need to retrieve a single row and you know that at most
one row should be retrieved, you should use a SELECT INTO
statement.
Bulk collect:
Using bulk collect into a collection will be faster, but talking about
that amount of records, it could be also dangerous because of the
per-session memory it would consume.
In this case you could use the LIMIT clause, to fetch only a smaller
group of records, process them, and then fetch another group.
Disadvantages of bulk collect:

90

Plsql
Using the BULK COLLECT clause in PL/SQL implies following
restrictions:
1.We cannot bulk collect into an associative array having a string
type for the key.
2.BULK COLLECT clause can be used only in server-side programs
(not in client-side programs) else, error is reported that it is not
supported in client-side programs.
3.Collections should be used as target variables listed in a BULK
COLLECT INTO clause.
4.Composite targets (such as objects) cannot be used in the
RETURNING INTO clause else error is reported for feature with
RETURNING clause.
5.Multiple composite targets cannot be used in the BULK COLLECT
INTO clause When implicit data type conversions are needed.
6.When an implicit datatype conversion is needed, a collection of
a composite target (such as a collection of objects) cannot be
used in the BULK COLLECT INTO clause.
Thus above mentioned points should be kept in mind while using
BULK COLLECT.
What is collections? What is the use of LIMIT clause in bulk
collect?
Using LIMIT with BULK COLLECT
Oracle provides a LIMIT clause for BULK COLLECT that allows you
to limit the number of rows fetched from the database. The
syntax is:
FETCH cursor BULK COLLECT INTO ... [LIMIT rows];

91

Plsql
where rows can be any literal, variable, or expression that
evaluates to an integer (otherwise, the database will raise a
VALUE_ERROR exception).
LIMIT is very useful with BULK COLLECT, because it helps you
manage how much memory your program will used to process
data. Suppose, for example, that you need to query and process
10,000 rows of data. You could use BULK COLLECT to retrieve all
those rows and populate a rather large collection. However, this
approach will consume lots of memory in the PGA for that session.
If this code is run by many separate Oracle schemas, your
application performance may degrade because of PGA swapping.
FORALL loop_counter IN bounds_clause
SQL_STATEMENT [SAVE EXCEPTIONS];
where bounds_clause is one of the following:
lower_limit..upper_limit
INDICES OF collection_name BETWEEN lower_limit..upper_limit
VALUES OF collection_name
THE INDICES OF OPTION
As stated previously, the INDICES OF option enables you to loop
through a sparse collection.
Recall that such a collection may be a nested table or an
associative array.
THE VALUES OF OPTION
VALUES OF..., references values of the individual elements
of a particular collection, which is either a nested table or an
associative array.
The elements of the collection used in the VALUES OF clause must
be PLS_INTEGER or BINARY_INTEGER.
Why there is such a huge performace difference between
Collection loop and a cursor Loop? Why collection
populated using Bulk collect is way faster?

92

Plsql
PL/SQL sends SQL statements such as DML and queries to the
SQL engine for execution, and SQL returns the results to PL/SQL.
You can minimize the performance overhead of this
communication between PL/SQL and SQL by using the PL/SQL
features that are known collectively as bulk SQL.
The FORALL statement sends INSERT, UPDATE, or DELETE
statements in batches, rather than one at a time. The BULK
COLLECT clause brings back batches of results from SQL. If the
DML statement affects four or more database rows, bulk SQL can
improve performance considerably.
Bulk SQL uses PL/SQL collections to pass large amounts of data
back and forth in single operations. This process is called bulk
binding. If the collection has n elements, bulk binding uses a
single operation to perform the equivalent of n SELECT INTO,
INSERT, UPDATE, or DELETE statements. A query that uses bulk
binding can return any number of rows, without requiring a FETCH
statement for each one.
What is BULK LOADER?
BulkLoader scans a directory structure containing content and
loads it into a specified content repository. In addition to loading
content, BulkLoader reads prepared metadata files and associates
the metadata with each loaded content item. Metadata files can
be prepared for each specific content item, or more broadly for
directories and subdirectories of items.
If you use BulkLoader to load content into a database repository,
then both the metadata and binary files are transferred to the
repository. If you load into a filesystem repository, then only the
metadata is transferred to the database--the actual content files
remain in place on the filesystem.
You cannot use the Bulkloader to update existing content (or its
metadata) within a filesystem repository. It can only be used to
add new content to the repository.

93

Plsql

DYNAMIC SQL
Native Dynamic SQL (EXECUTE IMMEDIATE)

What is the difference b/w Native Dynamic sql and


DBMS_SQL?
Native Dynamic SQL
(EXECUTE IMMEDIATE)
Supports user defined
types.

DBMS_SQL

Supports FETCH INTO


record types
Not supported in client
site code.

Does not support


FETCH INTO record
types
Supported in client
side code.

Does not support


DESCRIBE_COLUMNS

Supports
DESCRIBE_COLUMNS

Does not support bulk


Dynamic SQL, but it can
be faked by placing all
statements in a PL/SQL
block.

Supports bulk
Dynamic SQL.

Does not support user


defined types.

94

Plsql
Only supports Single row
Updates/Deletes with
RETURNING clause.

Supports Single and


Multiple row
Updates/Deletes with
RETURNING clause.

95

Plsql

96

You might also like