You are on page 1of 218

1Z0-147

Oracle9i: Program with PL/SQL

Oracle 1z0-147 Study Guide

Oracle 1Z0-147 Study Guide


2005 Self Test Software, a Kaplan IT Company. All rights reserved. No part of this
study guide may be used or reproduced in any manner whatsoever without written
permission of the copyright holder. The information contained herein is for the personal
use of the reader and may not be incorporated in any commercial programs, other books,
databases, or any kind of software without written consent of the publisher. Making
copies of this study guide or any portion for any purpose other than your own is a
violation of United States Copyright laws.
Information has been obtained by Self Test Software from sources believed to be
reliable. However, because of the possibility of human error by our sources, Self Test
Software, or others, Self Test Software does not guarantee the accuracy, adequacy, or
completeness of any information in this study guide and is not responsible for any errors
or omissions or the results obtained from use of such information.
Oracle is a registered trademark of Oracle Corporation in the United States and/or other
countries.

Self Test Software


A Kaplan IT Company
500 Northridge Road
Suite 240
Atlanta, Georgia 30350
800-244-7330
www.selftestsoftware.com

2
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Contents
Contents......................................................................................................................... 3
Pass the Exam with the Self Test Study Guide ............................................................................................ 6

Overview of PL/SQL Constructs: Program with PL/SQL ........................................... 7


Brief Outline of PL/SQL Programs ................................................................................................................ 8
Describe the Configuration of PL/SQL Blocks .............................................................................................. 9
Benefits of Subprograms............................................................................................................................. 11
Invoking Stored Procedures and Functions ................................................................................................ 12
Review Checklist: Overview of PL/SQL Constructs: Program with PL/SQL............................................... 13

Creating Procedures: Program with PL/SQL ............................................................ 14


Define a Stored Procedure.......................................................................................................................... 15
Development Steps for Creating a Procedure ............................................................................................ 16
Create a Procedure..................................................................................................................................... 18
Difference Between Formal and Actual Parameters................................................................................... 20
Procedure Parameter Modes ...................................................................................................................... 21
List the Methods for Calling a Procedure with Parameters......................................................................... 25
DEFAULT Options for Parameters............................................................................................................... 27
Create a Procedure with Parameters.......................................................................................................... 29
Invoke a Procedure with Parameters.......................................................................................................... 33
Declare a Subprogram in the Declarative Section of a Procedure ............................................................. 35
Exception Handling in PL/SQL Subprograms ............................................................................................. 36
Remove a Stored Procedure....................................................................................................................... 41
Review Checklist: Creating Procedures: Program with PL/SQL................................................................. 42

Creating Functions: Program with PL/SQL............................................................... 43


Explain Stored Functions ............................................................................................................................ 44
Create Functions......................................................................................................................................... 45
Invoking Functions ...................................................................................................................................... 48
Advantages of Using User-Defined Functions in SQL Statements............................................................. 51
Invoking User-Defined Functions from SQL Statements ............................................................................ 53
Describe the Restrictions on Calling Functions from SQL Statements ...................................................... 55
Remove a Stored Function ......................................................................................................................... 59
Describe Differences Between Procedures and Functions ........................................................................ 60
Review Checklist: Creating Functions: Program with PL/SQL ................................................................... 62

Managing Subprograms: Program with PL/SQL ...................................................... 63


Contrast between System and Object Privileges........................................................................................ 64
Grant Privileges........................................................................................................................................... 66
Invokers versus Definers Right ................................................................................................................. 67
Identify Views in the Data Dictionary to Manage Stored Objects ............................................................... 71
Review Checklist: Managing Subprogram: Program with PL/SQL ............................................................. 72

Packages: Program with PL/SQL............................................................................... 73


Usage of the DESCRIBE Command............................................................................................................ 74
Identify Package Specification and Package Body..................................................................................... 75
Developing a Package ................................................................................................................................ 79
Identify Public and Private Constructs ........................................................................................................ 82
Invoking Package Constructs...................................................................................................................... 84
Declaring a Bodiless Package .................................................................................................................... 89

3
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Drop Package ............................................................................................................................................. 91


Benefits of Using Packages ........................................................................................................................ 92
Review Checklist: Packages: Program with PL/SQL.................................................................................. 93

More Package Concepts: Program with PL/SQL ...................................................... 94


Package Overloading.................................................................................................................................. 95
Forward Referencing................................................................................................................................... 98
Mutually Referencing Subprograms.......................................................................................................... 102
Creating a One-Time-Only Procedure ...................................................................................................... 105
Persistent State of Packaged Variables and Cursors............................................................................... 106
Identify Restrictions on Using Packaged Functions in SQL Statements .................................................. 110
Invoke Packaged Functions with SQL ...................................................................................................... 113
Use PL/SQL Tables and Records in Packages ........................................................................................ 117
Review Checklist: More Package Concepts: Program with PL/SQL ........................................................ 119

Oracle-Supplied Packages: Program with PL/SQL ................................................ 120


Benefits of Using the EXECUTE IMMEDIATE Statement over the DBMS_SQL Package .......................... 121
Identify the Flow of Execution ................................................................................................................... 122
Use the EXECUTE IMMEDIATE Statement .............................................................................................. 123
Using Oracle Server-Supplied Packages.................................................................................................. 128
Review Checklist: Oracle-Supplied Packages: Program with PL/SQL..................................................... 138

Manipulating Large Objects: Program with PL/SQL .............................................. 139


Compare and Contrast LONG and LOB Data Types .................................................................................. 140
Create and Maintain LOB Data Types....................................................................................................... 141
Differentiate Between Internal and External LOBs .................................................................................... 143
Identify and Manage BFILEs .................................................................................................................... 144
Migrating from LONG to LOB ...................................................................................................................... 147
Create LOB Columns and Populate Them ................................................................................................ 149
Perform SQL Operations on LOBs ............................................................................................................ 151
Describe the use of Temporary LOBs ....................................................................................................... 153
Review Checklist: Manipulating Large Objects: Program with PL/SQL.................................................... 154

Creating Database Triggers: Program with PL/SQL............................................... 155


Describe the Different Types of Triggers .................................................................................................. 156
Describe the Use of Triggers .................................................................................................................... 157
Guidelines for Creating Triggers ............................................................................................................... 160
Creating DML Triggers.............................................................................................................................. 161
List the DML Trigger Components ............................................................................................................ 163
Describe the Trigger Firing Sequence Options......................................................................................... 165
Conditional Predicates .............................................................................................................................. 167
Creating a Row Level Trigger ................................................................................................................... 168
Creating a Statement Level Trigger .......................................................................................................... 171
Using :OLD and :NEW Qualifiers .............................................................................................................. 173
Create an INSTEAD OF Trigger ...............................................................................................................175
Difference Between Database Triggers and Stored Procedures.............................................................. 178
Describe the Trigger Execution Model...................................................................................................... 179
Managing Triggers .................................................................................................................................... 181
Dropping Triggers ..................................................................................................................................... 182
Review Checklist: Creating Database Triggers: Program with PL/SQL ................................................... 183

More Trigger Concepts: Program with PL/SQL ...................................................... 184


Define a Database Trigger ........................................................................................................................ 185
List How Database Triggers are Used ...................................................................................................... 186
List Guidelines for Designing Triggers ...................................................................................................... 187

4
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create a DML Trigger ............................................................................................................................... 189


List the DML Trigger Components ............................................................................................................ 191
Mutating Tables......................................................................................................................................... 192
Implementing Triggers .............................................................................................................................. 194
Managing Triggers .................................................................................................................................... 195
Viewing Trigger Information ...................................................................................................................... 196
Review Checklist: More Trigger Concepts: Program with PL/SQL........................................................... 197

Managing Dependencies: Program with PL/SQL ................................................... 198


Track Procedural Dependencies............................................................................................................... 199
Describe Dependent and Referenced Objects ......................................................................................... 201
Define Local Dependencies ...................................................................................................................... 202
View Dependency Information from the Data Dictionary Views ............................................................... 203
Describe How the UTLDTREE Script is Used ............................................................................................ 205
Describe How the DEPTREE and IDEPTREE Views are Used.................................................................. 206
Understanding Remote Dependencies ..................................................................................................... 208
Describe How Remote Dependencies are Governed............................................................................... 209
Describe When a Remote Dependency is Unsuccessfully Recompiled................................................... 211
Describe When a Remote Dependency is Successfully Compiled .......................................................... 212
List How to Minimize Dependency Failures .............................................................................................. 213
Review Checklist: Managing Dependencies: Program with PL/SQL........................................................ 214

Test Taking Strategies ........................................................................................ 215


Thank You and Good Luck on your Exams! ............................................................................................. 218

5
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Pass the Exam with the Self Test Study Guide


As a certification candidate, youre on the lookout for as many test preparation resources as possible, but your time is
at a premium. So, we put together the Study Guide with your study goals and busy schedule in mind.
Create a study plan and stick to it. Dont try to cram. Set aside specific study times so you can thoroughly
prepare for your exam. In our experience, following a disciplined prep schedule leads to success on Exam Day. To
thoroughly gain the benefits of our Study Guide, we recommend that you start preparing about six weeks prior to
taking your exam.
Use all the prep tools in your Study Guide. Your Guide contains a full suite of products to help you thoroughly
prepare for your exam. Each one is designed with a specific study purpose in mind. Heres how we recommend you
use the products together:
1.

Perform a baseline checkup. Set your personal baseline by taking the Self Test Practice Test in
Certification Mode. It is a timed test that simulates the real exam. Objective-based scoring shows you the
areas you are relatively strong in, and those you need to devote additional time to.

2.

Concentrate your studies by objective. Since your study time has to be in chunks, use the exams
structure by objective to help you organize your study sessions. Use each product to study at the objective
level with particular emphasis on the objectives where you did not score 100% in your baseline checkup.

3.

Study Guide. Read the Study Guide by objective to familiarize yourself with the exam content. The
Study Guide is objective-driven and contains a Scope and Focused Explanation for each objective. At
the end of each major objective is a Review Checklist that lists the key points covered in this area of the
exam.
Self Test Flash Cards. Drill through the Flash Cards by objective to be sure you know the fundamental
concepts. Make Personal Study Notes with these cards to supplement your learning.
Self Test Practice Test. Use the Practice Test in Learning Mode by objective. Answer the questions,
read the tutorials, and use the Personal Study Notes to supplement your learning and/or highlight items
that youll want to review before the exam.
References. Use your favorite references (books, web references, etc.) to get additional materials on
more complex subject matter.

Track your progress. Youve completed your objective-driven study plan. Now youre ready to see how
youve progressed. Take the Self Test Practice Test in Certification Mode again. Did you score 100%? If not,
go back to your objective study plan and focus on your weaknesses. Keep checking yourself, highlighting
objectives that youll need to study, until you consistently score 100%.

Do your final preparation. Print the Review Checklists from the Study Guide and the Personal Study Notes from the
Self Test Practice Test and Flash Cards. Use these as your condensed final review before taking the real exam. And,
before taking the real exam, read the Test-Taking Strategies at the end of this guide to get specific techniques on
approaching the different question types you may encounter.
Finally, some last words of advice. During your studies and practice test drills, concentrate on the process - not totally
on performance. What matters most is that you are using a disciplined approach that covers the materials on the
exam and you know what to expect on exam day. Stay the course of your study plan and you will be ready to PASS
THE EXAM!

6
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Overview of PL/SQL Constructs:


Program with PL/SQL

7
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Brief Outline of PL/SQL Programs


Scope
Describe a PL/SQL program construct.

Focused Explanation
PL/SQL programs are made up of blocks. These blocks can appear successively or can appear one
within another. Oracle provides many tools to construct these blocks. These blocks can be constructed
either at the database server or using the Oracle development tools, such as Oracle Forms Developer
and Oracle Reports Developer.
Oracle 9i also provides iSQL*Plus, which is a Web-based tool and can be used to build and manage
PL/SQL programs.
The following are the categories of the constructs created at the database server:

Anonymous blocks PL/SQL blocks without a name

Stored Procedures and Functions Named PL/SQL blocks also known as subprograms

Stored Packages PL/SQL constructs that are used to group related objects

Database Triggers PL/SQL blocks associated with a table, a view, a schema, or the database

Object Types User-Defined composite data types

You can create constructs using Oracle development tools, such as Oracle Forms Developer, Oracle
Reports Developer, or client-side application tools. These client constructs can be classified as:

Anonymous blocks

Application Procedures and Functions

Application Packages

Application triggers

Object Types

Client-side constructs are similar to the server-side constructs. The only difference is that these
constructs are created using the Oracle client-side tools.

8
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Configuration of PL/SQL Blocks


Scope
Describe the types of PL/SQL blocks and their configuration.

Focused Explanation
Oracle supports two types of PL/SQL blocks: named and anonymous. Named blocks have a name or a
header to identify them at the time of creation. Named blocks can be stored in the database. These
include procedures, functions, and packages. Named blocks are also known as subprograms. Named
blocks can also be created dynamically, allocated a name, and executed; but not stored in the database.
These types of named blocks are known as labeled blocks.
Anonymous blocks are similar to labeled blocks except that they do not have a name. Anonymous blocks
are not stored in the database and can be built and executed when required.
A PL/SQL block is divided into the following three sections:

A declarative section in which the variables, types, and other PL/SQL objects are defined. The
declarative section is an optional section.

An executable section, which contains SQL and PL/SQL statements that are executed to perform the
specified task. This is a mandatory section and must contain at least one executable statement. You
can include a NULL keyword to fulfill the need to have at least one executable statement in this
section.
For example,
BEGIN
NULL;
END

An exception-handling section, which traps the errors or exceptions generated in the executable
section. The exception-handling section is an optional section.

The following is the syntax for anonymous PL/SQL block:


DECLARE -- denotes the beginning of declarative section (optional)
. . .
BEGIN -- denotes the beginning of executable section (mandatory)
. . .
EXCEPTION - denotes the beginning of exception-handling section (optional)
. . .

9
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

END; -- labels the end of PL/SQL block. The semicolon is part of the syntax.
The following is the syntax for named blocks:
CREATE OR REPLACE <block type> <block name>
IS | AS -- Mandatory
. . .

-- Declarative section

BEGIN
. . .

-- Executable section

EXCEPTION
. . . - Exception-handling section (optional)
END;

-- Marks the end of the block

In the above syntax, the <block type> parameter can be substituted with one of the following
keywords:

PROCEDURE

FUNCTION

PACKAGE

TRIGGER

In addition, the DECLARE keyword is not used in named blocks. The declarative section is between the
IS|AS and BEGIN keywords. The keywords, IS and AS, are mutually exclusive and either one can be
used in the above syntax.
Note: Only the executable section is required to include the executable code, and it must contain at least
one executable statement. The header portion is the section above the IS | AS keyword. The header
section determines the properties of the named block. These properties include:

The name for the program, which is substituted in place of the <BLOCK NAME> parameter

The type of the program, whether it is a procedure or function

The parameters defined for the program

The RETURN clause if the program is a function

Note: The CREATE OR REPLACE keywords are used to create the named block.

10
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Benefits of Subprograms
Scope
List the benefits that subprograms provide.

Focused Explanation
Subprograms are named PL/SQL blocks created as either procedures or functions.
Subprograms provide the following benefits:

Performance Enhancement
Subprograms send a set of statements to the server in a group instead of sending individual
statements. This reduces network traffic and increases the performance of the database.
Subprograms are compiled when they are created. This increases performance by avoiding reparsing when these subprograms are executed.
When a call is made to the subprogram, the compiled code is placed into the shared pool making the
code available for all the users accessing the database.

Data Security and Integrity


Subprograms ensure that all the activity on related tables is either performed in its entirety or not
performed at all.
Subprograms inherit the privileges of the owner by default. This controls indirect access to the
database objects.

Easy to Maintain
Subprograms can be utilized by a number of applications in the database after they have been
compiled without any errors.
If there is change to the underlying objects, only the subprogram needs to be modified.
Changes can be made to a subprogram without halting the normal database operations.

Increased code clarity


Subprograms ensure better readability of the code, because each section of the subprogram block is
defined separately. For example, an exception-handling section is the section of the named block that
is used to handle system-defined errors or user-defined errors.
Variable declaration can be done using easy to read identifiers, which also aids in providing better
clarity.

11
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoking Stored Procedures and Functions


Scope
Know how subprograms are invoked from different calling environments.

Focused Explanation
A procedure or function can be invoked from multiple environments, such as Oracle Forms Developer,
Oracle Reports Developer, Oracle Portal, Oracle Discoverer, SQL*Plus, another stored procedure,
anonymous blocks, and other third-party tools.
To invoke a procedure from within SQL*Plus, you need to use the EXECUTE or the EXEC statement. The
syntax is as follows:
SQL> EXECUTE <procedure name>;
The <procedure name> parameter is substituted by the name of the procedure to be executed.
The syntax to invoke a procedure from Oracle development tools is as follows:
<procedure name>;
The following example describes how to call a procedure from an anonymous block:
BEGIN
<procedure name>;
END;
The procedure can also be invoked from within another procedure:
CREATE OR REPLACE PROCEDURE proc1
AS
BEGIN
. . .
procedure2; -- This is the name of the called procedure.
END proc1;
In the above example, proc1 is the calling procedure.
Note: When a procedure is called irrespective of the calling environment, the statement used to call the
procedure is a PL/SQL statement. For example, in the above block the call to procedure2 is considered
as a PL/SQL statement.

12
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Overview of PL/SQL Constructs: Program with


PL/SQL
Describe a PL/SQL program construct.
Describe the types of PL/SQL blocks and their configuration.
List the benefits that subprograms provide.
Know how subprograms are invoked from different calling environments.

13
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating Procedures: Program with


PL/SQL

14
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Define a Stored Procedure


Scope
Identify characteristics of stored procedures.

Focused Explanation
A procedure is a named PL/SQL program that is stored in the database as a schema object. A stored
procedure consists of a header, an optional declarative section, an executable section, and an optional
exception-handling section. A procedure can also optionally accept values or parameters from the calling
environment. The calling environment is the interface from where the procedure is executed or invoked.
Generally, procedures are built to perform some work on the database. This work can include regular
entry into database tables, such as whenever a company purchases new machinery, or it can be deletion
of records from the tables, such as whenever machinery is obsolete. The work that a procedure performs
depends upon the statements that are written in the executable section of its block. However, at least one
statement is mandatory in the executable section of the procedure. The executable section can also
include a NULL; statement that fulfills the need to have at least one executable statement.
Procedures inherit the privileges of the owner by default. Consider a scenario where a user Steve owns a
procedure B. This procedure inserts records in a table called temp_table. Now Steve grants the right to
execute this procedure to another user Shane. When Shane executes this procedure and a table known
as temp_table exists in Shanes schema, the data is inserted into the table owned by Steve. If the
procedure had been owned by Shane and executed by Steve, the data would have been inserted into the
table located in Shanes schema.
You can also use procedures to grant indirect access to the objects. Consider a scenario, where a user
Scott is the owner of the table my_table. Scott wants to grant INSERT privileges on the table to other
users in the database. To do this, Scott can either grant direct access to the table by granting the INSERT
privilege on the table to other users of the database or Scott can create a procedure, which inserts the
records in the table and grant EXECUTE privileges on this procedure to other users of the database. Users
granted execute privilege on the procedure will now be able to insert records in the table even if they do
not have direct insert privilege on the table.
When a procedure is created, it is compiled and the compiled form, referred to as p-code or pseudocode,
is stored in the database.
The source code of the procedure is also stored in the database. When the procedure is called, the pcode is read from the disk and stored by the PL/SQL engine in the shared pool area of the SGA. This
stored procedure can then be executed any number of times and can be shared by all applications
accessing the database. This ensures that all the users can share the code simultaneously.
Note: Procedures are stored in the database irrespective of whether or not the compilation was
successful. Procedures whose compilation was not successful because of errors in the code show an
INVALID status in the USER_OBJECTS view. Such procedures will fail to execute. Procedures whose
compilation was successful show a VALID status in the USER_OBJECTS view and can be successfully
executed. The PL/SQL engine is responsible for generating the p-code based on the compiled code and
later executing it when the procedure is invoked. In addition, if there are any modifications in the objects
which the procedure references, the procedure will have an INVALID status and will fail to execute. This
is also a benefit of procedures because in this case only the procedure will need to be updated.

15
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Development Steps for Creating a Procedure


Scope
Describe the syntax for creating procedures.

Focused Explanation
The syntax for creating a procedure is:
CREATE [OR REPLACE] PROCEDURE <procedure name>
[parameter1 [mode1] datatype1,
parameter2 [mode2] datatype2,
. . .)]
IS | AS
. . .
BEGIN
. . .
EXCEPTION
END <procedure name>;
Procedures are created with the CREATE PROCEDURE statement followed by the name of the procedure
and optionally followed by the argument list. The CREATE statement permits the creation of a stand-alone
procedure, which is stored in the database. The OR REPLACE clause denotes that if the procedure with
the same name already exists in the database, the procedure will be dropped implicitly and replaced with
the newer version of the procedure that is being created.
Note: The OR REPLACE clause is optional. You can create the procedure with only the CREATE
<procedure name> statement. In this case, if the procedure with the same name already exists in the
database, Oracle generates the following error at compilation time:
ORA-00955: name is already used by an existing object
The next option in the syntax of the CREATE PROCEDURE statement contains arguments or parameters.
Parameters are variables declared in the parameter list before the IS or AS keyword. These are known
as formal parameters. You can declare any number of parameters in the parameter list. Each parameter
contains a mode and a data type. When you define the data type, the length of the data type is not
allowed in the parameter list. If you specify the length of a formal parameter, Oracle issues an error at
compilation time. An argument can also use the %TYPE attribute to inherit the data type from the column
of a table, if the parameter is based on a column of a table in the database. Each parameter also has a
specific mode, which determines whether the parameter will accept or return the values to the calling
environment.

16
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Next, you declare local variables in the syntax of the procedure. Local variables are declared after the IS
or AS keyword and before the BEGIN keyword. When declaring local variables, both the data type and the
length of the data type are required. In case of a nested procedure, which is a procedure within another
procedure, the variables should be declared before you declare the nested procedure.
Note: Nested procedures are declared in the declarative section of the main program unit. All the local
variables of the main program should appear before the local subprogram declaration.
The BEGIN keyword marks the beginning of the PL/SQL block. The name of the procedure can optionally
follow the END keyword. This introduces clarity in the code and is useful when multiple procedures are
defined in the same block to mark the end of the procedure. This is also useful when nesting procedures
to improve readability in the code.

17
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create a Procedure
Scope
Know that formal parameters cannot have their data types size restricted. Identify exception errors.
Identify when to create a local subprogram defined within the program unit. Identify the purpose of formal
arguments.

Focused Explanation
A stand-alone procedure is created in the database with the CREATE <procedure name> statement in
the SQL*Plus environment. Specifying the OR REPLACE clause while creating the procedure replaces
any existing procedures with the same name in the database with the newer version of the procedure that
is being created. Procedures can optionally have a parameter list associated with them. Consider the
following code, which creates a stand-alone procedure:
SQL> CREATE OR REPLACE PROCEDURE my_first_procedure
2

(p_first_name IN VARCHAR2, p_last_name IN VARCHAR2)

AS

PROCEDURE log_info

IS

BEGIN

INSERT INTO log_table VALUES (user,sysdate);

END log_info;

BEGIN

10

INSERT INTO temp_table VALUES (p_first,p_last);

11

log_info;

12

END my_first_procedure;

13

Procedure created.
The above code creates a procedure named my_first_procedure with two formal parameters
p_first_name and p_last_name. The arguments are then used to insert the record into the table
temp_table inside the body of the procedure. In the above code, the parameters have the data type
declared, but the size is not restricted. Assigning a size to the formal parameters results in compilation
errors. Arguments declared in the parameter list of the subprogram are called formal parameters. The
purpose of formal parameters is to supply the necessary input to the subprogram to accomplish the

18
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

specified task. For example, in the above created procedure the two formal parameters are used to
populate the table with data at run time. These parameters use the data or input provided by the user
executing the procedure to populate the table.
The procedure my_first_procedure contains two sections: declarative and executable. No variables
are declared in the declarative section. However, the declaration section has another procedure named
log_info defined. Subprograms created in this manner are called local subprograms. In the example,
the procedure log_info is the local subprogram defined and invoked in the main procedure
my_first_procedure. The local subprogram enhances the clarity of the code by assigning appropriate
business-rule identifiers to blocks of code. The executable section of the parent subprogram begins with
the BEGIN keyword following the end of local subprogram declaration. The local subprogram is invoked in
the executable section of the main program.
Note: You can invoke the local subprogram anywhere in the executable section of the main subprogram.
The local subprogram must however be declared in the declarative section of the main program after the
local variables are declared.
In addition to the declarative and executable sections, the PL/SQL block in the procedure can include an
exception-handling section. The exception-handling section is denoted by the EXCEPTION keyword and is
followed by the code to handle exceptions. The PL/SQL subprograms are designed to interact with the
database. The PL/SQL engine can detect the errors in the code and the syntax at the time of compilation.
However, when the subprogram is executed, an unpredictable situation may arise when the subprogram
interacts with the database. This unpredictable situation results in an exception. The exception-handling
section traps these unpredictable situations and resolves them. An exception is referenced in the body of
the PL/SQL block and resolved in the exception-handling section.
Note: Exceptions are raised in the executable section of the subprogram. If the subprogram has an
associated exception-handling section designed, the control is transferred to that exception-handling
section. Otherwise, the block terminates unsuccessfully.

19
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Difference Between Formal and Actual Parameters


Scope
Describe formal and actual parameters.

Focused Explanation
Procedures can be created with parameters. These parameters are known as formal parameters and
appear in the parameter list before the IS or AS keyword and after the CREATE <procedure name> or
REPLACE option. For example:
CREATE PROCEDURE raise_salary (emp_id

NUMBER, emp_salary

NUMBER)

. . .
END raise_salary;
Variables defined in the parameter list of procedures are called formal parameters. In the above example,
emp_id and emp_salary are formal parameters.
The actual parameters are values passed to the subprogram when it is invoked. These values are then
assigned to the formal parameters during the subprogram call.
Actual parameters can also be expressions such as in the following statement:
raise_salary (1, salary + 1000);
The formal and actual parameters should be of compatible data types. If necessary, the PL/SQL engine
converts the data type of the actual parameter to that of the formal parameter before assigning the value
to the formal parameter. However, if the data type conversion is not possible, PL/SQL raises an error at
run time.

20
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Procedure Parameter Modes


Scope
List the types of parameter modes and their uses.

Focused Explanation
Formal parameters declared in the parameter list of a procedure can be one of three modes. The three
modes are IN, OUT, and IN OUT.
The IN Parameter Mode
When a parameter is defined with an IN mode, it indicates that this parameter will only accept the input
from the calling environment. This is the default mode and is assigned to the parameter if no mode is
assigned to the parameter. The input provided by the user is used to supply the values to the executable
section of the procedure. A default value can also be assigned when declaring formal parameters with the
IN mode. The IN parameters are read-only inside the procedure. The formal parameters declared with
the IN mode act as constants inside the procedure. This indicates that an IN parameter cannot be
modified in the body of the procedure. You can pass values, such as a literal, a constant, an expression,
or an initialized variable, to the IN parameters. For example, in the following procedure all the parameters
are defined with the IN mode:
CREATE PROCEDURE update_salary
(emp_id IN NUMBER, emp_name VARCHAR2, emp_dept IN VARCHAR2)
IS
-- PL/SQL block;
To invoke the procedure in SQL*Plus, you use the EXECUTE statement:
EXECUTE update_salary (13366,SCOTT);
To invoke the procedure from another procedure, you use a direct call:
update_salary (13366,SCOTT);
The IN parameters are passed as constants from the calling environment to the procedure. Therefore, an
attempt to change the value results in an error.

21
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The OUT Parameter Mode


When a parameter is defined with an OUT mode, it indicates that this parameter will only provide the value
or output back to the calling environment. This is not a default mode and needs to be explicitly defined.
Formal parameters of the OUT mode do not accept any input from the calling environment. Parameters of
the OUT mode cannot be assigned a default value inside the procedure. The OUT parameters do not act
as constants inside the body of the procedure and can be changed. An OUT mode parameter acts as an
uninitialized variable inside the procedure. The following code demonstrates how to declare formal
parameters of the OUT mode and how the OUT mode parameters pass values to the calling environment:
SQL>

CREATE OR REPLACE PROCEDURE update_salary

(p_emp_id IN NUMBER, p_first_name OUT VARCHAR2,p_salary OUT NUMBER)

IS

BEGIN

SELECT first_name, salary INTO p_first_name,p_salary

FROM emp WHERE emp_id=p_emp_id;

END;

Procedure created.
The above example requires the calling environment to pass the value of the employee identification
number to the procedure. The procedure is then executed, and the values for the employee first name
and salary are returned to the calling environment through the OUT mode parameters.
The calling block should hold values because the OUT parameters are required to pass a value to the
calling environment. This is accomplished by declaring the following variables:
VARIABLE v_firstname VARCHAR2(50);
VARIABLE v_salary NUMBER;
EXECUTE update_salary(1,:v_firstname,:v_salary);
PRINT v_firstname

v_salary

The variables v_firstname and v_salary are used to host values returned by the OUT parameters.
The procedure is then invoked using the EXECUTE <procedure name> command.
Note: The colon (:) is used to reference the host variables in the EXECUTE command.
The PRINT command prints the values passed to the host variables by the procedure. You can also use
the PRINT command to display the values in the host variable one by one.

22
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

For example:
PRINT v_firstname
PRINT v_salary
When declaring host variables of the NUMBER data type, the length is not specified. The commands
PRINT and VARIABLE are SQL*Plus commands.
Passing a constant or an expression as an actual parameter to an OUT variable results in a compilation
error. For example, the following statement will cause errors because the procedure invocation uses an
expression to pass the value to the OUT mode formal parameter:
EXECUTE update_salary (1,:v_firstname,:v_salary + 100);
The IN OUT Parameter Mode
When a parameter is defined with an IN OUT mode, it indicates that this parameter will accept an input
from the calling environment and also return a value. This is a combination of IN and OUT parameters.
The value returned to the calling environment can be the same value, which is accepted from the calling
environment, or a different value from the input supplied to the formal parameter. Formal parameters of
the OUT mode cannot be assigned any default value. The IN OUT parameter mode is not a default mode
and should be explicitly defined when creating variables of the IN OUT mode.
Note: Within the procedure, an IN OUT parameter acts as an initialized variable.
The following code demonstrates the use of IN OUT parameters:
SQL> CREATE OR REPLACE PROCEDURE incremented_number (p_number IN OUT NUMBER)
2

IS

BEGIN

p_number :=

END;

p_number + 1;

Procedure created.
Note: Because an IN OUT parameter will accept and return a value, the calling environment should have
a variable declared that will pass the value to and from the procedure.

23
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following code declares a host variable and then assigns a value of 1 to it inside the PL/SQL block:
VARIABLE v_number NUMBER;
SQL> BEGIN
2

:v_number := 1;

END;

PL/SQL procedure successfully completed.


The following statements are used to display the initial value of the host variable followed by the
execution of the procedure and also displays the new value returned by the procedure:
PRINT v_number
EXECUTE incremented_number (:v_number);
PRINT v_number
The variable v_number first passes the value 1 to the procedure and then hosts the value 2 provided by
the procedure. In the sample block shown above, the call to the procedure cannot have any literal
assigned to it directly to pass the value to the IN OUT formal parameter of the procedure. The call to the
procedure can only accept a variable to assign the value to the formal parameter. The following code
displays errors because the call to procedure uses a literal to assign the value to the IN OUT formal
parameter:
EXECUTE incremented_number (1);

24
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List the Methods for Calling a Procedure with Parameters


Scope
Describe the methods to execute a procedure with parameters.

Focused Explanation
Procedures created with formal parameters can use any of the methods listed below to pass the values
for the parameters:

Positional: Includes the actual parameters listed in the same sequence as the formal parameters. For
example, if there are three parameters declared in the order parameter1, parameter2, and
parameter3, the inputs to these parameters will be in the order value1, value2, and value3. The inputs
are provided in the same sequence in which the formal parameters are defined, and there is no need
to qualify the names of the formal parameters when passing values from the calling environment. For
example, you create a procedure with the following parameters:
SQL>

CREATE OR REPLACE PROCEDURE my_procedure

(p_empid IN NUMBER, p_deptcode IN NUMBER)

IS

v_empname VARCHAR2(50);

v_deptname VARCHAR2(50);

BEGIN

SELECT emp_name,emp_dept INTO v_empname,v_deptname FROM emp

WHERE emp_id = p_empid

AND dept_code = p_deptcode;

10
11

END my_procedure;
/

Procedure created.
The actual parameters for the above created procedure can be passed using positional notation. The
following example demonstrates using the positional notation for passing actual parameters:
SQL> EXECUTE my_procedure (1,10);

Named: Includes the actual parameters that are listed in any order by specifying the name of the
formal parameter. The exact order of the actual parameters is not mandatory when passing values.
However, it is necessary to use the names of the formal parameters when the procedure is called.
This method uses an association operand (=>). The syntax is parameter (n) => value.

25
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following example demonstrates using named notation for passing actual parameters to the
above created procedure my_procedure:
SQL> EXECUTE my_procedure (p_deptcode=>10, p_empid => 1);

Mixed: Includes the actual parameters that are listed using positional notation and named notation.
The first actual value, which refers to the first formal parameter in the parameter list, will use the
positional notation and the remaining will use the named notation. For example, if the parameters are
parameter1, parameter2, and parameter3, the values will be passed as value1, parameter (3) =>
value3, and parameter (2) => value2.
The following example demonstrates using mixed notation for passing actual parameters to the above
created procedure my_procedure:
SQL> EXECUTE my_procedure (1, p_deptcode => 10);

26
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

DEFAULT Options for Parameters


Scope
Identify valid procedure invocations for procedures using %TYPE DEFAULT declarations. Identify
procedure code syntax errors. Identify characteristics of the DEFAULT clause in formal parameter
declaration.

Focused Explanation
Formal parameters can also be assigned a default value in the parameter list. Instead of declaring a
formal parameter and then assigning a data type to it, a formal parameter can also be made to inherit the
data type of an underlying column of the table by using the %TYPE attribute.
The following example creates a procedure with the formal parameters that have the %TYPE attribute with
the default values:
SQL> CREATE OR REPLACE PROCEDURE create_emp
2

(empid emp.emp_id%TYPE DEFAULT 11,

firstname emp.first_name%TYPE DEFAULT 'testing',

lastname emp.last_name%TYPE DEFAULT 'data')

IS

BEGIN

INSERT INTO emp (emp_id,first_name,last_name)

VALUES (empid,firstname,lastname);

9*

END;

SQL> /
Procedure created.
Formal parameters of the IN mode can be assigned a default value when they are declared. However,
you cannot assign a default value for the OUT and IN OUT parameters. This is because assigning any
default value to an OUT or IN OUT parameter causes the following compilation error:
PLS-00230: OUT and IN OUT formal parameters may not have default expressions
You allocate a default value to the subprogram to ensure that the subprogram uses the default value if no
value is passed by the calling environment. You can use both named and positional calls to the procedure
to override the default values. However, all the parameters that use positional notation should precede
those that use named notation in the subprogram call.

27
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Formal parameters that do not have any default values assigned in the parameter list must be provided
the actual values when the procedure is invoked. When invoking a procedure, you cannot omit the actual
value of a formal parameter that does not have a default value.
When declaring parameters, the data type of the formal parameter is required. However, in situations
where either the data type of the underlying column of the table is not known or the data type of the
column of the underlying table is subject to change, it may not be feasible to define the data type of each
parameter. To deal with such situations, PL/SQL provides a %TYPE attribute. Instead of defining the data
types of each parameter, a parameter can be assigned a %TYPE attribute. When a parameter is created
with this attribute, the parameter inherits the data type of the underlying column of the table. The %TYPE
attribute can be applied for all three parameter modes.
The syntax for declaring the parameter is:
CREATE OR REPLACE PROCEDURE <procedure name>
(parameter1 mode tablename.columnname%TYPE)
AS
PL/SQL BLOCK;
If the data type of the underlying column on which the parameter has been declared changes, there is no
need to change the data type of the formal parameter in the body of the subprogram. This method
minimizes code maintenance.
Note: When declaring a parameter with the %TYPE attribute, the data type of the parameter is not
specified in the parameter list of the procedure.
You can also use default values for the parameters using the %TYPE attribute. This is also shown in the
example provided at the beginning of this section.
Procedures created with the formal parameters using the %TYPE attribute and DEFAULT values can
either use the default values when invoked without any actual parameters or the DEFAULT values can be
overridden using both positional and named notation. The following examples illustrate the calls to the
procedure create_emp from a SQL*Plus prompt using the default values or overriding the default
values:

EXECUTE create_emp; -- Uses the default values of the formal parameters.

EXECUTE create_emp (1); -- Uses the default values for the formal parameters except the
formal parameter empid.

EXECUTE create_emp (1,SCOTT,TIGER); -- Uses the values passed as actual


parameters for the formal parameters. Overrides the default values.

EXECUTE create_emp (1,firstname =>SCOTT); -- Uses the values passed as actual


parameters for the two formal parameters empid and firstname. The remaining formal parameters
use the default values.

EXECUTE create_emp (1,lastname=>TIGER); -- Uses the values passed as actual


parameters for the two formal parameters empid and lastname. The remaining formal parameters
use the default values.

Note: If no value is provided when the procedure is invoked, the actual values for the formal parameters
are provided from the default values.

28
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create a Procedure with Parameters


Scope
Identify various methods to execute a procedure with DEFAULT values. List various syntax errors in
CREATE OR REPLACE PROCEDURE statements for using IN, OUT, and %TYPE declarations

Focused Explanation
Procedures that are created with formal parameters and have default values can either use the default
value, or the default values can be overridden when the procedure is executed. The following example
creates a procedure with parameters that have DEFAULT values:
SQL>CREATE OR REPLACE PROCEDURE add_employee
2

(employee_id IN NUMBER, employee_dept IN VARCHAR2 DEFAULT 'Unknown',

location_id IN NUMBER DEFAULT 1100)

IS

BEGIN

INSERT INTO employee (emp_id, emp_dept,emp_loc_id)

VALUES (employee_id,employee_dept,location_id);

8* END;
9 /
Procedure created.
The procedure can be executed using both named and positional notation. If no values are passed for the
parameters employee_dept and location_id, the DEFAULT values are used. The following examples
illustrate some of the methods used to invoke the procedure add_employee from SQL*Plus:

EXECUTE add_employee (1); -- Uses the value 1 for the formal parameter employee_id. The
remaining formal parameters use the default values.

EXECUTE add_employee (2, employee_dept => CLERK); -- Uses the value 2 for the
formal parameter employee_id and the value CLERK for the formal parameter employee_dept.
The formal parameter location_id uses the default value.

EXECUTE add_employee (3, location_id => 1200); -- Uses the value 3 for the formal
parameter employee_id and the value 1200 for the formal parameter location_id. The formal
parameter employee_dept uses the default value.

EXECUTE add_employee (4, CLERK, 1200); -- Uses the actual parameters for all the
formal parameters. The positional notation overrides the default values for the formal parameters.

29
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Note: When using mixed notation to pass the values, all the parameters specified with positional notation
must precede the parameters specified with named notation in the subprogram call.
If the parameters specified with positional notation do not precede the parameters specified with named
notation, the following error is generated at run time:
PLS-00312: a positional parameter association may not follow a named
association
The parameters for the procedure add_employee can also use the %TYPE attribute to declare the data
type. In this scenario, the parameter list will be specified as follows:
SQL>CREATE OR REPLACE PROCEDURE add_employee
2

(employee_id IN employee.emp_id%TYPE,

employee_dept IN employee.emp_dept%TYPE DEFAULT 'Unknown',

location_id IN employee.emp_loc_id%TYPE DEFAULT 1100)

Arguments created with the %TYPE attribute cannot include a data type specified in the parameter list. For
example, the following code is invalid:
SQL>CREATE OR REPLACE PROCEDURE add_employee
2

(employee_id IN employee.emp_id%TYPE NUMBER,

employee_dept IN VARCHAR2 DEFAULT 'Unknown',

location_id IN NUMBER DEFAULT 1100)

IS

BEGIN

INSERT INTO employee (emp_id,emp_dept,emp_loc_id)

VALUES (employee_id,employee_dept,location_id);

9* END;
10 /
Warning: Procedure created with compilation errors.

30
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

To view the errors in SQL*Plus, you use the SHOW ERRORS or SHOW ERR command:
SQL> SHOW ERR
Errors for PROCEDURE ADD_EMPLOYEE:
LINE/COL ERROR
-------- ----------------------------------------------------------------2/33

PLS-00103: Encountered the symbol "NUMBER" when expecting one of


the following:
:= ) , default character
The symbol ":=" was substituted for "NUMBER" to continue.

The %TYPE attribute can be used with all the three parameter modes: IN, OUT, and IN OUT. You can
specify default values to the parameters of the IN mode when using the %TYPE attribute. The OUT and IN
OUT parameters cannot be assigned any default values.
The values of parameters declared with the IN mode cannot be changed in the block. The following code
generates compilation errors because in this code you are modifying the value for the IN parameter:
SQL>CREATE OR REPLACE PROCEDURE add_employee
2

(employee_id IN emp.emp_id%TYPE ,

employee_dept IN VARCHAR2 DEFAULT 'Unknown',

location_id IN NUMBER DEFAULT 1100)

IS

BEGIN

employee_id :=4;

INSERT INTO emp (emp_id,first_name,mgr_id)

VALUES (employee_id,employee_dept,location_id);

10* END;
SQL> /
Warning: Procedure created with compilation errors.
SQL> show err

31
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Errors for PROCEDURE ADD_EMPLOYEE:


LINE/COL ERROR
-------- ----------------------------------------------------------------6/1

PLS-00363: expression 'EMPLOYEE_ID' cannot be used as an


assignment target

6/1

PL/SQL: Statement ignored

The OUT parameters cannot be assigned a default value inside the parameter list. The following code
generates compilation errors because in this code you are attempting to assign an OUT parameter a
default value in the parameter list:
SQL>CREATE OR REPLACE PROCEDURE view_employee
2

(employee_id IN emp.emp_id%TYPE ,

firstname OUT VARCHAR2 DEFAULT 'Unknown')

IS

v_firstname vARCHAR2(50);

BEGIN

SELECT first_name INTO v_firstname FROM employee

WHERE emp_id=employee_id;

9* END;
SQL> /
Warning: Procedure created with compilation errors.
SQL> show err
Errors for PROCEDURE VIEW_EMPLOYEE:
LINE/COL ERROR
-------- ----------------------------------------------------------------2/35
PLS-00230: OUT and IN OUT formal parameters may not have default
expressions
The IN and IN OUT parameters define the values that will be used in the executable section of the
procedure. Consider a scenario where a procedure is used to display the first and last name of all the
students enrolled in a particular semester. In this scenario, the value for the semester is accepted from
the calling environment and passed to the formal parameter of mode IN or IN OUT. Next, the query is
executed based on the input from the formal parameter, and the desired output is displayed. In this
scenario, the parameters of the IN and IN OUT modes provide the necessary values to the executable
section of the block.

32
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoke a Procedure with Parameters


Scope
Identify the valid calls for procedure with the IN parameters. Identify the correct command to execute a
procedure from the SQL*Plus prompt.

Focused Explanation
Stand-alone procedures can be invoked from the SQL*Plus prompt. These procedures can also be
invoked from within another procedure or from an anonymous PL/SQL block. Procedures can be invoked
from any tool or language that supports PL/SQL.
To invoke a stand-alone procedure from SQL*Plus, you use the following command:
EXECUTE update_salary (1);
Note: The EXECUTE or EXEC statement is used to invoke an independent procedure from SQL*Plus. The
EXECUTE or EXEC keyword is followed by the name of the procedure and arguments.
The following example demonstrates invoking a procedure, update_salary, from an anonymous
PL/SQL block:
SQL> DECLARE
2

v_empid NUMBER :=1;

BEGIN

update_salary (v_empid);

END;

Procedures can also be invoked from within another procedure. The following example demonstrates
invoking a procedure, update_salary, from within another procedure, proc1:
CREATE OR REPLACE PROCEDURE proc1
IS
. . .
BEGIN
. . .
update_salary (1);
END proc1;

33
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following statements create a procedure where a default value is assigned to the IN mode parameter
p_empid:
SQL> CREATE OR REPLACE PROCEDURE invoke_me (p_empid IN NUMBER DEFAULT 1)
2

IS

v_firstname VARCHAR2(50);

v_lastname VARCHAR2(50);

BEGIN

SELECT first_name,last_name INTO v_firstname,v_lastname

FROM emp WHERE emp.id=p_empid;

8*

END;

Procedure created.
You can use both named and positional notation to pass values to the parameters of the IN mode. To
successfully invoke the procedure at the SQL*Plus prompt, you use the following statements:
EXECUTE invoke_me; -- Uses the default value.
EXECUTE invoke_me(2); -- Uses the positional notation and overrides the default value.
EXECUTE invoke_me (p_empid=> 3); -- Uses the named notation and overrides the default value.
If the procedure is created without any formal parameters, the call to the procedure at the SQL*Plus
prompt specifies only the procedure name. For example, for a procedure update_salary created
without any formal parameters, you would invoke the procedure using:
SQL>EXECUTE update_salary;
or
SQL> EXEC update_salary;

34
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Declare a Subprogram in the Declarative Section of a Procedure


Scope
Describe how to declare a subprogram in the declarative section of a procedure.

Focused Explanation
Subprograms, such as procedures and functions, can be declared in any PL/SQL block, package, or
another subprogram. For example:
SQL> CREATE OR REPLACE PROCEDURE example AS
2

(p_empid IN emp.emp_id%TYPE)

IS

PROCEDURE log_info IS

BEGIN

INSERT INTO log_table (user_id, log_date) VALUES (user, sysdate);

END log_info;

BEGIN

DELETE FROM emp WHERE emp_id = p_empid;

10

log_info;

11

END example;

The above example declares a local subprogram named log_info in the declarative section of the main
program example. The local subprogram is then invoked in the executable section of the main program.
The declarative section of the main program example begins after the AS keyword and ends after the
declaration of the local subprogram marked with the statement END log_info;. The BEGIN keyword
following the end of declaration of log_info marks the beginning of the executable section of the parent
program example. The executable section of the procedure example ends with the statement END
example;.
Subprograms declared in the declarative section of the parent subprogram are called local subprograms.
Local subprograms must be declared in the declarative section of the parent subprogram. In addition,
other variables need to be declared first in the declarative section of the main program. The local
subprogram should be placed last in the declarative section. Otherwise, a compilation error will be
generated. Local subprograms can only be referenced from within the main program. This indicates that
the local subprogram cannot be invoked from outside the parent subprogram.
Note: If you need to use the local subprogram from outside the parent subprogram, then either the local
subprogram should be created as a stand-alone procedure or as a procedure inside a package.

35
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Exception Handling in PL/SQL Subprograms


Scope
Describe how exceptions are propagated in a subprogram.

Focused Explanation
Exceptions can be defined as unpredictable situations arising in the subprogram when it is executed. An
exception-handling section in the subprogram deals with these situations. Exceptions can be either an
Oracle error or a user-defined error. Oracle errors are predefined exceptions enclosed in the STANDARD
package. User-defined exceptions are defined by the programmer when the subprogram interacts with
the database and an unpredictable situation arises. User-defined exceptions are raised using the RAISE
statement. Exceptions are raised at either compile time or at run time. The PL/SQL engine detects
compilation errors when the subprogram is created and the errors are returned to the user. Run time
errors are detected when the program is executed. User-defined exceptions are normally invoked at run
time.
As a rule of thumb, exceptions are declared in the declarative section, raised in the executable section,
and handled in the exception-handling section. When an exception is raised, the control is passed to the
exception-handling section. The control is never transferred back to the executable section after the
exception is handled. This control passes or propagates to the enclosing block.
You use the RAISE statement to invoke user-defined exceptions. The following example demonstrates
the usage of the RAISE statement:
SQL> CREATE OR REPLACE PROCEDURE use_raise (p_empid IN NUMBER)
2

IS

raise_me EXCEPTION;

v_firstname VARCHAR2(50);

v_lastname VARCHAR2(50);

BEGIN

SELECT first_name,last_name INTO v_firstname,v_lastname

FROM emp WHERE emp_id=p_empid;

INSERT INTO log_info (userid,log_date) VALUES (user,sysdate);

10

EXCEPTION

11

WHEN NO_DATA_FOUND THEN

12

RAISE raise_me;

13*

END;

SQL> /
Procedure created.

36
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

SQL> EXECUTE use_raise(1000);


ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at "SCOTT.USE_RAISE", line 10
ORA-01403: no data found
ORA-06512: at line 1
The above example declares an exception named raise_me in the declarative section of the program.
Next, an exception is raised in the executable section of the block when the procedure executes. This
causes the control to be transferred to the exception-handling section of the block. The exceptionhandling section uses the RAISE statement to invoke an unhandled user-defined exception. In the above
example, the exception is said to be unhandled because no action has been specified in the exceptionhandling section if data is not found in the emp table. The INSERT statement in the block does not
execute because the exception is not handled.
You can view this information by invoking a query on the log_info table:
SQL> SELECT * FROM log_info;
no rows selected
If the procedure executes successfully, the data is inserted into the log_info table:
SQL> EXECUTE use_raise(1);
PL/SQL procedure successfully completed.
SQL> SELECT * FROM log_info;
USERID

LOG_DATE

----------------------------------------------------------------------------SCOTT

02-APR-04

37
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Exceptions can also be raised in the exception-handling section. This can be done explicitly by using the
RAISE statement, or it can be an Oracle error raised by Oracle if the code is not able to relate to the
database in the desired manner. In either case, the exception is propagated to the enclosing block. At a
given point, only one exception can be active inside the exception-handling section. This indicates that in
the exception-handling section another exception can be raised only when the first one is handled. In
such scenarios, the exception that is raised will propagate to the enclosing or outer block even when
there is a handler for the exception in the current exception-handling section. For example:
DECLARE
X EXCEPTION;

/* EXCEPTION X IS DECLARED*/

Y EXCEPTION;

/* EXCEPTION Y IS DECLARED*/

BEGIN
RAISE X;

/* EXCEPTION X IS RAISED*/

EXCEPTION
WHEN X THEN

/* EXCEPTION X IS HANDLED AND Y IS RAISED*/

RAISE Y;
WHEN Y THEN

/* EXCEPTION Y IS NOT HANDLED EVEN WHEN THERE IS A HANDLER*/

. . .
END;
/* THE BLOCK TERMINATES UNSUCCESSFULLY LEAVING Y AS AN UNHANDLED EXCEPTION*/
In the above example, there is no enclosing block when an exception Y is raised, and the block
terminates unsuccessfully.
In the following example, the block executes successfully because there is an outer block to handle the
exception Y:
DECLARE
X EXCEPTION;

/* EXCEPTION X IS DECLARED*/

Y EXCEPTION;

/* EXCEPTION Y IS DECLARED*/

BEGIN
RAISE X;

/* EXCEPTION X IS RAISED*/

EXCEPTION

38
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

WHEN X THEN

/* EXCEPTION X IS HANDLED AND EXCEPTION Y IS RAISED*/

RAISE Y;
WHEN Y THEN

/* EXCEPTION Y IS PROPAGATED TO THE OUTER BLOCK*/

. . .
END;
EXCEPTION

/* Y IS HANDLED IN THIS BLOCK */

WHEN Y THEN
END;
/* BLOCK TERMINATES SUCCESSFULLY AND CONTROL IS TRANSFERRED TO THE CALLING
ENVIRONMENT */
The above scenario explains how a raised exception in the exception handler propagates to the enclosing
block and how the RAISE statement is used to invoke an exception inside the exception handler. The
RAISE statement can also be used without parameters. If no parameter is passed for the RAISE
statement, it raises the current exception again. For example:
DECLARE
X EXCEPTION;
BEGIN
RAISE X;

/* EXCEPTION X IS RAISED*/

EXCEPTION
WHEN X THEN

/* EXCEPTION X IS HANDLED*/

. . .
RAISE;

/* CURRENT EXCEPTION X IS AGAIN INVOKED */

END;
/* BLOCK TERMINATES UNSUCCESSFULLY WITH UNHANDLED EXCEPTION X AS RERAISED
EXCEPTION X CAUSES THE EXCEPTION TO PROPAGATE TO THE OUTER BLOCK AND THERE IS
NO OUTER BLOCK TO HANDLE IT */
In scenarios where a procedure calls another procedure, exceptions raised in the called procedure cause
the control to be transferred to the exception-handling section of the called procedure. If the exception is
handled, the block terminates and control is transferred to the calling procedure. All DML statements in
the called and calling procedures remain intact.

39
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

If the exception is not handled in the called procedure, the control is transferred to the exception-handling
section of the calling procedure. If the exception is handled, all the statements remain intact. If the
exception is not handled in the calling procedures exception-handling section, all the statements are
rolled back, and the exception propagates to the calling environment.
For example:
PROCEDURE proc1

PROCEDURE proc2

IS

IS

. . .

. . .

BEGIN

BEGIN

. . .

. . .

proc2;

EXCEPTION

. . .

. . .

EXCEPTION

END proc2;

---- EXCEPTION RAISED

---- EXCEPTION UNHANDLED

. . . -------Control returns to the exception section of the calling procedure.


END proc1;
In the above example, an exception is raised in the called procedure proc2. This causes the control to
be transferred to the exception-handling section of the called procedure. However, the called procedure
does not handle the exception, and the exception then propagates to the exception-handling section of
the calling procedure proc1. If the exception is handled, the block terminates successfully. Otherwise,
the exception propagates to the outer block, which is the calling environment, and rolls back all the
statements in the called and calling procedures.

40
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Remove a Stored Procedure


Scope
Describe how to drop a procedure and understand the accompanying effects.

Focused Explanation
A stand-alone stored procedure can be removed from the database by issuing the following statement at
the SQL*Plus prompt:
DROP PROCEDUE <procedure name>;
To drop a procedure, the procedure must be present in your schema or if you are assigned the DROP
ANY PROCEDURE system privilege, the schema name should precede the procedure name.
For example:
DROP ANY PROCEDURE <schema name>.<procedure name>;
The DROP PROCEDURE statement is a DDL command. Therefore, the procedure cannot be recovered if a
ROLLBACK is issued after dropping it.
You need to consider the following restrictions when using the DROP PROCEDURE statement:

You cannot drop a procedure that is a part of a package. Instead, either the package should be
re-created without the procedure, or the package should be dropped.

You cannot issue the command DROP PROCEDURE <procedure name> from inside a PL/SQL
block.

If the object on which the procedure has been built is dropped, the procedure is not removed from the
data dictionary. The status of such procedures in marked as INVALID. The status can be queried from
the STATUS column of the data dictionary view USER_OBJECTS.
If a procedure references another procedure and the referenced procedure is dropped, the procedure that
refers to the dropped procedure is marked as INVALID by Oracle. The status of such procedures can be
viewed from the STATUS column of the USER_OBJECTS view. For example, there are two procedures p1
and p2, and the procedure p1 references procedure p2. If p2 is dropped, the status of p1 is marked as
INVALID. When the procedure p1 is subsequently executed, Oracle will try to recompile the procedure
p1, and if the procedure p2 has not been re-created, Oracle will issue an error at run time.

41
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Creating Procedures: Program with PL/SQL.


Identify characteristics of stored procedures.
Describe the syntax for creating procedures.
Know that formal parameters cannot have their data types size restricted.
Identify exception errors.
Identify when to create a local subprogram defined within the program unit.
Identify the purpose of formal arguments.
Describe formal and actual parameters.
List the types of parameter modes and their uses.
Describe the methods to execute a procedure with parameters.
Identify valid procedure invocations for procedures using %TYPE DEFAULT declarations.
Identify procedure code syntax errors.
Identify characteristics of the DEFAULT clause in formal parameter declaration.
Identify various methods to execute a procedure with DEFAULT values.
List various syntax errors in CREATE OR REPLACE PROCEDURE statements for using IN, OUT,
and %TYPE declarations.
Identify the valid calls for procedure with the IN parameters.
Identify the correct command to execute a procedure from the SQL*Plus prompt.
Describe how to declare a subprogram in the declarative section of procedure.
Describe how exceptions are propagated in a subprogram.
Describe how to drop a stored procedure and understand the accompanying effects.

42
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating Functions: Program with


PL/SQL

43
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Explain Stored Functions


Scope
Identify the characteristics of a stored function.

Focused Explanation
Stored functions are named PL/SQL blocks that are stored in the database or at the client side using
tools, such as Oracle Forms or Oracle Reports. The purpose of a function is to accept zero or more
arguments and return a value. Functions can be called from SQL statements or PL/SQL program units as
part of an expression. Functions called as part of SQL expressions must conform to certain restrictions.
These restrictions define the purity level of functions.
Oracle provides many built-in functions, such as INSTR and SUBSTR, which are already being used in the
database to manipulate data.
The many characteristics of functions are discussed below:

Functions are required to return a value and only one value through the call to the function itself.
This return value is embodied in the function call in such a manner that the function behaves like
a variable. Although a function can return more than one value, it is not a good programming
practice to do so.

Functions can accept parameters in three modes: IN, OUT, and IN OUT.

Technically, functions created with any of the three parameter modes will compile and run
successfully. Again, it is not a good programming practice to build functions with mode other than
IN because functions always return a value.

Functions stored in the database are called stored functions. Functions can also be created using
client-side tools, such as Oracle Forms Developer. Functions are stored in the database as
schema objects and can be used by all applications and users accessing the database. Functions
promote reusability in the sense that if there are modifications to the underlying objects that the
function references, only the function needs to be changed.

The structure of functions is similar to procedures. However, a function must return a value to the
calling environment, whereas a procedure may or may not return a value. Logically, functions
return a single value, whereas procedures can return more than one value.

Note: Functions called in PL/SQL expressions can be used wherever variables are used in the PL/SQL
expression.

44
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create Functions
Scope
Know how to create a stored function.

Focused Explanation
Stand-alone functions that are stored in the database are created with the CREATE <function name>
statement. The CREATE statement creates the function and stores it in the database. If there are
compilation errors in the CREATE statement, the function is still created.
Note: Functions having compilation errors will have an invalid status, and these functions cannot be
invoked.
The syntax for creating a function is similar to that of creating a procedure with the addition of a RETURN
statement. The following is the syntax for CREATE FUNCTION:
CREATE [OR REPLACE] FUNCTION <function name> [(parameter [mode1] datatype1,
parameter2 [mode2] datatype2 ...)]
RETURN datatype
IS | AS
PL/SQL BLOCK;
In the above syntax, the OR REPLACE clause indicates that if the function already exists, it will be
dropped and then re-created.
The RETURN statement includes a data type, but the length is not allowed. There must be at least one
RETURN statement in the function, and the function must return a value to the calling block.
The PL/SQL block starts with the BEGIN keyword or a declaration of local variables and ends with the
END or END <function name>.
Note: Host or bind variables cannot be referenced in the PL/SQL block of the function.
The following is an example of the CREATE FUNCTION statement:
SQL> CREATE OR REPLACE FUNCTION func_last_name (p_empid NUMBER)
2

RETURN VARCHAR2

IS

v_lastname VARCHAR2 (50);

BEGIN

SELECT last_name INTO v_lastname FROM emp WHERE emp_id = p_empid;

RETURN v_lastname;

END;

Function created.

45
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The function func_last_name uses a parameter p_empid to accept the value for employer
identification and returns the corresponding last name to the calling environment using the RETURN
statement.
The header portion of the function contains the RETURN keyword, which also identifies the data type that
needs to be returned to the calling block. The RETURN statement in the executable section of the function
performs the actual returning of the value. Therefore, the header section defines the return data type of
the value, and the executable section does the actual returning.
Note: The data type of the two return statements must be compatible for a function to successfully
compile.
There can be more than one RETURN statement in the executable section of the function, but the function
stops executing when it meets the first RETURN statement. At this point, control is returned to the calling
block, and as a result, the PL/SQL statements following the RETURN statement will not be executed.
However, this is not a requirement for the function to successfully parse. A function will be successfully
compiled even if there are statements following the RETURN statement.
There should be a RETURN statement in the function body. If the RETURN statement in the executable
section is omitted, the function will successfully compile but the following error will be generated at run
time:
ORA-06503: PL/SQL: Function returned without value
This is because the function does not return any value to the calling block.
If the function is created without a RETURN statement, the function will not compile. The following example
attempts to create a function without a RETURN statement:
SQL> CREATE OR REPLACE FUNCTION func_last_name (p_empid NUMBER)
2

IS

BEGIN

SELECT last_name INTO v_lastname FROM emp WHERE emp_id = p_empid;

END;

Warning: Function created with compilation errors.

46
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

To view the compilation errors, you use the SHOW ERRORS or SHOW ERR command at the SQL*Plus
prompt.
SQL> SHOW ERR
Errors for FUNCTION func_last_name:
LINE/COL ERROR
-------- ----------------------------------------------------------------2/4

PLS-00103: Encountered the symbol "IS" when expecting one of the


following:
return

Using stored functions can also increase the efficiency of queries. Functions can be used on the server to
filter the data by applying them on the queries and then fetching the appropriate data in the application.
You can use functions in the WHERE clause of the query to perform the filtering task. This method is more
straightforward than fetching the data in the application and then using functions to filter the data.

47
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoking Functions
Scope
Identify expressions to invoke a function.

Focused Explanation
Functions are called as a part of an expression. Functions can be called either from PL/SQL or SQL
statements. However, the return data type should be compatible when a function is called from a SQL
statement. For example, the BOOLEAN data type is not recognized by SQL, so a function returning a
BOOLEAN data type cannot be invoked from a SQL statement.
Functions called from SQL Statements
Functions invoked using SQL statements should be stored in the database. This indicates that a function
stored in client-side tools cannot be invoked from SQL statements. The return data type should be
compatible to the calling interface, such as the BOOLEAN data type. In addition, the function should have
parameters of only the IN mode.
Functions can be invoked as part of SELECT statements (in the column list, WHERE, GROUP BY, HAVING
and ORDER BY clauses), in the UPDATE statement (in the SET and WHERE clause), in the DELETE
statement (in the WHERE clause), and in the INSERT statement (in the VALUES clause).
The following code creates a procedure and invokes the function as part of a SELECT statement:
SQL> CREATE OR REPLACE FUNCTION func_last_name (p_empid NUMBER)
2 RETURN VARCHAR2
3 IS
4 v_lastname VARCHAR2 (50);
5 BEGIN
6 SELECT last_name INTO v_lastname FROM emp WHERE emp_id = p_empid;
7 RETURN v_lastname;
8* END;
9 /
Function created.

48
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The function is then called from a SQL query. To call this function, you run the following query:
SQL> SELECT func_last_name(1) FROM dual;
func_last_name(1)
----------------------------------------------------------------------------Clark
The following is also a valid call for the function func_last_name:
SQL> SELECT first_name FROM emp WHERE last_name=func_last_name(1);
FIRST_NAME
----------------------------------------------------------------------------Michael
Functions can also be invoked by declaring environment variables in SQL*Plus. For example:
SQL> VARIABLE lastname VARCHAR2(50);
SQL> EXECUTE :lastname := func_last_name(1);
PL/SQL procedure successfully completed.
SQL> PRINT lastname
LASTNAME
----------------------------------------------------------------------------Clark
The VARIABLE command declares a variable named lastname to host the value returned by the
function. The EXECUTE command then invokes the function and passes the value to the bind variable.
Next, the PRINT command displays the value returned by the function.

49
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Functions called from PL/SQL Expressions


A function can be invoked as part of a PL/SQL expression. Functions can be invoked as part of an
IF..THEN..ELSE statement a WHILE loop, the right side of an assignment statement, as parameter
values to other functions, and in the calculation of a variables default value. Therefore, you can use a
function wherever a variable can be successfully used in PL/SQL statement. The following example
demonstrates calling the function func_last_name as part of an assignment statement:
SQL> DECLARE
2 v_lastname VARCHAR2 (50);
3 BEGIN
4 v_lastname:= func_last_name (1);
5 DBMS_OUTPUT.PUT_LINE (v_lastname);
6* END;
SQL> /
Clark
PL/SQL procedure successfully completed.
This example shows invoking a function as part of an IF..THEN..ELSE statement:
SQL> BEGIN
2 IF (func_last_name (1) = 'Clark')
3 THEN
4 DBMS_OUTPUT.PUT_LINE ('FOUND CLARK');
5 END IF;
6* END;
SQL> /
FOUND CLARK
PL/SQL procedure successfully completed.

50
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Advantages of Using User-Defined Functions in SQL Statements


Scope
List the benefits of using user-defined functions in SQL expressions.

Focused Explanation
Oracle provides many built-in functions, such as INSTR and SUBSTR. You can use user-defined functions
at places where an Oracle-supplied function can be used. User-defined functions can be created to
extend the existing functionality or to provide the functionality not available in Oracle. The following are
the advantages of user-defined functions:

User-defined functions promote SQL where the requirement is unavailable with Oracle or the
requirement is too complex to implement using the Oracle built-in functions alone.

User-defined functions increase the efficiency of queries by applying the functions in the query
itself. This drastically improves the performance because the query is designed to use the
function instead of using the query and functions separately from client-side tools when enforcing
application logic. For example, the query can be designed to use the function in the WHERE clause
to filter out unwanted data, skipping the evaluation process by the application.

User-defined functions can be used to manipulate character strings to represent special data
types, such as temperature.

User-defined functions can include SQL statements that use the parallel query feature to run in
parallel.

When using a function in a SQL expression, the value returned by the function should be compatible with
SQL. Returning a data type that is acknowledged by SQL is required. Otherwise, the function cannot be
invoked. You cannot use PL/SQL data types, such as BOOLEAN, RECORD, or TABLE for returning values.
As a rule, these data types cannot be used in functions called from SQL expressions.
The following is an example of a user-defined function that is invoked as part of a SQL expression:
SQL> CREATE OR REPLACE FUNCTION f1(var VARCHAR2)
2

RETURN VARCHAR2

IS

res VARCHAR2(20);

BEGIN

SELECT LOWER(SUBSTR(var,1,1))||UPPER(SUBSTR(var,2))

INTO res FROM dual;

RETURN res;

9
10

END;
/

Function created.

51
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The above code is an example of a user-defined function that can be used in SELECT, UPDATE and
DELETE statements. The above function will achieve the opposite of what the INITCAP built-in function
does.
The Oracle-supplied function INITCAP changes the case of the first alphabetic character of the specified
string to uppercase. The following code demonstrates the usage of INITCAP:
SQL>SELECT INITCAP(ename) FROM emp;
Clark
Michael
Shane
The user-defined function f1 changes the first alphabetic character of the specified string to lowercase.
The following example demonstrates the usage of f1:
SQL>SELECT f1(ename) FROM emp;
cLARK
mICHAEL
sHANE
You can use user-defined functions against any table, but the parameters being passed to the userdefined function are bound to the data types of the columns of the table.
The return value of a user-defined function is determined by the functionality of the user-defined function.

52
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoking User-Defined Functions from SQL Statements


Scope
Identify statements to invoke a function from SQL.

Focused Explanation
Functions can be invoked as part of SELECT statements (in the column list, WHERE, GROUP BY, HAVING
and ORDER BY clauses), in the UPDATE statement (in the SET and WHERE clause), in the DELETE
statement (in the WHERE clause) and in the INSERT statement (in the VALUES clause).
The following code invokes the function func_last_name within a SELECT statement:
SQL> SELECT func_last_name (1) FROM dual;
func_last_name (1)
----------------------------------------------------------------------------Clark
The following example creates a function that accepts a numeric value as a parameter and returns a
numeric value that is 30 percent of the specified value:
SQL> CREATE OR REPLACE FUNCTION basic (p_value IN NUMBER)
2

RETURN NUMBER

IS

BEGIN

RETURN (p_value * 0.3);

END basic;

Function created.
The following example demonstrates the usage of the basic function:
SQL> SELECT last_name, first_name, salary, basic(salary)
2

FROM emp WHERE dept_id=10;

LAST_NAME

FIRST_NAME

SALARY

BASIC(SALARY)

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

---

---

Clark

5000

1500

Michael

53
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following example invokes the function both within the ORDER BY clause and the SELECT statement:
SQL>

SELECT last_name, first_name, salary, basic(salary)

FROM emp WHERE dept_id=10

ORDER BY basic(salary) DESC;

LAST_NAME

FIRST_NAME

SALARY

BASIC(SALARY)

---------

--------

-----

-----

Langer

Justin

8000

2400

Hayden

Matthew

7000

2100

Waugh

Steve

6000

1800

Clark

Michael

5000

1500

The following example uses the basic function to display the average basic salary of each department.
Note: In the following example the Oracle built-in function AVG is used with the user-defined function both
in the SELECT statement and the HAVING clause:
SQL> SELECT dept_id, AVG (basic(salary))
2 FROM emp
3 GROUP BY dept_id
4 HAVING AVG(basic(salary)) > 1500;
DEPT_ID

AVG(basic(salary))

-------

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

10

1950

20

2100

54
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Restrictions on Calling Functions from SQL Statements


Scope
List the restrictions on invoking functions from SQL statements.

Focused Explanation
Functions called from SQL statements must use positional notation to pass values to the IN parameters.
To invoke a function from SQL statements, the function must have only parameters of the IN mode.
Functions that modify any database tables cannot be used with a SELECT statement.
The following code can be used with the SELECT statement because it does not modify any database
tables:
SQL> CREATE OR REPLACE FUNCTION basic (p_value IN NUMBER)
2 RETURN NUMBER
3 IS
4 BEGIN
5 RETURN (p_value * 0.3);
6 END basic;
7 /
Function created.
The following example demonstrates the usage of basic:
SQL> SELECT basic(salary) FROM emp;
basic(salary)
------------1500
2100
450
1800
2100
2400
6 rows selected.

55
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

However, attempting to use a function in a SELECT statement that modifies database tables will generate
the following error:
ORA-14551: cannot perform a DML operation inside a query
You can also use functions in UPDATE or DELETE statements. However, such functions cannot query or
modify any database tables modified by that statement. The following usage of the function is valid in the
UPDATE statement:
SQL> UPDATE emp SET salary=basic(5000) WHERE emp_id=8;
1 row updated.
However, the following usage of the function is invalid because the function body tries to insert the data in
the emp table. This function is then used in the UPDATE statement to update the salary of the emp table.
When invoked in the UPDATE statement the function returns an error message that the table is mutating.
Note: Mutation occurs when the function called from an UPDATE or DELETE statement on a table X is
also querying table X at the same time.
SQL> CREATE OR REPLACE FUNCTION restrictions_with_functions
2

(p_salary IN NUMBER)

RETURN NUMBER

IS

BEGIN

INSERT INTO emp (emp_id, last_name, first_name, salary)

VALUES (100,'testing','data',1000);

RETURN (p_salary + 1000);

END;

10

Function created.
SQL> UPDATE emp SET salary = restrictions_with_functions(2000)
2

WHERE emp_id=1;

UPDATE emp SET salary = restrictions_with_update(2000)


*
ERROR at line 1:
ORA-04091: table SCOTT.EMP is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.RESTRICTIONS_WITH_FUNCTIONS", line 5
Functions called from SQL statements cannot use transaction control language, such as COMMIT, session
control language, such as SET ROLE, system control language, such as ALTER SYSTEM, and DDL
statements, such as CREATE.

56
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Functions called from SQL statements must use positional notation to pass values to the parameters. As
per Oracle, named notation is not allowed for passing values to the function. This concept is shown in the
example given below:
SQL> CREATE OR REPLACE FUNCTION func_last_name (p_empid NUMBER, p_deptid
NUMBER)
2 RETURN VARCHAR2
3 IS
4 v_lastname VARCHAR2 (50);
5 BEGIN
6 SELECT last_name INTO v_lastname FROM emp
7 WHERE emp_id=p_empid AND dept_id=p_deptid;
8 RETURN v_lastname;
9* END;
SQL> /
Function created.
SQL> SELECT func_last_name (p_deptid=>10, p_empid=>1) FROM DUAL;
SELECT func_last_name (p_deptid=>10, p_empid=>1) FROM DUAL
*
ERROR at line 1:
ORA-00907: missing right parenthesis
However, the following SELECT statement is valid because it uses positional notation to pass the values
to the function:
SQL> SELECT func_last_name (1, 10) FROM DUAL;
func_last_name (1, 10)
----------------------------------------------------------------------------Clark
Functions called from SQL expressions should return the data type that is compatible with SQL. For
example, the BOOLEAN, RECORD, or TABLE data types are not supported by SQL. All other SQL data
types are supported if the function is invoked as part of the SQL expression.

57
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Only stored functions can be called from SQL expressions.


To summarize, the restrictions on functions that are invoked as part of SQL expressions are:

Functions should be stored in the database.

Functions should return data types acceptable by SQL.

Functions should not include any transaction, session, or system control statements.

Functions should have formal parameters of the IN mode.

Functions should not modify any database tables, if called as part of a SELECT statement.

Functions should not modify or read the same table, if called as part of an UPDATE or DELETE
statement.

Functions should use only positional notation to pass values to the formal parameters.

58
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Remove a Stored Function


Scope
Drop a stored function.

Focused Explanation
Stored functions can be permanently removed from the database by dropping them. You use the
following statement for dropping a stand-alone stored function:
DROP FUNCTION <function name>;
You can remove the function from the database without having to remove the underlying tables that the
function references.
Existing functions in the database are dropped automatically by Oracle when there is an attempt to create
a function with the same name using the following statement:
CREATE OR REPLACE FUNCTION func_count_emp
RETURN NUMBER;
AS
PL/SQL BLOCK;
The OR REPLACE clause in the above example first drops the existing function, if any exists with the
same name, and then the CREATE keyword re-creates the function func_count_emp with the newer
version of code.
If the CREATE OR REPLACE <function name> statement is issued without the OR REPLACE clause,
and the function with the same name already exists in the database then the following error message is
generated:
ORA-00955: name is already used by an existing object
Note: Functions can be dropped explicitly before re-creating the function with the same name by using
the DROP FUNCTION statement or implicitly by Oracle using the OR REPLACE clause when building a
function. However, when you use the OR REPLACE clause, the user is not aware that an existing function
is being dropped by Oracle.

59
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe Differences Between Procedures and Functions


Scope
List the differences between procedures and functions.

Focused Explanation
Table 3-1 describes the differences between functions and procedures.

Functions

Procedures

Functions must return a single value to the


calling block.

Procedures may or may not return a value to the calling


block. Procedures can also return more than one value
to the calling block.

Functions are called as part of an expression.

Procedures are called through a PL/SQL statement.

Functions use a RETURN statement in the


CREATE FUNCTION statement.

Procedures do not use a RETURN statement.

Functions use a RETURN statement to pass a


value to the calling block.

Procedures use a parameter of the OUT mode to pass a


value to the calling block.
Table 3-1

The CREATE OR REPLACE statements for functions will generate a run-time or compile-time error without
a RETURN statement. This is because the RETURN statement is mandatory in the function code. However,
this RETURN statement is not allowed when creating a procedure.
Procedures use OUT mode parameters to pass values to the calling environment. Technically, the OUT
and IN OUT mode parameters can be used when creating a function. This indicates that the parsing
machine will not have any problem in compiling the function. However, these functions cannot be called
from SQL statements.
The following two examples demonstrate the correct statements for creating a procedure and function.
Both the procedure and function return a value to the calling environment, but the function uses a RETURN
statement, and the procedure uses an OUT mode parameter.
The procedure is created using the following code:
SQL>

CREATE OR REPLACE PROCEDURE display_lastname

(p_empid IN NUMBER, p_lastname OUT VARCHAR2)

IS

v_lastname VARCHAR2(50);

60
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

BEGIN

SELECT last_name INTO v_lastname FROM emp WHERE emp_id = p_empid;

END;

Procedure created.
The function is created using the following code:
SQL> CREATE OR REPLACE FUNCTION func_display_lastname (p_empid IN NUMBER)
2

RETURN VARCHAR2

IS

v_lastname VARCHAR2(50);

BEGIN

SELECT last_name INTO v_lastname FROM emp WHERE emp_id = p_empid;

RETURN v_lastname;

END;

Function created.

61
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Creating Functions: Program with PL/SQL


Identify the characteristics of a stored function.
Know how to create a stored function.
Identify expressions to invoke a function.
List the benefits of using user-defined functions in SQL expressions.
Identify statements to invoke a function from SQL.
List the restrictions on invoking functions from SQL statements.
Drop a stored function.
List the differences between procedures and functions.

62
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Managing Subprograms: Program


with PL/SQL

63
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Contrast between System and Object Privileges


Scope
Differentiate between object and system privileges.

Focused Explanation
Privileges are the rights to perform an action in the database. Privileges can be granted to users, roles,
and to the user group PUBLIC. Privileges are grouped into two categories: system privileges and object
privileges.
System privileges Allow the grantee the right to perform a particular action in all the schemas of the
database.
Note: grantee indicates the user or role to which the specified privilege has been granted.
System privileges are granted to a particular schema. System privileges can also be granted to roles, and
the roles, in turn, granted to the schema. You can classify system privileges into the following:

The type of privilege granted, such as CREATE, ALTER, DROP, or SELECT

The optional word ANY

The kind of database object, such as TABLE, VIEW, or PROCEDURE

System privileges granted using the optional keyword ANY provide the grantee the right to perform the
respective work in the entire database. For example, the privilege CREATE ANY TABLE provides the
grantee the permission to create a table in any of the schemas of the database. This is in contrast to the
system privilege CREATE TABLE, which gives the grantee the power to create a table only in their
schema. Optionally, the system privilege can be granted to the user group PUBLIC. Every database has
the PUBLIC user group. Each user created in the database belongs to the user group PUBLIC. Granting
a system privilege to the PUBLIC user group provides the right to exercise the specified system privilege
to all the existing schemas in the database and to all schemas that will be created in the future. Most
system privilege can optionally be granted using the WITH ADMIN OPTION clause. This clause gives the
grantee the privilege to pass the privilege to other schemas in the database. However, revoking a
system privilege does not have a cascading effect. For example, if user A grants a system privilege
CREATE ANY TABLE WITH ADMIN OPTION to user B and user B in turn grants the privilege to user C,
then revoking the privilege from user B will have no effect on the privilege granted to user C.
Object privileges Allow the grantee to perform an action on a particular database object or program
unit in another schema in the database. For example, to allow user B to be able to perform a query on the
employee table owned by user A, user B must be granted the SELECT object privilege by user A. For
example, to grant user B the SELECT object privilege on the employee table present in user As schema,
user A can issue the following statement:
GRANT SELECT ON employee TO B;

64
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Note: The system administrator can also grant the above privilege to the user B.
Therefore, object privileges must include an object or program unit name in the statement. This allows the
grantee to perform the desired action on the specified object, which resides in a different schema. Each
object privilege can be granted using the WITH GRANT OPTION clause. This clause allows the grantee
to pass the object privilege to other schemas in the database. However, revoking an object privilege has
a cascading effect. For example, if user A grants the SELECT object privilege on the employee table to
user B including the WITH GRANT OPTION clause, and user B in turn grants the privilege to user C, then
revoking the privilege from user B also revokes the privilege granted to user C.

65
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Grant Privileges
Scope
Know how to grant object and system privileges.

Focused Explanation
System privileges can be granted using the GRANT statement. In addition, the ANY keyword can be used
in the GRANT statement to enable the grantee to perform the work in all the schemas in the database.
The following are some of the examples of system privileges being granted to the user SCOTT:

GRANT CREATE TABLE TO SCOTT;

GRANT CREATE ANY TABLE TO SCOTT;

GRANT EXECUTE ANY PROCEDURE TO SCOTT;

GRANT CREATE ANY PROCEDURE TO SCOTT;

Granting the EXECUTE privilege gives the grantee the right to execute program units, such as
procedures, functions, and packaged functions. The privilege CREATE ANY PROCEDURE gives the
grantee the right to create procedures, functions, and packages within any of the schemas, but this
privilege does not give the right to drop or alter the program constructs.
Note: You cannot use the OR REPLACE clause when granting the CREATE ANY PROCEDURE privilege.
Object privileges are granted on objects or program units under your schema. Object privileges are
narrower in scope as compared to system privileges. Object privileges are also granted using the GRANT
statement. For example, if user A wants user B to execute the procedure func_last_name, user A
issues the following statement:
GRANT EXECUTE ON func_last_name TO B;
Object privileges can also be granted to roles. In addition to system privileges, object privileges can also
be granted to the user group PUBLIC, which has the overall effect of granting the privilege to all the
existing schemas in the database and schemas that will be created in the future.
To successfully execute a package containing many functions and procedures, the privilege should be
granted on the entire package and not on individual procedures and functions within the package. For
example, to allow user B to execute the package pack_example, you would use the following statement:
GRANT EXECUTE ON pack_example TO B;

66
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invokers versus Definers Right


Scope
Understand the logic used to execute a procedure, inheriting either the owners or invokers right.

Focused Explanation
Each subprogram performs some sort of action or actions on objects in the database. The program unit
can execute within the permissions of the user that created the program or within the permissions of the
user that invokes the program. Program units that execute with the right of the owner utilize what are
known as definers right, and program units that execute with the right of the schema invoking the
program unit utilize what are known as invokers right.
Definers Rights
Definers rights indicate that the program unit executes within the privileges that the program unit owner
has at the time of execution.
Consider the following example, which demonstrates the definers right:
SQL> conn SCOTT/SCOTT
Connected.
SQL> CREATE OR REPLACE PROCEDURE insert_on_test
2

AS

BEGIN

INSERT INTO SHANE.test VALUES (3,'testing definer rights');

END;

Procedure created.
The procedure is created by user SCOTT. This procedure inserts the data into the table owned by user
SHANE. In the preceding code, the procedure is successfully created because the required INSERT
privilege on table test has been granted to the user SCOTT by SHANE:
SQL> conn SHANE/SHANE
Connected.
SQL> GRANT INSERT ON test TO SCOTT;
Grant succeeded.

67
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Now, the EXECUTE privilege on this procedure is granted by the user SCOTT to the user ANDREW.
SQL> GRANT EXECUTE ON insert_on_test TO ANDREW;
Grant succeeded.
The user ANDREW then executes the procedure:
SQL> connect ANDREW/ANDREW
Connected.
SQL> EXECUTE SCOTT.insert_on_test;
PL/SQL procedure successfully completed.
The user ANDREW does not need any of the INSERT privileges on table test. This is because the
procedure is executing within the owners right. This indicates that the owner of the procedure has been
granted appropriate privileges, and any user or schema to which the owner grants the permission to
execute the procedure will inherit this privilege through a call to this procedure. This method is also called
indirect access. The user ANDREW, however, will not be able to directly insert data in the table.
The following example illustrates that the INSERT privilege on table test has been revoked from the
procedures owner SCOTT:
SQL> conn SHANE/SHANE
Connected.
SQL> REVOKE INSERT ON test FROM SCOTT;
Revoke succeeded.
Now, ANDREW executes the procedure again after the privilege has been revoked from the procedures
owner SCOTT:
SQL> connect ANDREW/ANDREW
Connected.
SQL> EXECUTE SCOTT.insert_on_test;
BEGIN SCOTT.insert_on_test; END;
*
ERROR at line 1:
ORA-06550: line 1, column 14:
PLS-00905: object SCOTT.INSERT_ON_TEST is invalid
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored

68
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above code, the procedure fails to execute because the necessary INSERT privilege has been
revoked from the procedures owner.
Therefore, you need to ensure that you have the following rights when the procedure executes within the
owners right:

To execute the procedure, you must have the EXECUTE privilege granted by the owner or by the
system administrator.

To perform DML activity through the procedure, the owner must have appropriate permissions if
the procedure attempts to perform DML on objects located in other schemas. Other users can
also execute the procedure if they have the EXECUTE privilege granted by the owner or system
administrator.

To manually recompile a procedure, you must have the ALTER ANY PROCEDURE system
privilege.

To create a program unit in any other schema, you must have the CREATE ANY PROCEDURE
system privilege.

Invokers Rights
Invokers rights require the schema executing the procedure to have the appropriate permissions on the
underlying objects that the program references. This is in contrast with definers rights, which require the
owner of the program to have appropriate permissions on the objects that the program references.
Invokers rights are not inherited by default. The default is definers rights. To use the invokers rights, the
keywords AUTHID CURRENT_USER must be used in the CREATE statement. The keywords are included
in the CREATE statement after the parameter list and before the IS or AS keyword. The following example
illustrates the invokers right:
SQL> conn SCOTT/SCOTT
Connected.
SQL> CREATE OR REPLACE PROCEDURE insert_on_test
2 AUTHID CURRENT_USER
3 AS
4 BEGIN
5 INSERT INTO SHANE.test VALUES (3,'testing invoker rights');
6 END;
7 /
Procedure created.

69
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The EXECUTE privilege on the procedure is granted to the user ANDREW. The procedure then executes
according to the rights of the invoker. In this example if ANDREW executes the procedure, ANDREW will
require the INSERT privilege on the test table owned by SHANE.
You can also specify the AUTHID DEFINER clause in the CREATE statement if the procedure is to be
invoked within the owners right.
Note: The definers right is the default mode. Therefore, if you do not specify any AUTHID clause in the
CREATE statement, the definers right is used.
You need to ensure that you have the following rights when the procedure executes within the invokers
right:

To execute the procedure, you must have the EXECUTE privilege granted by the owner or system
administrator.

To perform DML activity through the procedure, the invoker must have appropriate permissions if
the procedure attempts to perform DML on objects located in other schemas.

To manually recompile a procedure, you must have the ALTER ANY PROCEDURE system
privilege.

To create a program unit in any other schema, you must have CREATE ANY PROCEDURE system
privilege.

70
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify Views in the Data Dictionary to Manage Stored Objects


Scope
Query data dictionary views to manage the stored subprograms.

Focused Explanation
The data dictionary views provide relevant information about the subprograms.
The three important data dictionary views that you can use are USER_PROCEDURES, USER_SOURCE, and
USER_OBJECTS.

USER_PROCEDURES: Provides the names of all the program units that invoke a procedure or function.
The important columns in this view are OBJECT_NAME and PROCEDURE_NAME. The OBJECT_NAME
column provides the invoking program, and the PROCEDURE_NAME column provides the invoked
procedure or function. For example, a stand-alone procedure created with the name
insert_on_test will have its name in the OBJECT_NAME column, and the corresponding
PROCEDURE_NAME column will be blank. This is because the procedure is invoked as a stand-alone
unit, and there is no other subprogram unit that this procedure further invokes. If this procedure is
invoked as part of a package named total_records, then the name of the package appears under
the OBJECT_NAME column, and the name of the invoked procedure appears under the
PROCEDURE_NAME column.

USER_SOURCE: Provides the name and the source code for all procedures created by the owner. The
source code appears in the TEXT column, and the name of the procedure appears in the NAME
column.

USER_OBJECTS: Provides important information about the program units.


The important columns of this view are:

CREATED Provides information about the creation date of the subprogram.

LAST_DDL_TIME Provides information about when the subprogram was last compiled.

STATUS Provides information about the status of the subprogram. The valid value for this
column is VALID or INVALID.
Note: A subprogram with the status INVALID needs to be recompiled before executing it
successfully.

Other important information that can be extracted from this view is the type of object, procedure, or
function. This information is provided by the OBJECT_TYPE column.
The above three data dictionary views all provide information about the program units in your
schema.

71
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Managing Subprogram: Program with PL/SQL


Differentiate between object and system privileges.
Know how to grant object and system privileges.
Understand the logic used to execute a procedure, inheriting either the owners or invokers right.
Query data dictionary views to manage the stored subprograms.

72
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Packages: Program with PL/SQL

73
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Usage of the DESCRIBE Command


Scope
Identify the output of the DESCRIBE command.

Focused Explanation
The DESCRIBE command can be used to view the package constructs declared in a package
specification. Executing the DESCRIBE command on a table lists all the columns, including their data
types, precision, and the NOT NULL constraints.
The DESCRIBE command lists the package constructs that are declared in the package specification,
including their name, parameters, parameter modes of the parameters, the data type of the parameters,
and any default values for the parameters. For functions, the return data type is also displayed. The
following example demonstrates the usage of the DESCRIBE command on a package named
pack_public_private:
SQL> DESCRIBE pack_public_private
Argument Name

Type

In/Out Default?

------------------------------ ----------------------- ------ -------FUNCTION func_global RETURNS


p_amount

NUMBER
NUMBER

IN

NUMBER

IN

PROCEDURE proc_global_
p_value

The above DESCRIBE command on the package named pack_public_private, displays two program
constructs declared in the package specification. The first is the function func_global whose return
data type is NUMBER, and the parameter of this function is p_amount. The data type of the parameter is
NUMBER, and the parameter is an IN mode parameter. This parameter does not have a default value. The
second construct is a procedure named proc_global, with the parameter p_value of type NUMBER and
mode IN. This parameter also does not have a default value.
The only constructs that are displayed by the DESCRIBE command are procedures and functions. If the
specification contains cursors, variables, and other global constructs, no information will be displayed for
these constructs by the DESCRIBE command.
Note: The DESCRIBE command is used to display the program constructs in the specification part of the
package only. The DESCRIBE command does not display the package body.

74
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify Package Specification and Package Body


Scope
Identify characteristics of packages. Know when to declare variables in the package body.

Focused Explanation
A package is a PL/SQL construct that allows related objects to be grouped together.
A package is made up of two parts: the package specification and an optional package body. Both the
units are created and stored separately in the database. A package must have a specification. A package
may also have a body, but it is not mandatory. The decision whether a package will have the body or not
depends upon what is written in the specification. However, most packages are created with both a
specification and a body.
A package created with only the specification is compiled and stored successfully in the database as a
valid object, irrespective of the presence or absence of the package body. However, a package body will
not successfully compile without a package specification. This package body will, however, be stored in
the database with its status being INVALID. The status can be viewed by using the USER_OBJECTS data
dictionary view. When the package specification is subsequently created, the package body can be
compiled either manually by using the ALTER PACKAGE...COMPILE statement or by Oracle
automatically, whenever there is a reference to the package construct. The status of the package body is
then marked as VALID, after the specification is created.
The following query on the USER_OBJECTS view fetches two rows one for the package specification
and one for the package body, because the package has a corresponding package body:
SQL> SELECT OBJECT_NAME, OBJECT_TYPE FROM USER_OBJECTS WHERE
OBJECT_TYPE='PACKAGE';
OBJECT_NAME

OBJECT_TYPE

--------------------------------------------------------------PACK_BOOKING

PACKAGE

PACK_BOOKING

PACKAGE BODY.

The declaration of the constructs takes place in the package specification. The package specification can
also include PRAGMAs, which are compiler directives to the PL/SQL compiler. The actual code of the
constructs is defined in the package body. In other words, the package body is used to put the package
specification into action.
The package cannot be called, parameterized, or nested by itself. Only the constructs within the package
can be called, parameterized, or nested. When a construct is invoked within the package, the entire
package is loaded in the memory. This minimizes the disk input/output for subsequent calls made to the
package.

75
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The constructs declared in the package specification are public constructs. These constructs can be
referenced from any Oracle server environment, either from within the package or from outside the
package.
Constructs declared and defined in the package body are known as private constructs. These constructs
are available from inside the package only and cannot be called from outside the package.
The following example demonstrates the local and global variables defined in the package. The package
specification is created first, as shown below:
SQL>

CREATE OR REPLACE PACKAGE my_package

IS

v_global_rate NUMBER := 0.3;

PROCEDURE check_rate (p_empid IN NUMBER);

END my_package;

Package created.
In the above example, the variable v_global_rate is a global variable. This variable can be referenced
by any procedure or constructs within the package or by any Oracle server environment outside the
package. This is also true for procedure check_rate.

76
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The package body is created next, as shown below:


SQL>

CREATE OR REPLACE PACKAGE BODY my_package

IS

v_curr_rate NUMBER;

PROCEDURE log_info (p_username IN VARCHAR2, p_date IN DATE)

IS

BEGIN

INSERT INTO log_table (m_user, m_date) VALUES (p_username, p_date);

END log_info;

PROCEDURE check_rate (p_empid IN NUMBER)

10

IS

11

v_rate NUMBER;

12

BEGIN

13

SELECT curr_rate INTO v_curr_rate FROM emp

14

WHERE emp_id = p_empid;

15

IF v_curr_rate > v_global_rate THEN

16

DBMS_OUTPUT.PUT_LINE ('Current rate is greater');

17

RAISE_APPLICATION_ERROR (-20500,'Cannot proceed');

18

ELSE

19

log_info (user,sysdate);

20

END IF;

21

END check_rate;

22

END my_package;

23

Package body created.

77
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above example, variable v_curr_rate is a private variable and is only available to procedure
check_rate and procedure log_info within the package body. The v_rate variable is local to the
check_rate procedure and can only be referenced from within the check_rate procedure body.
In the above example, procedure log_info is a private procedure because it has not been declared in
the package specification. Therefore, procedure log_info can only be referenced by other constructs
within the package. The global procedure check_rate calls the private procedure log_info from within
the package body. The procedure log_info is not available from outside the package.

78
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Developing a Package
Scope
Identify output of packages. Identify constructs that can be declared within a package. Identify statements
that will assign a value to a variable through a procedure, outside a package.

Focused Explanation
A package can be divided into two parts. The first is the package specification, and the second is the
optional package body. Both the units are stored separately in the database. This allows each unit to be
modified separately. The syntax for creating packages is similar to that of creating stored subprograms.
The syntax for creating the package specification is as follows:
CREATE [OR REPLACE] PACKAGE <package name>
IS | AS
-- Variables, constants, cursors, and other types declarations
-- Subprogram declarations
END <package name>;
The variables declared in the package specification are assigned a null value, by default, if the variables
are not initialized with any value. The values for such variables can be assigned within the package body
or by a program unit outside the package.
The following code creates a package specification with a variable initialized to a null value by default and
then assigns a value to it from outside the package. The important point to note here is that the changed
value remains persistent in the current user session.
The package specification is created first. In the following example, the package specification declares a
global variable v_global. The variable is not assigned any value.
SQL> CREATE OR REPLACE PACKAGE testing
2 AS
3 v_global NUMBER;
4 END testing;
5 /
Package created.

79
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Next, you create a stand-alone procedure. In the following example, the procedure initializes the global
variable to a value of 1:
SQL> CREATE OR REPLACE PROCEDURE assign_values
2 AS
3 v_local NUMBER;
4 BEGIN
5 testing.v_global :=1;
6 v_local := testing.v_global;
7 DBMS_OUTPUT.PUT_LINE (v_local);
8* END;
SQL> /
Procedure created.
The procedure displays the current value of the global variable upon execution. In the following example,
the value of the global variable is displayed in the SQL*Plus environment:
SQL> EXECUTE assign_values;
1
The preceding examples demonstrate how you can assign values to the global variables declared in the
package specification from outside the package. You can also declare these variables in the package
body. Variables declared in the package body can be assigned values from within the package only. You
cannot assign values to the private variables declared in the package body from outside the package.
The package body can also have subprogram declarations, which are not declared in the package
specification. These subprograms are known as private subprograms. The private subprograms are
available from within the package only, and these cannot be called from outside the package.
The syntax for creating the package body is:
CREATE [OR REPLACE] PACKAGE BODY <package name>
IS | AS
-- Private variables, constants, cursors, and other types declarations
-- Subprogram bodies
END <package name>;

80
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Subprograms within a package body can be either public or private. Public subprograms are those that
have been declared in the package specification. The order of defining subprograms in the body is very
important. It is a common practice to declare the private subprograms first and the public subprograms
following the private subprograms.
The constructs that can be grouped within a package include:

Procedures and Functions

Cursors, Variables, and Constants

Composite data types, such as TABLE or RECORD

Exceptions

Comments

PRAGMAs

81
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify Public and Private Constructs


Scope
Identify private procedures or functions in a package. Identify public procedures or functions in a
package.

Focused Explanation
The subprograms and other constructs declared in the package specification are known as the public
constructs. These can be referenced from within the package body and from program units outside the
package.
For example:
SQL> CREATE OR REPLACE PACKAGE pack_public_private
2

AS

g_global NUMBER := 0.01;

PROCEDURE proc_global (p_value IN NUMBER);

FUNCTION func_global (p_amount IN NUMBER)

RETURN NUMBER;

END pack_public_private;

Package created.
In the above example, the variable g_global is a public variable and the proc_global procedure and
the func_global function are public subprograms.

82
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Constructs defined within the package body are known as private constructs. These can be referenced by
other constructs within the same package only. For example:
SQL> CREATE OR REPLACE PACKAGE BODY pack_public_private
2

IS

v_private NUMBER:=1;

FUNCTION func_global (p_amount IN NUMBER)

RETURN NUMBER

IS

BEGIN

RETURN (p_amount * 0.08);

END func_global;

10

PROCEDURE proc_global (p_value IN NUMBER)

11

IS

12

v_firstname VARCHAR2(50);

13

v_lastname VARCHAR2(50);

14

BEGIN

15

SELECT last_name,first_name INTO v_lastname,v_firstname

16

FROM emp WHERE emp_id=p_value;

17

DBMS_OUTPUT.PUT_LINE (v_lastname || ' '|| v_firstname);

18

END proc_global;

19

PROCEDURE proc_private

20

IS

21

BEGIN

22

INSERT INTO temp (temp_id)

23

VALUES (v_private);

24

END proc_private;

25

END pack_public_private;

26

Package body created.


The above package body declares a private variable v_private and assigns a value of 1 to it. This
variable is then referenced in the private procedure proc_private. Both the variable and the procedure
can only be referenced from within the package. The package body also contains the actual code of the
global procedure proc_global and the function func_global. These can be called from within the
package and from outside the package. The variables v_firstname and v_lastname declared in the
procedure proc_global are local to this procedure and cannot be referenced from anywhere outside
this procedure. Other constructs that are part of this package cannot reference the v_firstname and
v_lastname variables.

83
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoking Package Constructs


Scope
Identify various methods for invoking packaged constructs. Identify the privileges required to execute
constructs within a package. Identify the errors encountered when referencing invalid and valid packages.

Focused Explanation
Packages are not directly invoked. Instead, the constructs within the package are executed. The
constructs that can be grouped in the package can be broadly classified into the packaged program units,
such as procedures and functions, and the packaged global units, such as packaged variables,
constants, and cursors.
The rules to invoke packaged program units are the same as rules to invoke stand-alone procedures and
functions. The packaged procedures must be invoked from SQL statements. The packaged functions are
invoked as part of an expression. Parameters can be passed by using named or positional notation. The
name of the package, however, must be prefixed to the packaged program unit name using dot notation,
when referencing the program unit from outside the package. The following example displays different
methods that can be used to invoke the packaged program units:
When called from within the same package, only the name of the construct is required. For example:
CREATE OR REPLACE PACKAGE BODY invoke_constructs
IS
PROCEDURE

proc1 ( p_value IN NUMBER)

IS
BEGIN
IF

proc2 (p_value) THEN

. . .
ELSE
. . .
END IF;
END proc1;
END invoke_constructs;
To invoke the construct from SQL*Plus, you use:
EXECUTE invoke_constructs.proc1 (11);

84
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

To invoke the package construct in a different schema, you use:


EXECUTE scott.invoke_constructs.proc1 (11);
The constructs within the package can also be called by stand-alone procedures and functions in the
database. For example, to invoke the packaged procedure from a stand-alone procedure, the following
syntax is used:
CREATE OR REPLACE <procedure name>
IS
BEGIN
<package name>.<procedure name>;
END <procedure name>;
A stand-alone procedure that invokes the package construct is dependent on the package. Therefore, the
stand-alone procedure is the dependent object, which references the package constructs. If the package
is in an invalid state, the Oracle server will invalidate a dependent procedure that invokes a packaged
construct. For example, the following code creates a package specification that declares a procedure:
SQL>

CREATE OR REPLACE PACKAGE my_package

IS

PROCEDURE proc_del_rows(p_id IN NUMBER);

END my_package;

Package created.
The package body is created next, as shown in the following example:
SQL>

CREATE OR REPLACE PACKAGE BODY my_package

IS

PROCEDURE proc_del_rows (p_id IN NUMBER)

IS

BEGIN

DELETE FROM emp WHERE emp_id=p_id;

END proc_del_rows;

END my_package;

Package body created.

85
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The package procedure proc_del_rows is then referenced in the body of the stand-alone procedure, as
shown in the following example:
SQL>

CREATE OR REPLACE PROCEDURE proc_audit_table

IS

BEGIN

my_package.proc_del_rows(1);

INSERT INTO log_info (user_id,log_date) VALUES (user,sysdate);

END proc_audit_table;

Procedure created.
The stand-alone procedure is then executed in the SQL*Plus environment using the following command:
SQL> EXECUTE proc_audit_table;
PL/SQL procedure successfully completed.
The procedure executes successfully because the referenced package is in a valid state. However, if the
package body is subsequently invalidated, the Oracle server will automatically invalidate the stand-alone
procedure.
The following example adds another parameter in the parameter list of the procedure proc_del_rows in
the package specification:
SQL>

CREATE OR REPLACE PACKAGE my_package

IS

PROCEDURE proc_del_rows(p_id IN NUMBER, p_name IN VARCHAR2);

END my_package;

Package created.
The addition of another parameter in the procedure declaration in the package specification will invalidate
the package body.

86
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

You can view the status of the package by querying the USER_OBJECTS view, as shown below:
SQL> SELECT OBJECT_TYPE,STATUS FROM USER_OBJECTS WHERE
OBJECT_NAME='my_package';
OBJECT_TYPE
-----------

STATUS
------

PACKAGE

VALID

PACKAGE BODY

INVALID

The Oracle server will also invalidate the stand-alone procedure. Oracle will try to recompile the standalone procedure when it is executed the next time. If the recompilation succeeds, the procedure will be
executed; otherwise a run-time error is generated.
In the following example, the stand-alone procedure is executed after the referenced package body is
invalidated:
SQL> EXECUTE proc_audit_table;
BEGIN proc_audit_table; END;
*
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00905: object SCOTT.PROC_AUDIT_TABLE is invalid
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
In the above example, the stand-alone procedure fails to execute because it is in an invalid state. You
must make changes in the code of the package body to successfully compile and execute the procedure.
Invoking packaged global constructs is similar to using stand-alone variables, constants, and cursors.
However, there is one major difference. The declaration of the packaged global constructs is global to the
user sessions.
Note: Only the constructs declared in the package specification are global.

87
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

If you are not the administrator, then you should have either the EXECUTE ANY PROCEDURE system
privilege or EXECUTE ON <package name> object privilege to invoke the package and the package
constructs. You do not need any privilege for the constructs of the package. However, you need to have
appropriate privileges on the objects referenced by the package.
However, if the constructs of the package reference any objects that are not present in your schema, you
need the privilege on those objects to successfully create the package.
For example, assume that the user SCOTT has the necessary privilege, and he executes the following
statement to invoke a packaged procedure owned by user MARTIN:
SQL> EXECUTE MARTIN.my_package.first_procedure;

88
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Declaring a Bodiless Package


Scope
Define a bodiless package. Define the usage of a bodiless package.

Focused Explanation
Bodiless packages are packages created without a corresponding package body. Only the specification
part is created. If a package specification contains only variables, constants, types, exceptions, and a call
specification, the package body is not required.
You can declare public variables and other constructs in the package specification that exist for the
duration of the session. You can create a package specification that does not need a package body. For
example, you can create a package specification that declares the rates for variables that are uniform for
all the users accessing the specification.
The following example creates a package specification with two global variables that are constant for all
user sessions accessing the package:
SQL> CREATE OR REPLACE PACKAGE uniform_global_values
2

AS

service_tax_rate CONSTANT NUMBER :=0.08;

salary_increment_rate CONSTANT NUMBER :=0.25;

END uniform_global_values;

6 /
Package created.
In the above example, the package specification defines the rates for service tax and salary increment,
which are uniform and standard across the application.
The variables declared are global and constant for all user sessions. Users can now code their own
program units and constructs and utilize the global variables in those program units. However, the
variables are declared as constants, and their values cannot be changed when referencing them through
individual program units.

89
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following example demonstrates the usage of global variables in a stand-alone procedure:
SQL> CREATE OR REPLACE PROCEDURE use_global_values (p_empid IN NUMBER)
2

AS

v_salary NUMBER;

v_tax NUMBER;

BEGIN

SELECT salary,tax_rate INTO v_salary,v_tax FROM emp WHERE

emp_id=p_empid;

v_salary := v_salary + (v_salary *

uniform_global_values.salary_increment_rate);

10

v_tax := v_tax + (v_tax * uniform_global_values.service_tax_rate);

11

DBMS_OUTPUT.PUT_LINE (' NEW SALARY IS ' || v_salary);

12

DBMS_OUTPUT.PUT_LINE ('NEW TAX IS ' || v_tax);

13

END use_global_values;

14 /
Procedure Created.
In the above code, the stand-alone procedure use_global_values uses the existing rates for tax and
salary from the database table, and then formulates a new salary and tax using the constant rates
provided via global variables in the package specification.

90
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Drop Package
Scope
Identify the commands for removing the package specification and the package body.

Focused Explanation
To remove the package specification and the package body from the database, you use the following
syntax:
DROP PACKAGE <package_name>;
To remove only the package body from the database, you use the following syntax:
DROP PACKAGE BODY <package_name>;
The DROP PACKAGE statement removes both the package specification and the package body from the
database.
The DROP PACKAGE BODY statement removes only the package body. The package specification
remains intact in the database. The status of the package specification remains VALID even if the
corresponding package body is dropped from the database.
Note: The status of the package can be viewed from the USER_OBJECTS data dictionary view. The
STATUS column displays the current status of the package.

91
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Benefits of Using Packages


Scope
List the benefits of using packages, as compared to using stand-alone constructs.

Focused Explanation
The benefits of using a package include the following:

When a construct in a package is executed, the entire package is loaded into the system global
area. This indicates that the entire code resides in memory, so subsequent calls to the other
constructs of the package are faster. Because the code resides in memory, all users can share it
without the need to read it from disk.

A package groups relatively linked objects together, making it possible to separate one set of
application logic from another.

A package enables the developer to hide certain information. This means that the developer can
create procedures and functions that are included in the package body but not in the package
specification. This allows the package constructs to be made private to the package, and these
constructs are not available for use outside the package.

A package can be used to create global constructs. For example, by creating a bodiless package
you can declare variables that are global to a user session. The values of these global variables
are persistent across the session.

92
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Packages: Program with PL/SQL


Identify the output of the DESCRIBE command.
Identify characteristics of packages.
Know when to declare variables in the package body.
Identify output of packages.
Identify constructs that can be declared within a package.
Identify statements, which will assign a value to a variable through a procedure outside a
package.
Identify private procedures or functions in a package.
Identify public procedures or functions in a package
Identify various methods for invoking packaged constructs.
Identify the privileges required to execute the constructs within a package.
Identify the errors encountered when referencing invalid and valid packages.
Define a bodiless package.
Define the usage of a bodiless package.
Identify the commands for removing the package specification and the package body.
List the benefits of using packages, as compared to using stand-alone constructs.

93
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

More Package Concepts: Program


with PL/SQL

94
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Package Overloading
Scope
Describe the overloading feature of packages.

Focused Explanation
Package overloading allows more than one procedure or function inside the package to use the same
name. This enables the developer to perform the same operation in different ways. Package overloading
is accomplished by creating formal parameters inside the subprogram. These parameters differ in
number, data type, or the order of parameters. This feature can only be used for packaged subprograms.
Stand-alone subprograms cannot be overloaded. Consider a scenario where you want to create an
employee record based on either the employee ID or the employee name. You can accomplish this by
using the package overloading feature. The package specification is created first by declaring two
procedures with the same name:
SQL> CREATE OR REPLACE PACKAGE pack_overloading
2

AS

PROCEDURE create_employee (p_empid IN NUMBER, p_lastname IN VARCHAR2,

p_firstname IN VARCHAR2)

PROCEDURE create_employee (p_lastname IN VARCHAR2,

p_firstname IN VARCHAR2);

7*

END pack_overloading;

SQL> /
Package created.
Next, you create the package body by defining the overloaded procedures:
SQL> CREATE OR REPLACE PACKAGE BODY pack_overloading
2 AS
3 PROCEDURE create_employee (p_empid IN NUMBER,
4 p_lastname IN VARCHAR2, p_firstname IN VARCHAR2)
5 AS
6 BEGIN
7 INSERT INTO emp (emp_id, last_name, first_name) VALUES

95
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

8 (p_empid, p_lastname, p_firstname);


9 END create_employee;
10 PROCEDURE create_employee (p_lastname IN VARCHAR2,
11 p_firstname IN VARCHAR2)
12 AS
13 BEGIN
14 INSERT INTO EMP (emp_id, last_name, first_name) VALUES
15 (empid.nextval, p_lastname, p_firstname);
16 END create_employee;
17 END pack_overloading;
18 /
Package body created.
The above package body defines a procedure create_employee twice with the same name, but with
parameters that differ in number. The create_employee procedure can be executed by passing
parameters for the two procedures in two different ways.
In the first case, the value for employee ID is taken from the user as shown below:
SQL> EXECUTE pack_overloading.create_employee (900,'Waugh','Steve');
PL/SQL procedure successfully completed.
In the second case, employee ID is generated using one of the pre-defined sequences, as shown below:
SQL> EXECUTE pack_overloading.create_employee ('Martin','Joe');
PL/SQL procedure successfully completed.

96
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

You use the package overloading feature when the same operation is performed using arguments of
different types. However, there are some restrictions when using the package overloading feature:

You cannot use two functions with the same name that differ only in their return data type. For
example:
FUNCTION overloading RETURN DATE;
FUNCTION overloading RETURN NUMBER;

You cannot use two procedures with the same name if their parameters differ only in name or
mode. For example:
PROCEDURE overloading (p_parameter IN number);
PROCEDURE overloading (p_parameter OUT number);

You cannot overload two subprograms if their parameters belong to the same family of data
types. For example, the following is invalid because char and varchar2 belong to the same
family of data types:
PROCEDURE overloading (p_parameter IN char);
PROCEDURE overloading (p_parameter IN varchar2);

Note: The above restrictions are valid only if the names of the parameters are identical. If different
parameter names are used, the subprogram can be invoked using named notation for the
parameters. Secondly, the package specification and the package body will be created successfully if
the above features are present. The error will only be detected at run time.

97
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Forward Referencing
Scope
Understand forward declarations within a package.

Focused Explanation
PL/SQL does not allow forward referencing. This indicates that the subprogram must be declared before
it is referenced. The names of the PL/SQL subprograms are identifiers, and the compiler uses these
identifiers to check for the existence of the subprogram when it is referenced in the program unit.
The following example creates a procedure named audit_booking. This procedure has two functions
named get_revenue and get_discount. The function get_revenue calls the function
get_discount:
SQL>

CREATE OR REPLACE PROCEDURE audit_booking

IS

v_bookings NUMBER(3) := 375;

FUNCTION get_revenue

RETURN NUMBER

IS

BEGIN

IF get_discount > 0 THEN

RETURN (v_bookings * (FINANCE.rate));

10

ELSE

11

RETURN v_bookings;

12

END IF;

13

END get_revenue;

14

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

15

RETURN NUMBER

16

IS

17

v_discount NUMBER(3,2);

18

BEGIN

98
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

19

IF (p_guest_id <> 0) THEN

20

RETURN .05;

21

ELSE

22

v_discount := 0.7;

23

RETURN v_discount;

24

END IF;

25

END get_discount;

26

BEGIN

27

INSERT INTO log_info (user_id,log_date) VALUES (user,sysdate);

28

END audit_booking;

29

Warning: Procedure created with compilation errors.


The above procedure results in a compilation error. You can view the compilation errors in the SQL*Plus
environment by issuing the SHOW ERRORS or SHOW ERR command. The following error is displayed for
the above created procedure:
SQL> SHOW ERR
Errors for PROCEDURE AUDIT_BOOKING:
LINE/COL ERROR
-------- ----------------------------------------------------------------8/2

PL/SQL: Statement ignored

8/5

PLS-00313: 'GET_DISCOUNT' not declared in this scope

The call to the function get_discount is illegal because the function get_discount has not been
declared. In other words, the compiler is not aware of the function body and what the function
get_discount is supposed to do.

99
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

PL/SQL provides a method known as forward declaration that can be used in situations where you need
to:

Define subprograms in an alphabetical or a logical order

Group subprograms in a package

Create subprograms that invoke each other

Forward declaration is a method of declaring a subprogram along with its parameter list before
referencing it in another subprogram. The subprogram can then be declared anywhere within the given
program unit.
You can modify the procedure audit_booking in the following manner:
SQL>

CREATE OR REPLACE PROCEDURE audit_booking

IS

v_bookings NUMBER(3) := 375;

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

RETURN NUMBER;

FUNCTION get_revenue

RETURN NUMBER

IS

BEGIN

10

IF get_discount > 0 THEN

11

RETURN (v_bookings * (FINANCE.rate));

12

ELSE

13

RETURN v_bookings;

14

END IF;

15

END get_revenue;

16

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

17

RETURN NUMBER

18

IS

100
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

19

v_discount NUMBER(3,2);

20

BEGIN

21

IF (p_guest_id <> 0) THEN

22

RETURN .05;

23

ELSE

24

v_discount := 0.7;

25

RETURN v_discount;

26

END IF;

27

END get_discount;

28

BEGIN

29

INSERT INTO log_info (user_id,log_date) VALUES (user,sysdate);

30

END audit_booking;

31

Procedure created.
In the above code, the function get_discount is declared, along with its parameter list and the return
data type, before referencing the function in another function get_revenue. In this situation, the
compiler is aware of the functions existence along with its return data type, and no compilation errors are
generated.
Note: The declaration of the program unit must be done before referencing it in another program.

101
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Mutually Referencing Subprograms


Scope
Identify the errors that occur with mutually referencing subprograms.

Focused Explanation
Mutually referencing subprograms are the program constructs that invoke each other either directly or
indirectly. Consider the following example:
SQL>

CREATE OR REPLACE PROCEDURE audit_booking

IS

v_bookings NUMBER(3) := 375;

FUNCTION get_revenue

RETURN NUMBER

IS

BEGIN

IF get_discount > 0 THEN

RETURN (v_bookings * (FINANCE.rate));

10

ELSE

11

RETURN v_bookings;

12

END IF;

13

END get_revenue;

14

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

15

RETURN NUMBER

16

IS

17

v_discount NUMBER(3,2);

18

BEGIN

19

IF (get_revenue <> 0) THEN

20

RETURN .05;

102
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

21

ELSE

22

v_discount := 0.7;

23

RETURN v_discount;

24

END IF;

25

END get_discount;

26

BEGIN

27

INSERT INTO log_info (user_id,log_date) VALUES (user,sysdate);

28

END audit_booking;

29

Warning: Procedure created with compilation errors.


In the above example, the code does not compile because the function get_revenue calls the function
get_discount, and the function get_discount calls the function get_revenue. In this case, the
function get_discount must be declared before referencing it in another function get_revenue and
the function get_revenue must be declared before referencing it in the function get_discount. Both
the situations cannot coexist at the same time. To resolve this situation, you use forward declarations,
which is the method of declaring the subprogram along with its parameters and return type (if the program
unit is a function) before referencing it in another program.
You can declare the function get_discount along with its parameter list and the return data type in the
following manner. This allows you to modify the above code before referencing it in another function
get_revenue:
SQL>

CREATE OR REPLACE PROCEDURE audit_booking

IS

v_bookings NUMBER(3) := 375;

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

RETURN NUMBER;

FUNCTION get_revenue

RETURN NUMBER

IS

BEGIN

103
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

10

IF get_discount > 0 THEN

11

RETURN (v_bookings * (FINANCE.rate));

12

ELSE

13

RETURN v_bookings;

14

END IF;

15

END get_revenue;

16

FUNCTION get_discount (p_guest_id NUMBER DEFAULT 0)

17

RETURN NUMBER

18

IS

19

v_discount NUMBER(3,2);

20

BEGIN

21

IF (get_revenue <> 0) THEN

22

RETURN .05;

23

ELSE

24

v_discount := 0.7;

25

RETURN v_discount;

26

END IF;

27

END get_discount;

28

BEGIN

29

INSERT INTO log_info (user_id,log_date) VALUES (user,sysdate);

30

END audit_booking;

31

Procedure created.

104
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating a One-Time-Only Procedure


Scope
Initialize variables with one-time-only procedures.

Focused Explanation
A one-time-only procedure is declared and defined in the package body. It is executed only once when
the package is invoked for the first time within the user session. A one-time-only procedure is used to
initialize variables, public or private, with values that are automated or when the derivations are too
complex to initialize the variables.
Variables initialized in this manner are not initialized in the declaration because the value is passed by the
one-time procedure.
The following example illustrates this concept:
SQL> CREATE OR REPLACE PACKAGE one_time_procedure
2 AS
3 service_tax NUMBER;
4 END;
5 /
Package created.
The above package specification includes only a single global variable named service_tax. The
package body is created next, which initializes the global variable with a value derived from the
curr_tax column of the taxes table:
SQL> CREATE OR REPLACE PACKAGE BODY one_time_procedure
2 AS
3 BEGIN
4 SELECT curr_tax INTO service_tax FROM taxes WHERE rate_name='TAX';
5 END one_time_procedure;
6 /
Package body created.
In the above example, the value for the global variable service_tax is passed by the one-time
procedure, which begins with the BEGIN keyword. There is no END keyword at the end of the one-timeonly procedure. The END keyword used in the above example denotes the end of the package body.

105
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Persistent State of Packaged Variables and Cursors


Scope
Define a persistent state of a packaged variable and cursors. Identify global variables in a package.
Identify the value of a global variable after a package executes.

Focused Explanation
A global variable, declared in the package specification, retains its value within the user session across
PL/SQL blocks. This is also true for cursors that are declared in the package specification.
For example, the following package specification declares a global variable rate and initializes the
variable to a value of 0.25.
SQL> CREATE OR REPLACE PACKAGE persistent_state
2 AS
3 rate NUMBER := 0.25;
4 END persistent_state;
5 /
Package created.
The concept of persistent state of variables is based on the rule that within a single user session, the
value of the global variable is retained and is carried across the blocks until the session ends. Ending the
session changes the value of the variable back to its original value. For example, the following
anonymous block changes the value of the global variable rate to 0.5:
SQL> BEGIN
2 persistent_state.rate := 0.5;
3* END;
/
PL/SQL procedure successfully completed.
The following anonymous block takes the value of the rate variable, which is assigned by the previous
block, and multiplies it by 15:
SQL> BEGIN
2

persistent_state.rate := persistent_state.rate * 15;

3* END;
/
PL/SQL procedure successfully completed.

106
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following anonymous block prints the value of the global variable rate in the SQL*Plus environment
using the Oracle-supplied package DBMS_OUTPUT:
SQL> BEGIN
2

DBMS_OUTPUT.PUT_LINE

3 ('The value for the global variable rate is ' || persistent_state.rate);


4

END;

5 /
The value for the global variable rate is 7.5
PL/SQL procedure successfully completed.
In the preceding examples, the first block changes the value of the global variable to 0.5. The second
block then uses this value to multiply it by 15 and passes the new value to the variable rate. The new
value is then displayed using the DBMS_OUTPUT package.
Any other session will not be aware of these values. When the global variable is referenced by other
sessions, the variable will have the value 0.25 with which the global variable was initialized.
Ending the user session will reset the variables value to the value with which it was originally initialized in
the package specification.
As with global variables, cursors declared in the package specification can also retain their status across
the user session. Cursors are used to fetch the rows from a table and perform some action on the rows
fetched, one at a time. The persistent state of the cursor refers to the rule that you can open a cursor in
one block, fetch the rows in another block, and close the cursor in yet another block.
You can also fetch rows returned by the cursor in more than one block. For example:
SQL> CREATE OR REPLACE PACKAGE persistent_state
2 AS
3 CURSOR c1 IS SELECT emp_id FROM emp;
4 PROCEDURE proc1_3rows;
5 PROCEDURE proc1_6rows;
6* END persistent_state;
SQL> /
Package created.

107
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The above package specification declares a cursor that fetches the rows from the emp table. Two
procedures are also declared that will return the rows fetched by the cursor in the package body. The
package body is created next as shown below:
SQL>CREATE OR REPLACE PACKAGE BODY persistent_state
2 AS
3 v_empid NUMBER;
4 PROCEDURE proc1_3rows IS
5 BEGIN
6 OPEN c1;
7 LOOP
8 FETCH c1 INTO v_empid;
9 DBMS_OUTPUT.PUT_LINE (ID:' || v_empid);
10 EXIT WHEN c1%ROWCOUNT >=3;
11 END LOOP;
12 END;
13 PROCEDURE proc1_6rows IS
14 BEGIN
15 LOOP
16 FETCH c1 INTO v_empid;
17 DBMS_OUTPUT.PUT_LINE ( 'ID :' || v_empid);
18 EXIT WHEN c1%ROWCOUNT >=6;
19 END LOOP;
20 CLOSE c1;
21 END;
22* END persistent_state;
SQL> /
Package body created.

108
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above example, the first procedure is used to fetch the first three rows, and the second procedure
is used to fetch the next three rows from the emp table. The output of the package is displayed below:
SQL> EXECUTE persistent_state.proc1_3rows;
ID :1
ID :2
ID :3
PL/SQL procedure successfully completed.
Next, the second procedure is invoked, which fetches the next three rows, as displayed below:
SQL> EXECUTE persistent_state.proc1_6rows;
ID :4
ID :5
ID :6
PL/SQL procedure successfully completed.

109
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify Restrictions on Using Packaged Functions in SQL Statements


Scope
Define a side effect in a stored package. Use a packaged function in a query. Identify a packaged
function that can be called from a SELECT statement against a table.

Focused Explanation
To call a stored function from a SQL statement, the Oracle server must guarantee that the function meets
certain restrictions. These restrictions are defined in terms of purity levels. This indicates that the function
is free of certain side effects. Side effects are changes to the database tables or the public packaged
variables.
The function should meet the following requirements when called from SQL statements:

The function should be stored in the database either as a stand-alone unit or as the part of a
package.

The function takes only IN mode parameters.

The formal parameters return only database types, such as NUMBER, CHAR, and VARCHAR2, and
not PL/SQL types, such as BOOLEAN or RECORD.

The return data type of the function should also be recognized by SQL.

The function must not end the current transaction with COMMIT or ROLLBACK, or ROLLBACK to a
savepoint prior to the function execution.

The function must not issue any ALTER SYSTEM or ALTER SESSION commands.

In addition to the above, a function is also subject to the following restrictions:

A function called from a query or a DML statement cannot execute a DML statement or modify
the database tables.

A function called from a query cannot execute a DML statement against the table that is being
queried.

For example, consider the following code, which creates a stand-alone function:
SQL> CREATE OR REPLACE FUNCTION purity_level
2

RETURN NUMBER

IS

BEGIN

UPDATE emp SET emp_id=99 WHERE emp_id=1;

110
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

RETURN NULL;

7* END;
SQL> /
Function created.
The above function is then called in a SQL statement that is querying the emp table, which the function is
also attempting to update:
SQL> SELECT emp_id,purity_level FROM emp;
SELECT emp_id,purity_level FROM emp
*
ERROR at line 1:
ORA-14551: cannot perform a DML operation inside a query
ORA-06512: at "SCOTT.PURITY_LEVEL", line 5
You can also create a function that is part of a package. Packaged functions can be invoked from SQL
statements provided the functions conform to the restrictions defined by the purity level. For example, the
following code creates a packaged function:
SQL> CREATE OR REPLACE PACKAGE basic_salary
2 AS
3 FUNCTION calculate_basic (p_salary IN NUMBER) RETURN NUMBER;
4 END;
5

Package created.
The package body is declared next, as shown below:
SQL> CREATE OR REPLACE PACKAGE BODY basic_salary
2

AS

FUNCTION calculate_basic (p_salary IN NUMBER) RETURN NUMBER

111
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

IS

BEGIN

RETURN (p_salary * 0.10);

END;

END basic_salary;

Package body created.


User-defined functions are called in the same way as the Oracle built-in functions inside a SQL
statement. To call the function created above, you issue the following statement:
SQL> SELECT emp_id, salary, basic_salary.calculate_basic (salary) FROM emp
WHERE salary IS NOT NULL;
EMP_ID

SALARY

----------

----------

BASIC_SALARY.CALCULATE_BASIC (SALARY)
------------------------------------

5000

500

7000

700

1500

150

6000

600

7000

700

8000

800

6 rows selected.

112
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Invoke Packaged Functions with SQL


Scope
Define the purpose of the PRAGMA RESTRICT_REFERENCES compiler directive. Use the PRAGMA
RESTRICT_REFERENCES to allow a function to be used in a GROUP BY clause of a SELECT statement,
after the function is moved to a package.

Focused Explanation
The PRAGMA RESTRICT_REFERENCES is a compiler directive that provides the instructions to the
compiler as to what a function can and cannot do. This compiler directive helps to restrict the functions
processing so that the function conforms to its purity level. In other words, the restriction on a function
that it cannot issue any INSERT, UPDATE, and DELETE statements, when called from within a SELECT
statement, will not stop you from creating a packaged function that violates this rule. The violation will be
detected at run time.
You can also create a package specification without a corresponding body that declares only the headers
of the function, and the package specification will not be able to detect the actual code of the function and
from where the developer wants to reference the function. You can also call the function from an
IF...THEN...ELSE statement. However, if you call the function from a SQL statement, an error will be
generated. The compiler directive provides hints to the compiler to avoid any problems that may occur at
run time. For example:
SQL> CREATE OR REPLACE PACKAGE online_booking
2 IS
3 FUNCTION check_availability RETURN VARCHAR2;
4 PROCEDURE get_reservation (p_id NUMBER);
5 PRAGMA RESTRICT_REFERENCES (check_availability, WNDS, WNPS, RNPS, RNDS);
6* END online_booking;
SQL> /
Package created.
The above code creates a package specification that declares a function and a procedure.

113
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Note: The PRAGMA RESTRICT_REFERENCES compiler directive was used in versions prior to Oracle8i.
The PRAGMA RESTRICT_REFERENCES indicates to the compiler that the function:

Writes No Database State (WNDS) The function cannot issue any INSERT, UPDATE, or
DELETE statements to the database.

Writes No Package State (WNPS) The function does not make any changes to the packaged
variables.

Reads No Package State (RNPS) The function reads no package constructs.

Reads No Database State (RNDS) The function issues no SELECT statements.

When the function is subsequently created, the compiler issues the checks on the function, and in case of
any violation, an error message is generated at compile time.
In Oracle9i, a user-defined function can be successfully compiled, even if it violates any of the purity
rules. However, the PRAGMA RESTRICT_REFERENCES compiler directive is available to perform purity
checks at compile time for packaged functions only. Another reason for using this compiler directive in
packaged functions is that the packages tend to be very lengthy in code, and the developer may not be
aware of the violations in the function body until the package is run. In this scenario, the compiler will
issue an error message when the package is compiled, thus avoiding any run time issues.

114
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the following example, you create a packaged function that can be used in the GROUP BY clause of a
SELECT statement. This package uses the directive so that the function Writes No Database State.
However, the function can be invoked in the SELECT statements because the directive, Reads No
Database State is not included.
SQL> CREATE OR REPLACE PACKAGE my_package
2

IS

FUNCTION my_func (var VARCHAR2) RETURN VARCHAR2;

PRAGMA RESTRICT_REFERENCES (my_func, WNDS);

END my_package;

6 /
Package created.
Next, the package body is created as shown below:
SQL> CREATE OR REPLACE PACKAGE BODY my_package
2

IS

FUNCTION my_func (var VARCHAR2) RETURN VARCHAR2

IS

res VARCHAR2(20);

BEGIN

SELECT LOWER (SUBSTR (var, 1, 1)) ||UPPER (SUBSTR (var, 2))

INTO res FROM dual;

RETURN res;

10

END my_func;

11* END my_package;


12 /
Package body created.

115
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The function is now invoked in the GROUP BY clause of a SELECT statement to list the average salary of
the employees department-wise:
SQL> SELECT my_package.my_func (deptname), avg (salary) from emp
2* GROUP BY my_package.my_func (deptname);
CHECK_GROUPBY.MY_FUNC (DEPTNAME)

AVG (SALARY)

----------------------------------------------------------------------------aCCOUNTS

51000

cLERICAL

4833.33

116
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Use PL/SQL Tables and Records in Packages


Scope
Briefly describe how to use PL/SQL tables and records in packages.

Focused Explanation
PL/SQL composite data types, such as tables and records, can be used in the packages. For example:
SQL> CREATE OR REPLACE PACKAGE my_datatypes
2

IS

TYPE t_emprecord IS RECORD

empid emp.emp_id%TYPE,

lastname emp.last_name%TYPE,

firstname emp.first_name%TYPE);

PROCEDURE proc1 (p_empid IN NUMBER, p_emp_info OUT t_emprecord);

9* END my_datatypes;
SQL> /
Package created.
The above package declares a PL/SQL record, which references the emp table, and a procedure that
accepts two arguments. The first parameter is an IN mode parameter that accepts the value for the
employee identification number. The second parameter is an OUT mode parameter where the data type is
the user-defined RECORD data type.

117
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The package body is created in the following example:


SQL> CREATE OR REPLACE PACKAGE BODY my_datatypes
2 IS
3 PROCEDURE proc1 (p_empid IN NUMBER, p_emp_info OUT t_emprecord)
4 IS
5 BEGIN
6 SELECT emp_id, last_name, first_name
7 INTO p_emp_info FROM emp WHERE emp_id=p_empid;
8 END proc1;
9* END my_datatypes;
SQL> /
Package body created.
The package body includes a SELECT statement that fetches the records into the parameter
p_emp_info, based on the input provided for the parameter p_empid when the procedure is invoked.
To invoke the procedure proc1 from an anonymous PL/SQL block using SQL*Plus, you issue the
following commands:
SQL> DECLARE
2

v_empinfo my_datatypes.t_emprecord;

BEGIN

my_datatypes.proc1 (1, v_empinfo);

DBMS_OUTPUT.PUT_LINE (v_empinfo.firstname ||' '|| v_empinfo.lastname);

END;

7 /
Michael Clark
PL/SQL procedure successfully completed.
The PL/SQL block first declares a variable of type RECORD, defined in the package specification. Next, the
procedure is invoked with two values. The first value is the input for the IN mode parameter, and the
second value is the variable of type RECORD. This variable fetches three records from the emp table:
employee identification number, last name, and first name. The DBMS_OUTPUT package then prints the
values fetched in the v_empinfo variable.
Note: The variables used in the DBMS_OUTPUT package refer to the variables of the RECORD type
t_emprecord.

118
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: More Package Concepts: Program with PL/SQL


Describe the overloading feature of packages.
Understand forward declarations within a package.
Identify the errors that occur with mutually referencing subprograms.
Initialize variables with one-time-only procedures.
Define a persistent state of a packaged variable and a cursor.
Identify global variables in a package.
Identify the value of a global variable after a package executes.
Define a side effect in a stored package.
Use a packaged function in a query.
Identify a packaged function that can be called from a SELECT statement against a table.
Define the purpose of the PRAGMA RESTRICT_REFERENCES compiler directive.
Use the PRAGMA RESTRICT_REFERENCES to allow a function to be used in a GROUP BY clause
of a SELECT statement, after the function is moved to a package.
Briefly describe how to use PL/SQL tables and records in packages.

119
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Oracle-Supplied Packages: Program


with PL/SQL

120
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Benefits of Using the EXECUTE IMMEDIATE Statement over the


DBMS_SQL Package
Scope
Discuss the use of the EXECUTE IMMEDIATE statement over the DBMS_SQL package.

Focused Explanation
You can use PL/SQL to build blocks that use dynamic SQL. Dynamic SQL enables you to write SQL
statements whose actual values are supplied at execution. For example, you can write a procedure that
builds a table whose name is not available until run time. Dynamic SQL allows the usage of DDL, DCL, or
session control language inside a PL/SQL block, which otherwise is not supported. With dynamic SQL,
SQL statements are not embedded in the code, but are passed as character strings that are inputs to or
built by the program. In other words, the SQL statement contains variables or placeholders whose values
can change during run time or can be supplied at run time.
Dynamic SQL can be written using either the DBMS_SQL package (Oracle 8 and earlier) or native dynamic
SQL with the EXECUTE IMMEDIATE statement (Oracle 8i and later).
Native dynamic SQL is an integral part of the SQL language that is built into the language, thus making it
simpler to use and faster than the DBMS_SQL package.
Native dynamic SQL also supports the usage of object types and collections not supported by the
DBMS_SQL package. The EXECUTE IMMEDATE statement is used for queries that fetch a single row. For
queries that return more than one row, you use the OPEN-FOR, FETCH, and CLOSE statements.
Native dynamic SQL supports fetching the rows returned by a query into the PL/SQL records, which
DBMS_SQL does not.
The DBMS_SQL package makes use of procedures and functions in a particular order, making the code
lengthy and complex. Native dynamic SQL allows SQL statements to be used within the PL/SQL code.
This makes native dynamic SQL easy to use.
Native dynamic SQL is also faster than the DBMS_SQL package because it parses, binds, and executes
the statements immediately as compared to the DBMS_SQL package, which requires calls to procedures
and functions.

121
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify the Flow of Execution


Scope
Discuss the Flow of execution of SQL statements.

Focused Explanation
All SQL statements pass through different stages when they are submitted. These stages include:

Parse: Includes checking the statement for syntactic correctness, validating the statement, and
ensuring that the user has necessary privileges to run the statement and the object resolution.
The object resolution determines that all references to the objects in the statement are correct.

Bind: Binds the SQL statements, after successful parsing. This binding process is used when the
statement makes use of bind variables.

Execute: Executes the SQL statement. The Oracle server has all the required information about
the statement at this point.

Fetch: Fetches the rows returned by the query and each successive fetch retrieves another row,
until the last row has been fetched. This stage is required only for the SELECT statements. The
result set fetched may be ordered, if requested, by the query.

Note: Some of the above mentioned stages may be skipped, because DML statements, such as INSERT,
UPDATE, and DELETE, do not involve the fetch stage.

122
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Use the EXECUTE IMMEDIATE Statement


Scope
Describe the usage of the EXECUTE IMMEDIATE statement.

Focused Explanation
The following example demonstrates the usage of the EXECUTE IMMEDIATE statement:
SQL>DECLARE
2 v_sqlstring VARCHAR2(200);
3 v_plsqlblock VARCHAR2(200);
4 BEGIN
5 EXECUTE IMMEDIATE 'CREATE TABLE temp_table (colA VARCHAR2(10))';
6 FOR v_counter IN 1..10 LOOP
7 v_sqlstring := 'INSERT INTO temp_table
8 VALUES (''Row ' || v_counter || ''')';
9 EXECUTE IMMEDIATE v_sqlstring;
10 END LOOP;
11 v_plsqlblock := 'begin
12 FOR v_rec IN (SELECT * FROM temp_table ) LOOP
13 DBMS_OUTPUT.PUT_LINE (v_rec.colA);
14 END LOOP;
15 END;';
16 EXECUTE IMMEDIATE v_plsqlblock;
17 EXECUTE IMMEDIATE 'DROP TABLE temp_table';
18 END;
19

Row 1
Row 2

123
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Row 3
Row 4
Row 5
Row 6
Row 7
Row 8
Row 9
Row 10
PL/SQL procedure successfully completed.
The preceding example illustrates the usage of the EXECUTE IMMEDIATE statement and demonstrates
how it can be used to issue DDL and DML with anonymous PL/SQL blocks.
Note: The trailing semicolon is not used for DML and DDL statements inside the string. For anonymous
blocks, the trailing semicolon is used inside the string.
The following example uses the EXECUTE IMMEDIATE statement from within the procedure as shown
below:
SQL> CREATE OR REPLACE procedure del_rows
2

(p_table_name IN VARCHAR2, p_rows_del OUT NUMBER)

IS

BEGIN

EXECUTE IMMEDIATE 'DELETE FROM ' || p_table_name;

p_rows_del := SQL%ROWCOUNT;

END;

Procedure created.

124
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following command declares a variable in the SQL*Plus environment:


SQL> VARIABLE deleted NUMBER
The following command then executes the procedure as shown below:
SQL> EXECUTE del_rows ('emp',:deleted)
PL/SQL procedure successfully completed.
The following command then prints the value of the variable from the SQL*Plus environment, after
executing the procedure:
SQL> PRINT deleted
DELETED
---------6
The preceding example shows how you can use the EXECUTE IMMEDIATE statement. In the above
example, the del_rows procedure is used to delete the rows from the table, whose name is supplied by
the user when the procedure is invoked.
The other features of the EXECUTE IMMEDIATE statement are discussed below:
1. The EXECUTE IMMEDIATE statement uses an INTO clause for single row queries. The INTO clause
specifies the variable or the record into which the column values are retrieved. For example:
SQL>DECLARE
2 v_sqlquery VARCHAR2(200);
3 v_description emp.first_name%TYPE;
4 BEGIN
5 v_sqlquery := 'SELECT first_name FROM emp WHERE emp_id=1';
6 EXECUTE IMMEDIATE v_sqlquery INTO v_description;
7 DBMS_OUTPUT.PUT_LINE (' The name is ' || v_description);
8 END;
9 /
The name is Michael
PL/SQL procedure successfully completed.

125
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

2. The USING clause holds all the bind variables. For example:
SQL>DECLARE
2 v_sqlstring VARCHAR2(1000);
3 BEGIN
4 v_sqlstring := 'INSERT INTO temp_table (col1,col2)
5 values (:deptid,:deptname)';
6 EXECUTE IMMEDIATE v_sqlstring USING
7 1,'ACCOUNTS';
8 END;
9 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM temp_table;
COL1 COL2
---------- -------------------------------------------------1 ACCOUNTS
At run time, bind arguments replace corresponding placeholders in the string.
3. The EXECUTE IMMEDIATE statement also uses a RETURNING INTO clause. This clause specifies the
variables into which the column values are retrieved. It is used only for DML statements that have a
RETURNING clause.

126
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

4. By default, the procedure executes within the rights of its owner. Consider the following procedure,
which uses the EXECUTE IMMEDIATE statement to drop a table:
SQL>CREATE OR REPLACE PROCEDURE drop_objects
2 (p_object_type IN VARCHAR2, p_object_name IN VARCHAR2) AS
3 BEGIN
4 EXECUTE IMMEDIATE 'DROP ' || p_object_type || ' ' || p_object_name;
5 END;
6 /
Procedure created.
The procedure has been created by the schema SCOTT. Now, SCOTT grants the privilege to EXECUTE the
procedure to MARTIN. MARTIN then executes the procedure, with the following statement:
SQL> EXECUTE SCOTT.drop_table ('TABLE','TEMP_TABLE');
PL/SQL procedure successfully completed.
The procedure, as shown above, drops the table from SCOTTs schema and not from MARTINs schema,
even if MARTIN owns a table known as temp_table.
5. The DML statements submitted with the EXECUTE IMMEDIATE statement are parsed at run time and
not at compilation time. The parser recognizes any SQL statements as strings at compilation time.
Therefore, the errors in the SQL statements are discovered only at execution.

127
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Using Oracle Server-Supplied Packages


Scope
Use the DBMS_PIPE package to send a message. Use the DBMS_DDL.ALTER_COMPILE procedure to
compile the program units. Use the DBMS_JOB package to run jobs at the user-defined times. Use the
DBMS_OUTPUT package. Use the DBMS_SQL package to specify a table name in a procedure.

Focused Explanation
Oracle provides many server-side packages. These Oracle-supplied packages are used in PL/SQL to
perform a variety of tasks.
The DBMS_PIPE package
The DBMS_PIPE package is used to send and receive messages across user sessions in the same
database. The sessions connected to the database can be on different client programs or machines. As
long as the sessions can issue PL/SQL commands to the database, the sessions can communicate with
each other. Messages are sent along a pipe by the sender, by first packing them in the buffer and then
sending the buffer. The reader then receives the buffer and unpacks the buffer to read the messages.
Messages sent using the DBMS_PIPE package are independent of transactions. This indicates that even
if the session that sends the message issues a rollback, the message is not terminated. The DBMS_PIPE
package supports messages of type NUMBER, VARCHAR2, DATE, RAW, and ROWID.
The DBMS_PIPE package does not support user-defined data types. The following example creates a
block from SQL*Plus to send a message:
SQL>DECLARE
2 v_pipename VARCHAR2 (30) := 'mypipe';
3 v_result INTEGER;
4 BEGIN
5 -- FIRST PACK SOME INFORMATION INTO THE PIPE
6 -- WE WILL SEND CURRENT DATE AND A MESSAGE
7 DBMS_PIPE.PACK_MESSAGE (SYSDATE);
8 DBMS_PIPE.PACK_MESSAGE (' HELLO THIS MESSAGE IS SENT FROM THE PIPE');
9 -- NOW WE WILL SEND THE MESSAGE
10 v_result := DBMS_PIPE.SEND_MESSAGE (v_pipename);
11 -- CHECK TO SEE IF THE MESSAGE WAS SENT
12 IF v_result !=0 THEN

128
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

13 DBMS_OUTPUT.PUT_LINE ('Error ' || v_result || 'While sending message');


14 END IF;
15 END;
16

PL/SQL procedure successfully completed.


The above block sends a message consisting of the current date and a string along the pipe mypipe.
The message can be received from the same or a different SQL*Plus session as shown below:
SQL> DECLARE
2

v_pipename VARCHAR2(30) := 'mypipe';

v_result INTEGER;

v_date DATE;

v_string VARCHAR2(100);

BEGIN

-- FIRST RECEIVE THE MESSAGE

-- UNTILL THE MESSAGE IS RECIEVED THIS CALL WILL REMAIN BLOCK

v_result := DBMS_PIPE.RECEIVE_MESSAGE (v_pipename);

10

IF v_result !=0 THEN

11

DBMS_OUTPUT.PUT_LINE ('Error ' || v_result || 'While receiving message');

12

END IF;

13

-- NOW UNPACK THE PARTS OF THE MESSAGE

14

-- IN THE EXACT ORDER IN WHICH THEY WERE SENT

15

DBMS_PIPE.UNPACK_MESSAGE (v_date);

16

DBMS_PIPE.UNPACK_MESSAGE (v_string);

17

-- NOW PRINT THE MESSAGES

18

DBMS_OUTPUT.PUT_LINE (v_date);

129
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

19

DBMS_OUTPUT.PUT_LINE (v_string);

20* END;
21 /
07/04/2004
HELLO THIS MESSAGE IS SENT FROM THE PIPE
PL/SQL procedure successfully completed.

The DBMS_DDL package


The DBMS_DDL package is used to issue certain types of data definition language commands. The
DBMS_DDL package consists of several procedures and functions. The ALTER_COMPILE procedure is
used to issue an ALTER...COMPILE statement to compile the program units from the PL/SQL program
unit. For example, to compile a procedure named my_procedure, you issue the following command:
ALTER PROCEDURE SCOTT.my_procedure COMPILE;
However, this command cannot be issued from within a PL/SQL program unit. To issue the same
statement from a PL/SQL program unit, use DBMS_DDL package instead:
SQL> BEGIN
2

DBMS_DDL.ALTER_COMPILE ('PROCEDURE','SCOTT','my_procedure');

END;

PL/SQL procedure successfully completed.


The ALTER_COMPILE procedure accepts three parameters. The first is the type of program unit you want
to compile, for example PROCEDURE, FUNCTION, PACKAGE, PACKAGE BODY, or TRIGGER, the second is
the schema name, which owns the program unit, and the third is the name of the program unit.

130
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The DBMS_JOB Package


The DBMS_JOB package is used to run jobs at user-defined times. The jobs that are submitted run in the
background allowing you to continue with your work. The DBMS_JOB package consists of several
procedures.

The SUBMIT procedure is the most important procedure in this package. This procedure submits the
PL/SQL code that you want to run at the given time. The following information is provided when the
jobs are submitted using the SUBMIT procedure:
o

JOB: Specifies the identifier of the job that you are submitting. This is an OUT mode
parameter. The job number is required if there is a need to cancel or alter the job.

WHAT: Specifies the PL/SQL code that you need to run at specified times.

NEXT_DATE: Specifies the next date when the job will run. The default value is SYSDATE.

INTERVAL: Specifies the interval between the first execution and subsequent executions of
the job. This is actually a date function. You can also pass values as SYSDATE + 1.

NO_PARSE: Specifies whether the code is to be parsed at the time of submission or when the
code is executed. This is a BOOLEAN value indicating a flag. If set to FALSE (default), then the
code submitted is parsed at the time of submission. If set to TRUE, then parsing takes place
when the job is executed for the first time.

For example, consider the following statements that submit a job to the job queue and then prints the job
number:
SQL>VARIABLE jobno NUMBER
SQL>BEGIN
2 DBMS_JOB.SUBMIT
3(:jobno, 'DBMS_DDL.ALTER_COMPILE (''PROCEDURE'',''SCOTT'',''USE_RAISE'');',
4 SYSDATE,'SYSDATE + 1');
5 END;
6 /
PL/SQL procedure successfully completed.
SQL> PRINT jobno
JOBNO
---------3

131
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The REMOVE procedure is used to eliminate the jobs from the job queue.

For example:
SQL>BEGIN
2 DBMS_JOB.REMOVE (3);
3 END;
4

PL/SQL procedure successfully completed.

The RUN procedure is used to run the jobs once immediately. For example:

SQL> BEGIN
2

DBMS_JOB.RUN(4);

END;

PL/SQL procedure successfully completed.


The RUN procedure uses the identification for the job to execute the job immediately.

The DBMS_OUTPUT Package


The DBMS_OUTPUT package includes the two most widely-used and important procedures: PUT_LINE
and PUT.
PL/SQL does not have any mechanism for input-output. This facility is provided by the DBMS_OUTPUT
package. The package has several procedures, which are used to send the output or receive the input
from the buffer. This package executes only on the server side. The PUT_LINE procedure is used for
debugging code because it is used to print the contents of the variable to the output buffer in SQL*Plus
environment. The output is sent only when the execution of the code is complete. You cannot use the
procedure to display the values incrementally, during the execution of the code.

132
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

If the code is executed from the SQL*Plus environment, the session parameter SET SERVEROUTPUT
should be turned on. This parameter is not a part of the DBMS_OUTPUT package, but is used to turn on
the outputs buffer capability to display information to the screen.

The PUT_LINE procedure accepts one parameter and places it in the output buffer along with the
newline character at the end, so that the line prints as a complete line. The newline character does
not appear in the output. The PUT_LINE procedure is also used in the SQL*Plus environment to
monitor the values of the variables in the program code after the execution of the code is complete.

Consider the following example:


SQL>DECLARE
2 v_variable NUMBER := 0;
3 BEGIN
4 v_variable := v_variable + 1;
5 DBMS_OUTPUT.PUT_LINE ('The Value at Step 1 is : ' || v_variable);
6 v_variable := v_variable + 2;
7 DBMS_OUTPUT.PUT_LINE ('The Value at Step 2 is : ' || v_variable);
8 END;
9 /
The Value at Step 1 is : 1
The Value at Step 2 is : 3
PL/SQL procedure successfully completed.

The PUT procedure appends the text to the current line of the output buffer, but without a new line.

Note: Both the procedures do not directly write to the output console. Instead, the output is written to the
buffer as the program executes, and then to the output console after the program execution is complete.

133
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The UTL_FILE Package


The UTL_FILE package reads and writes to operating system text files. The file that is being read or
written to must reside on the same machine as the server or must be accessible from it. The UTL_FILE
package accesses the files through the directory and filename. For a program to manipulate the file from
the server, the user must have read or write permissions on the directory, and the directory must be
specified using the initialization parameter UTL_FILE_DIR. For example:
UTL_FILE_DIR =C:\UTL_FILE
The init.ora parameter UTL_FILE_DIR can also be initialized by using an * to indicate that all
directories are accessible by the user who invokes the program. The UTL_FILE package runs on both
the client and the server. The client-side security permissions are implemented by checking normal
operating system files permissions.
The UTL_FILE package has several procedures and functions enabling the user to open files, read text
from files, put text into files, and close files.
The following procedures and functions are included in the UTL_FILE package.

FOPEN: Opens the file for read or write activity. The function returns a handle, which is used in
subsequent operations.

PUT_LINE: Writes the strings from the buffer to an open file.

PUTF: Consists of two format specifiers, %s and \n. The format specifier %s is used to substitute a
value into the output string, and \n is used to begin a new line.

FCLOSE: Closes an open file.

The following example demonstrates the usage of the above procedures and functions:
SQL> DECLARE
2

v_filehandle UTL_FILE.FILE_TYPE;

BEGIN

v_filehandle:= UTL_FILE.FOPEN ('C:\UTL_FILE','check.txt','w');

UTL_FILE.PUT_LINE (v_filehandle, 'This is line 1 !');

FOR v_counter IN 2..10 LOOP

UTL_FILE.PUTF (v_filehandle,'This is line %s! \n', v_counter);

END LOOP;

UTL_FILE.FCLOSE (v_filehandle);

10
11

END;
/

PL/SQL procedure successfully completed.

134
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above example, the FOPEN function opens a file named check.txt, present in the directory
C:\UTL_FILE, for a write operation. The function then returns the corresponding handle to the variable
v_filehandle. If the file does not exist, then it is created. If the file exists, it is overwritten.
In the above example, the PUT_LINE procedure writes the string followed by a line terminator to the file
check.txt. The PUTF procedure is then called inside the loop, which substitutes the values by using the
format specifier %s followed by newline. Next, the FCLOSE procedure closes the opened file. After the
block is executed, the file check.txt contains the following:
This is line 1 !
This is line 2 !
This is line 3 !
This is line 4 !
This is line 5 !
This is line 6 !
This is line 7 !
This is line 8 !
This is line 9 !
This is line 10 !

The UTL_TCP Package


The UTL_TCP package enables you to read or write to an operating system text or binary file from a
remote host using TCP/IP. This package is useful for PL/SQL applications that use Internet protocols,
because many Internet applications reside on top of TCP/IP. The UTL_TCP package requires a remote
host, a port, and a local host as arguments to its functions.
The functions that are part of this package include:

OPEN_CONNECTION: Opens a connection with the remote host at the specified port passed as an
argument to the function. The remote host provides the destination service. For example, the remote
host is www.oracle.com and the port is 80, which is the default port number for HTTP. The
function returns a connection of PL/SQL record type.

CLOSE_CONNECTION: Closes the opened TCP/IP connection. The argument contains the details of
the previously opened connection. The CLOSE_ALL_CONNECTIONS function closes all opened
connections.

135
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

READ_BINARY: Receives binary, text, or text line data from the service.

WRITE_BINARY: Sends binary, text, or text line data to the service.

The UTL_TCP package raises exceptions in situations when the buffer is too small, when no data is
available to read from the connection, when a network error occurs, or when incorrect arguments are
passed to its functions.
Note: You can also use the UTL_TCP package to implement any protocol that is built on top of TCP/IP.
The UTL_HTTP Package
The UTL_HTTP package implements the HTTP protocol and allows SQL and PL/SQL to act as a Web
browser, so that it communicates with the HTTP server. The UTL_HTTP package contains two functions,
REQUEST and REQUEST_PIECES. These functions enable access to the data on the Internet, by
retrieving the results of a single HTTP request in one piece or in multiple pieces. Both the functions,
REQUEST and REQUEST_PIECES, accept a URL as input. Based on the input, the URL is used to access
the site and results are returned from that site. The REQUEST function returns up to the first 2000 bytes of
data, and the REQUEST_PIECES function returns a PL/SQL table of 2000-bytes of data from the given
URL.
The package UTL_HTTP requires a proxy parameter if the client is behind a firewall. The package raises
an INIT_FAILED or REQUEST_FAILED exception if the call to the given HTTP fails. The exception
INIT_FAILED is raised when the initialization of the HTTP callout system fails for reasons such as lack
of available memory. The exception REQUEST_FAILED is raised when the call to the specified HTTP
fails due to reasons such as the URL not being specified correctly.
If the URL does not give any response, then an HTML may be returned to the user.
The following example illustrates the usage of the UTL_HTTP package:
SQL>DECLARE
2 v_result UTL_HTTP.HTML_PIECES;
3 v_url VARCHAR2(100) := 'http://www.oracle.com';
4 v_proxy VARCHAR2(100) := 'edu-proxy.us.oracle.com';
5 BEGIN
6 v_result := UTL_HTTP.REQUEST_PIECES (v_url, 100,v_proxy);
7 DBMS_OUTPUT.PUT_LINE (v_result.COUNT || ' pieces were returned');
8 END;
9 /

136
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The preceding example demonstrates the usage of the REQUEST_PIECES function. The function returns
up to 100 pieces of data, each piece returning a maximum of 2000 bytes of data from the URL.
Note: The above example will raise an error if the destination host is unreachable.

137
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Oracle-Supplied Packages: Program with PL/SQL


Discuss the use of the EXECUTE IMMEDIATE statement over the DBMS_SQL package.
Discuss the Flow of execution of SQL statements.
Describe the usage of the EXECUTE IMMEDIATE statement.
Use the DBMS_PIPE package to send a message.
Use the DBMS_DDL.ALTER_COMPILE procedure to compile the program units.
Use the DBMS_JOB package to run jobs at the user-defined times.
Use the DBMS_OUTPUT package.
Use the DBMS_SQL package to specify a table name in a procedure.

138
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Manipulating Large Objects: Program


with PL/SQL

139
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Compare and Contrast LONG and LOB Data Types


Scope
Differentiate between the LONG and the LOB data types.

Focused Explanation
LONG and LOB (Large Objects) are data types used to store large unstructured data. LOB data types
supersede LONG data types from Oracle 8 onwards. Oracle 9i uses the LONG API to convert LONG
columns to LOB columns.
The following points illustrate why it is beneficial to use LOB data types as compared to LONG data types
(LONG and LONG RAW):

Only one LONG column is allowed in a table. However, you can have multiple LOB columns in a
table.

The LONG data type can store up to a maximum of 2 GB of data. However, the LOB data type can
store up to 4 GB of data.

The SELECT query on the LONG column returns data. However, the same query returns the
locator on the LOB columns. If the query is performed within a transaction, the LOB column also
includes the transaction ID and the LOB column cannot be updated from a different transaction.

The LONG columns store the data in the data blocks in line with the rest of the table data. This
means that the data is stored in the blocks, which hosts the rest of the data of the table. However,
if the data is greater than 4000 bytes, the LOB columns store the data in a separate segment in a
separate tablespace.

The LOB columns can be used as object type attributes. However, you cannot use the LONG
columns as object types.

The LOB columns support random access to data. The LONG columns only support sequential
access to data.

140
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create and Maintain LOB Data Types


Scope
Describe the LOB data types. Describe internal LOBs. Use the DBMS_LOB package to manage LOBs.

Focused Explanation
LOB is a data type used to store large unstructured data, such as video clips, text, and images.
Unstructured data, such as multimedia data, is present in the form of operating system files outside the
database.
There are four LOB data types available for use:

BLOB Depicts a Binary Large Object, such as video clips.

CLOB Depicts a Character Large Object.

NCLOB Depicts a multi-byte Large Character Object.

BFILE Depicts a binary file stored outside the database in the form of an operating system file.

The Oracle server groups LOB data types in two classes. The first group is classified on the basis of how
a LOB is interpreted by the Oracle server, for example, the Character LOB or Binary LOB. The second
group deals with the storage aspects of the LOB, such as whether the data is stored internally (CLOB,
NCLOB, and BLOB) inside the database or stored externally (BFILE) outside the database.
A LOB data type has two parts:

Value Contains the data.

Locator Contains the pointer to the location where the LOB value or the data is actually stored.

A LOB column always contains the locator, which points to the location of the LOB value. This is the case
for both internal and external LOBs.
Note: A LOB column does not contain any data. If the LOB is an internal LOB stored inside the database,
then the LOB value is stored in the LOB segment, and the LOB column contains the locator to this
segment. If the LOB is an external LOB stored outside the database, the LOB value is present in the form
of an operating system file, and the LOB column contains the locator pointing to this file.
Internal LOBs are stored inside the database. Examples of internal LOBs include CLOB, NCLOB, and BLOB.
Internal LOBs can be present as any of the following:

A column of the table

A bind or host variable

A PL/SQL variable, parameter, or result

An attribute of a user-defined type

141
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Because internal LOBs are stored inside the database, they provide the following advantages:

Redo Logging and Recovery mechanisms

Concurrency mechanisms

Participation in transactions, and the use of commits and rollbacks

Oracle interprets the BLOB data type as a bitstream, the CLOB data type as a single-byte character
stream, and the NCLOB data type as a multi-byte character stream based on the byte length of the
database national character set.
Note: National character set is used to store data in columns specifically defined as NCHAR,
NCLOB, or NVARCHAR2.
Internal LOBs can be managed by using the DBMS_LOB package. The following summarizes the steps
to manage internal LOBs through the DBMS_LOB package:
1. Create a table, which contains the column(s) of LOB data type.
2. Populate the table with data.
3. Declare and initialize the LOB locator in the program.
4. Use the SELECT FOR UPDATE statement to lock the row containing the LOB into the LOB locator.
5. Manipulate the LOB data type with the DBMS_LOB package and its associated procedures. LOBs
can also be managed through SQL.
6. Use the COMMIT statement to make any changes permanent.
Note: The DBMS_LOB package can also be used to manage external LOBs.

142
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Differentiate Between Internal and External LOBs


Scope
Describe Internal and External LOBs.

Focused Explanation
Internal LOBs are stored inside the database. You can store an internal LOB in a separate segment or in a
separate tablespace. To access the internal LOBs, Oracle provides the DBMS_LOB package, which uses
the locator to access the LOB values.
External LOBs are stored outside the database. For example, the BFILE data type, which is an external
LOB. External LOBs are stored in operating system files.
Note: The BFILE data type is used to access these external files.
If the file is accessed through the DBMS_LOB package, the package uses the locator stored in the column
declared as BFILE to access the external file. A BFILE data type can be GIF, JPEG, MPEG, text, or other
format, such as sound waveforms. BFILEs are read-only, and they cannot participate in transactions that
occur within the database. When the LOB column is deleted in the database, the external file is not
removed. The maximum size allowed for the BFILE data type is 4 GB. Oracle server does not guarantee
the integrity and durability of BFILEs, and any such issues must be addressed at the operating system
level.
Oracle backup and recovery mechanisms support only the BFILEs locators and not the external files.
To access the BFILEs, a database object known as DIRECTORY must be created in the database. A
DIRECTORY is a nonschema object owned by the user SYS and created by the DBA or by the user who
has the CREATE ANY DIRECTORY system privilege. Directory objects have object privileges and allow
the user to grant and revoke the privileges on the DIRECTORY objects.
A DIRECTORY object specifies an alias for a directory on the file system of the server under which the
BFILE data type is located. These aliases provide abstraction from hardcoded path names and provide
flexibility in managing file locations. In addition, privileges on directory objects can be selectively given to
provide secure access to the files on the operating system. The directory alias can be used in PL/SQL to
refer to the underlying operating system files for operations, such as open, close, and read.
Note: The permissions for the actual directory, which is present at the operating system, can be different
from the permissions granted to the DIRECTORY object. The DIRECTORY object only provides easy and
secure access to the file(s) present in the actual directory.

143
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Identify and Manage BFILEs


Scope
Create the DIRECTORY object. Use the BFILE data type, load BFILEs, and use the BFILENAME function.

Focused Explanation
You use the following steps to start working with the BFILE external LOBs:
1. Create an operating system (OS) directory on the server. The Oracle user should have
appropriate privileges to read and write to the directory.
2. Create a table or alter an existing table to include the column of the BFILE data type. For
example:
SQL>

CREATE TABLE employee

emp_id NUMBER,

emp_name VARCHAR2(100),

emp_photo BFILE);

Table created.
3. Create the DIRECTORY object. The syntax to create the directory object is:
CREATE DIRECTORY <directory name> AS <operating system path>;
For example:
SQL> CREATE DIRECTORY my_dir AS 'C:\BFILES';
Directory created.
Note: To create the DIRECTORY object, the user must have the CREATE ANY DIRECTORY
privilege.
4. Grant the READ privilege on the DIRECTORY object to the users. For example:
SQL> GRANT READ ON DIRECTORY my_dir TO SCOTT;
Grant succeeded.
Note: The privilege on the directory objects can also be granted to a role or to PUBLIC.

144
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

5. Insert rows into the table using the BFILENAME function and correlate the OS files with the
corresponding rows. For example:
SQL> INSERT INTO employee (emp_id, emp_name) VALUES (1,'MARTIN');
1 row created.
Note: You can also initialize a BFILE column to NULL and later use the BFILENAME function to
associate it with the OS file. Therefore, you can also use the following INSERT statement:
SQL> INSERT INTO employee VALUES (1,'MARTIN', NULL);
1 row created.
Now, use the UPDATE statement to associate the BFILE column with the OS file:
SQL> UPDATE employee
2 SET emp_photo = BFILENAME ('my_dir','image.bmp');
1 row updated.
The function BFILENAME is used to initialize a BFILE column. The actual signature of the
function is:
FUNCTION BFILENAME (directory_alias IN VARCHAR2, filename IN VARCHAR2)
RETURN BFILE;
Note: After the OS files are associated with the BFILE columns using the DML statements, all
subsequent read operations on the OS files are performed using the DBMS_LOB package.
However, the OS files are accessed in a read-only mode from the database.

145
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

6. Declare and initialize the LOB locator in the program:


SQL> CREATE OR REPLACE PROCEDURE load_bmp_file (p_file_loc IN VARCHAR2)
2

IS

v_file BFILE;

v_filename VARCHAR2(50);

CURSOR c1 IS SELECT emp_name FROM employee FOR UPDATE;

BEGIN

FOR emp_record IN c1 LOOP

v_filename := emp_record.emp_name || '.bmp';

v_file := BFILENAME (p_file_loc,v_filename);

10

DBMS_LOB.FILEOPEN (v_file);

11

UPDATE employee SET emp_photo = v_file WHERE CURRENT OF c1;

12

DBMS_LOB.FILECLOSE (v_file);

13

END LOOP;

14

END;

15

Procedure created.
You execute the procedure to load the BFILE pointer to an image of each employee present in the
directory C:\BFILES. The procedure FILEOPEN of the DBMS_LOB package is used to open the BFILE
for read-only access. The procedure FILECLOSE of the DBMS_LOB package is used to close the already
opened BFILE.

146
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Migrating from LONG to LOB


Scope
Describe various methods of migrating from LONG columns to LOB columns.

Focused Explanation
In Oracle9i, a LONG column in a table can be migrated to a LOB column using the ALTER TABLE
statement. The syntax is:
ALTER TABLE <schema>.<table name> MODIFY <long column name> {CLOB | BLOB |
NCLOB}
When an existing column of the table is migrated from LONG to LOB, the NULL and NOT NULL constraints
are retained.
Note: The NULL and NOT NULL constraints are the only constraints allowed on the LONG columns.
For example, if the table employee has a column named resume whose data type is LONG, then the
column can be migrated to the LOB column using the following statement:
SQL> ALTER TABLE employee MODIFY (resume CLOB);
In Oracle 8i you must use the TO_LOB function to migrate an existing LONG column to a LOB column. The
TO_LOB function can only be used on LONG and LONG RAW columns. This converts them to LOB columns.
The TO_LOB function can only be used in the SELECT list of a subquery in an INSERT statement. Before
using this function, you need to create a LOB column that will receive the value of the LONG column. You
can convert the LONG RAW column to BLOB, and the LONG column to CLOB or NCLOB.
For example, the following statement creates a table named long_table, which contains the LONG
column:
SQL> CREATE TABLE long_table (n NUMBER, long_col LONG);
Table created.

147
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following statement creates a table named lob_table, which contains the LOB column:
SQL> CREATE TABLE lob_table (n NUMBER, lob_col CLOB);
Table created.
The following statement converts LONG values to LOB values:
SQL> INSERT INTO lob_table
2

SELECT n, TO_LOB(long_col) FROM long_table;

1 row created.
The above statement fetches the records from the table long_table and inserts them into the table
lob_table. The values for the LONG column in the long_table are also converted into the LOB column
in the lob_table.
Note: In anticipation of Oracles discontinuing support for LONG data types in future releases, the function
TO_LOB was introduced in Oracle 8i, to migrate data to the LOB data type.

148
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create LOB Columns and Populate Them


Scope
Briefly describe the process to create LOB columns and populate them.

Focused Explanation
The LOB columns are added to an existing table using the SQL data definition language. You can use the
CREATE <table name> statement to create a LOB column in a table at the time of table creation. You
can also add a LOB column after the table is created by using the ALTER <table name> statement. The
LOB values are stored in the LOB segment, and the LOB column in the table only contains the locator to
this segment. You can also define a PL/SQL variable of type LOB, which contains only the locator to the
LOB segment.
The following command adds a LOB column to the table employee:
SQL> ALTER TABLE employee ADD emp_photo BLOB;
Table altered.
The employee table now has the following structure:
SQL> DESCRIBE employee
Name
------------------------

Null?

Type

--------

----

EMP_ID

NUMBER

EMP_NAME

VARCHAR2(100)

EMP_PHOTO

BLOB

The LOB column must be initialized with non-null values before you start writing data to it. Initializing a
LOB column to a non-null value indicates that the LOB column contains the locator, but not the data, that
points to an empty or populated LOB value. You can use the functions EMPTY_BLOB and EMPTY_CLOB in
the INSERT and UPDATE statements, to initialize a null or a not null LOB column to empty. Initializing the
LOB columns to empty using the functions EMPTY_BLOB and EMPTY_CLOB, indicates that the LOB column
in the table contains the locator, but no data that points to the LOB values. Alternatively, you can use the
NULL statement in the INSERT and UPDATE statement to mark the LOB columns as null.
Note: The LOB columns must be initialized to empty by using the functions EMPTY_BLOB or
EMPTY_CLOB, even if you initially set the LOB columns to a null value by using the NULL statement in the
INSERT and UPDATE statements.

149
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

For example, the following SQL statement initializes the LOB column emp_photo of the employee table
to NULL:
SQL> INSERT INTO employee VALUES (1,'SCOTT',NULL);
1 row created.
Even though the LOB column in the table has been marked as null, you must initialize the LOB column to
empty, using the function EMPTY_BLOB, as shown in the following example:
SQL> UPDATE employee SET emp_photo=EMPTY_BLOB()
2

WHERE emp_id=1;

1 row updated.
Alternatively, you can use the function EMPTY_BLOB in the INSERT statement to initialize the LOB column
to empty, as shown in the following example:
SQL> INSERT INTO employee VALUES (1,'SCOTT',EMPTY_BLOB());
1 row created.
The functions EMPTY_BLOB and EMPTY_CLOB are not part of the DBMS_LOB package. These are
available as special PL/SQL-supplied functions available for use in SQL DML statements.
You can also use the functions EMPTY_BLOB and EMPTY_CLOB as default values for the LOB columns
when creating a table, as shown in the following example:
SQL> CREATE TABLE emp_data
2

(emp_id NUMBER(5),

first_name VARCHAR2(100),

last_name VARCHAR2(100),

resume CLOB DEFAULT EMPTY_CLOB(),

photo BLOB DEFAULT EMPTY_BLOB());

Table created.

150
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Perform SQL Operations on LOBs


Scope
Update and select LOB columns by using SQL.

Focused Explanation
You can use the UPDATE statement or the EMPTY_BLOB or EMPTY_CLOB functions to update the values
in a LOB column. You can also use special functions to set the value of the LOB column to a null value,
another LOB value, or to empty. You can also use the bind variables in embedded SQL to set the LOB
values. The value of the bind variable can be null, empty, or populated. These actions do not require the
user to lock the rows explicitly by using the SELECT FOR UPDATE statement. However, if you need to
update only a piece of LOB, then you must lock the rows.
The following example uses an UPDATE statement to set the LOB values of the column resume in the
table emp_data:
SQL> UPDATE emp_data
2

SET resume='Date of Birth, 4 January 1976'

WHERE

emp_id=1;

1 row updated.
Now, the table emp_data has the following structure:
SQL> DESCRIBE emp_data
Name
-------------------------

Null?

Type

--------

----

EMP_ID

NUMBER (5)

FIRST_NAME

VARCHAR2 (100)

LAST_NAME

VARCHAR2 (100)

RESUME

CLOB

PHOTO

BLOB

Note: You can also use the Oracle-supplied package DBMS_LOB to update the LOB columns.

151
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

You can use the SELECT statement to retrieve the data in the CLOB column. For example, the following
statement retrieves the data for the CLOB column in the emp_data table:
SQL> SELECT resume FROM emp_data WHERE emp_id=1;
RESUME
----------------------------------------------------------------------------Date of Birth, 4 January 1976
Note: You can also use the Oracle-supplied package DBMS_LOB to view the CLOB values.
The SELECT statement cannot be used to view the data in BLOB or BFILE columns. You need to use a
tool that displays binary information for a BLOB column, and relevant software for viewing the BFILE
columns.
To delete the row and the associated internal LOB value from the table, you use the DELETE statement.
For example:
SQL> DELETE FROM emp_data WHERE emp_id=1;
1 row deleted.
If you need to remove the LOB locator and still preserve the row, you use the UPDATE statement. The
usage of the NULL statement in the UPDATE statement sets the value of the LOB column to null, whereas
using the function EMPTY_BLOB or EMPTY_CLOB ensures that the column is empty. For example:
SQL> UPDATE emp_data
2

SET resume=EMPTY_CLOB ()

WHERE

emp_id=1;

1 row updated.
A LOB is removed when the row containing the LOB column is deleted, when the table is dropped, or
when the table is truncated.
If the LOB column is a BFILE data type, then the associated file must be removed manually by deleting
the operating system file.
Note: If you need to remove only a part of the internal LOB, then you can use the DBMS_LOB.ERASE
procedure.

152
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the use of Temporary LOBs


Scope
Briefly describe the temporary LOBs.

Focused Explanation
Temporary LOBs are like local variables that provide an interface to enable creation and deletion of LOBs.
You can create BLOBs, CLOBs, or NCLOBs as temporary LOBs.
Temporary LOBs provide the following features:

The data for temporary LOBs is stored in the temporary tablespace and not in the database
tables.

Temporary LOBs are faster because they do not generate any rollback or redo information.

Temporary LOBs are localized to the user session that creates them. No other session can view
the temporary LOBs from other sessions. Temporary LOBs are deleted when the session that
created them ends.

Temporary LOBs are created by using the DBMS_LOB.CREATETEMPORARY procedure.

Temporary LOBs are empty when they are created.

Temporary LOBs do not support the functions EMPTY_BLOB and EMPTY_CLOB.

Temporary LOBs are useful if you want to perform some transformational operation on a LOB, for
example, changing a GIF image to JPEG.
Note: The DBMS_LOB package provides methods to use and manipulate temporary LOBs.

153
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Manipulating Large Objects: Program with PL/SQL


Differentiate between the LONG and the LOB data types.
Describe the LOB data types.
Describe internal LOBs.
Use DBMS_LOB package to manage LOBs.
Describe Internal and External LOBs.
Create the DIRECTORY object.
Use the BFILE data type, load BFILEs, and use the BFILENAME function.
Describe various methods of migrating from LONG columns to LOB columns.
Briefly describe the Oracle-supplied package DBMS_LOB.
Briefly describe the process to create LOB columns and populate them.
Update and select LOB columns by using SQL.
Briefly describe temporary LOBs.

154
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating Database Triggers: Program


with PL/SQL

155
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Different Types of Triggers


Scope
Identify the characteristics of triggers. List the different types of triggers.

Focused Explanation
A trigger is a PL/SQL block or procedure associated with a table, view, schema, or database.
Triggers are like procedures in the sense that they are named PL/SQL blocks with declarative,
executable, and exception-handling sections. Triggers are like packages in the sense that they are stored
as stand-alone objects in the database. On the other hand, procedures are invoked explicitly when a call
is made to them, while triggers are invoked implicitly whenever a particular event occurs in the database.
In addition, triggers do not accept arguments. The triggering event can be a data manipulation language
statement (DML), data definition language statement (DDL), or a system or database event. The act of
executing a trigger is known as firing the trigger.
Triggers can be of the following two types:

Application trigger Fires when a particular event occurs in the application. Application triggers
are developed using Oracle client-side tools, such as Oracle Forms Developer.

Database trigger Fires when a particular event occurs in the database. Database triggers are
developed and stored at the server side where the Oracle database resides.

The events that fire a database trigger can be broadly classified into two classes:

Data event Comprised of DML and DDL statements within the database. A trigger fires when a
particular DML statement, such as INSERT, UPDATE, or DELETE, is executed. In addition, a
trigger fires when a DDL statement, such as CREATE or DROP, is executed.

System event Comprised of actions that are performed either at the schema level or database
level. For example, you can create a trigger that is fired when a user initiates a connection to the
database. The triggering event in this case is LOGON. This trigger can be created either at the
database level or at the schema level. If the trigger is created at the database level, the trigger is
fired for all the users that connect to the database. If the trigger is created at the schema level,
the trigger is fired when the user that created the trigger connects to the database.
Note: Database triggers can also be created on a view. You can create an INSTEAD OF trigger
on a view and use the trigger to perform DML on a view that is inherently non-updatable.

156
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Use of Triggers


Scope
Identify syntax errors in trigger code. Use a BEFORE UPDATE trigger.

Focused Explanation
Triggers are fired when a particular event occurs in the database. The DML events are INSERT, UPDATE,
and DELETE. System events are the actions that occur at the schema or database level, such as LOGON
or LOGOFF. The trigger code specifies the event that fires the trigger. The trigger body should also specify
the timing for the trigger. The trigger timing event can be either BEFORE or AFTER the specified triggering
event.
A BEFORE UPDATE trigger on a table specifies that the trigger needs to be fired before the update activity
on the table. A BEFORE UPDATE trigger is used in situations where you need to ensure integrity rules or
business requirements.
For example, an integrity rule requires that the new value adheres to a specified range. You can also
build a BEFORE UPDATE trigger to ascertain that the user has necessary privileges before actually
performing modifications on the table.
Note: In the above example, the trigger will fire before any update activity is initiated against the table. In
case of violations, the UPDATE statement will fail.
The following example creates a trigger that fires before any INSERT or UPDATE on the salary column
in the employee table and checks the value of the salary against a minimum value of 10,000:
SQL>

CREATE OR REPLACE TRIGGER check_sal

BEFORE INSERT OR UPDATE OF salary ON employee

FOR EACH ROW

BEGIN

IF :NEW.salary < 10000 THEN

RAISE_APPLICATION_ERROR (-20500,'Salary is less than minimum');

END IF;

END;

Trigger created.

157
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following INSERT statement fails because the value supplied for the salary is less than 10,000:
SQL> INSERT INTO employee (emp_id,emp_name,salary) VALUES (1,'SCOTT',2000);
INSERT INTO employee (emp_id,emp_name,salary) VALUES (1,'SCOTT',2000)
*
ERROR at line 1:
ORA-20500: Salary is less than minimum
ORA-06512: at "SCOTT.CHECK_SAL", line 3
ORA-04088: error during execution of trigger 'SCOTT.CHECK_SAL'
The UPDATE statement will also fail if there is an attempt to update the salary column of the employee
table with a value less than the hard-coded minimum value of 10,000. For example:
SQL> UPDATE employee SET salary =1000 WHERE emp_id=1;
UPDATE employee SET salary =1000 WHERE emp_id=1
*
ERROR at line 1:
ORA-20500: Salary is less than minimum
ORA-06512: at "SCOTT.CHECK_SAL", line 3
ORA-04088: error during execution of trigger 'SCOTT.CHECK_SAL'

In the above example, the trigger code should specify the timing and the event. Otherwise, it results in a
syntax error.

158
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following is an example of a code that will generate a syntax error:


SQL> CREATE OR REPLACE TRIGGER check_sal
2

FOR EACH ROW

BEGIN

IF :NEW.salary < 10000 THEN

RAISE_APPLICATION_ERROR (-20500,'Salary is less than minimum');

END IF;

END;

for each row


*
ERROR at line 2:
ORA-04071: missing BEFORE, AFTER or INSTEAD OF keyword

159
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Guidelines for Creating Triggers


Scope
List the guidelines for creating triggers.

Focused Explanation
Some of the situations in which you can create a trigger include:

Enforcing business logic that is too complex to implement because of declarative integrity
constraints

Enabling the auditing feature to capture the changes made and the identity of the user who made
the changes

Automatically signaling other programs that a specified action needs to take place when changes
are made to a table

Maintaining centralized operations, irrespective of the users or application issuing the statements

Capturing information about various events in the database

Triggers should not be created when:

The action that the trigger performs is already built into the Oracle server.

A trigger exists for the specified event.

The logic of the trigger is very lengthy. In such a situation, you should use stored procedures.

Excessive use of triggers can be detrimental in an application. It can lead to complex situations that
make the application more difficult to maintain.

160
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating DML Triggers


Scope
Identify the elements of a trigger. Identify valid timing information for a DML trigger. Create a trigger that
fires when a value is changed. Create an UPDATE ON trigger that inserts a record into an audit table.

Focused Explanation
A trigger that fires when a DML statement is issued in the database is called a DML trigger.
When creating a trigger, you need to consider the following elements, which identify the triggering
statement:

Trigger Timing Determines whether the trigger will fire BEFORE or AFTER the DML statement on
the table. The BEFORE and AFTER timings are not valid for views. You can only create an
INSTEAD OF trigger on a view.

Triggering Event Determines the DML statement that will fire the trigger. The DML statements
are INSERT, UPDATE, and DELETE.

Table Name Specifies the name of the table or view that fires a trigger when the specified
triggering event occurs on it.

Trigger Type Determines whether the trigger will fire for each row affected by the DML
statement or once for the triggering event. The trigger type can be FOR EACH ROW or FOR EACH
STATEMENT.

Trigger Body Specifies the PL/SQL block that determines the action of the trigger.

Triggers can also be used to log information in audit tables whenever a particular DML-triggering event
occurs. You can record any information, such as the name of the user who performed the DML activity on
the table and the date on which the activity was performed. Consider the following example of a DML
trigger, which will fire after the update activity on the table called manager. The trigger will fire only when
there is an update of the salary column of the manager table. This trigger will fire once for the UPDATE
statement.
SQL> CREATE OR REPLACE TRIGGER my_trigger
2

AFTER UPDATE OF salary ON manager

BEGIN

INSERT INTO log_table (m_user, m_date) VALUES (user,sysdate);

END;

Trigger created.

161
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

SQL> UPDATE manager SET salary =10000 WHERE id=1;


1 row updated.
SQL> SELECT * FROM log_table;
M_USER

M_DATE

-------------------------------------------------- --------SCOTT

17-APR-04

If the trigger is designed to fire once for each row affected by the triggering event, such as the UPDATE
statement in the above example, then the number of rows inserted into the log_table will be equal to
the number of rows affected by the WHERE clause in the UPDATE statement. In the above example, the
number of rows inserted into the log_table will equal the number of rows that are affected by the
UPDATE statement.

162
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List the DML Trigger Components


Scope
Identify the components of a DML Trigger.

Focused Explanation
The components of a DML trigger include:

Trigger Timing Possible values are BEFORE and AFTER. A BEFORE trigger fires before the
triggering DML statement on the table. A BEFORE trigger is useful when there is a need to enforce
complex business rules, initialize global variables, derive column values before the triggering
INSERT or UPDATE statement, or to determine whether or not the triggering event should be
allowed to complete. An AFTER trigger fires after the triggering DML event on the table and is
useful when the triggering event should be allowed to complete. An AFTER trigger is also useful
when you need to perform different actions on the same triggering event on which a BEFORE
trigger is already present. An INSTEAD OF trigger is used to perform a DML activity on the
underlying tables of a view that is inherently non-updatable.

Triggering Event Possible values are INSERT, UPDATE, and DELETE. If the triggering event is
UPDATE, you can additionally specify the name of the column(s) to ensure that the trigger fires
only when there is an attempt to modify the specified column(s). The following is an example of
an UPDATE statement:
UPDATE OF <column1, column2, . . .> ON <table name>
Column(s) cannot be specified for INSERT and DELETE triggers because UPDATE and DELETE
statements affect entire rows. You can also specify all three DML events in a single trigger. For
example:
INSERT OR UPDATE OR DELETE ON <table name>
The trigger in the above statement will fire whenever any of the events occur against the table.

Trigger Type Possible values are FOR EACH ROW and FOR EACH STATEMENT. The trigger
built FOR EACH ROW fires for each row affected by the DML statement, and if the DML
statement does not affect any row, the trigger is not executed. This type of trigger is useful when
the trigger action depends upon the data of the rows that are affected. The trigger built FOR
EACH STATEMENT fires once for the triggering event, irrespective of the rows that are affected by
the DML statement. Even if no rows are affected, the statement level trigger fires. This type of
trigger is useful when the trigger does not depend on the data of rows that are affected.
Statement level triggers are the default triggers created if no trigger type is specified when
creating the trigger. By default, an INSTEAD OF trigger is a row trigger. You cannot create a
statement level INSTEAD OF trigger.
Note: You can access the old and new column values of the row that is being processed by the
trigger from within the trigger body by creating a row level trigger.

163
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Trigger Body Determines the action that the trigger should take. The trigger body is a PL/SQL
block. You can issue both SQL and PL/SQL statements from the trigger body. You can also call a
stored procedure or a Java procedure from the trigger body. You can also define PL/SQL
constructs such as variables, cursors, and exceptions, in the trigger body.
Note: The size of the trigger cannot be more than 32K. If the trigger size exceeds the limit, you
can create stand-alone procedures and then call the procedures from within the trigger.

164
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Trigger Firing Sequence Options


Scope
Know the trigger firing sequence.

Focused Explanation
A FOR EACH ROW trigger fires once for each row affected by the triggering event. A FOR EACH
STATEMENT trigger fires once for the entire triggering event. When the triggering event modifies only a
single row, both the FOR EACH ROW and FOR EACH STATEMENT trigger fire only once. This happens
because the SQL statement does not differentiate between the two triggers if only one row is affected.
Triggers that fire in response to a given DML statement, do so in a particular sequence. The sequence of
firing for an INSERT statement on a particular table is as follows:

BEFORE INSERT FOR EACH STATEMENT

BEFORE INSERT FOR EACH ROW

The INSERT Statement

AFTER INSERT FOR EACH ROW

AFTER INSERT FOR EACH STATEMENT

The sequence given above is also followed for other DML statements. The FOR EACH ROW triggers are
fired as close to the DML statements as possible. The FOR EACH STATEMENT triggers are fired first and
last.
There is no restriction on creating multiple triggers for a single event. You can also create two
BEFORE...FOR EACH ROW triggers that fire for a single event. In this scenario, the triggers have
different names but the sequence in which the trigger fires cannot be controlled. Therefore, if the
sequence is important, you should consolidate the two triggers to create a single trigger.
A FOR EACH ROW trigger fires once for each row affected by the triggering DML statement. Therefore, if
the DELETE statement affects 30 rows in the database, any FOR EACH ROW trigger created for the
DELETE statement will fire 30 times. Another important point to note in this regard is that if the FOR EACH
ROW trigger is designed to log information in the audit tables, the number of rows inserted in the audit
table is equivalent to the number of rows affected by the DML statement that fires the trigger. For
example, the following code creates an AFTER UPDATE trigger, which fires for each row affected by the
UPDATE statement on the table manager:
SQL>

CREATE OR REPLACE TRIGGER my_trigger

AFTER UPDATE ON manager

FOR EACH ROW

165
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

BEGIN

INSERT INTO log_table (m_user, m_date) VALUES (user, sysdate);

END;

Trigger created.
The trigger body records the information in the table log_table for each UPDATE statement on the table
manager. The following SELECT query is issued on the audit table log_table before the trigger fires:
SQL> SELECT * FROM log_table;
no rows selected
The DML statement then invokes the trigger:
SQL> UPDATE manager SET salary=10000;
2 rows updated.
The information about the user and the date is then logged into the audit table.
The following query on the audit table fetches two records because the UPDATE statement affected two
rows:
SQL> SELECT * FROM log_table;
M_USER

M_DATE

-------------------------------------------------- --------SCOTT

22-APR-04

SCOTT

22-APR-04

166
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Conditional Predicates
Scope
Describe conditional predicates in a DML trigger.

Focused Explanation
A single trigger can fire for all three DML statements, INSERT, UPDATE, and DELETE. You can also
create a single trigger that fires whenever any of the three events occur on the table. However, there may
be situations when you want to determine exactly which one of the three DML statements caused the
trigger to fire. In these situations, you use conditional predicates. There are three conditional predicates:
INSERTING, UPDATING, and DELETING.
All three predicates are BOOLEAN values indicating a TRUE or FALSE value in response to the triggering
event that fired the trigger. You can then check these BOOLEAN values to control processing within the
trigger body.
For example, the following is a trigger that fires BEFORE the DML statement. This trigger fires on specific
days and at a specific time:
SQL> CREATE OR REPLACE TRIGGER use_predicates
2

BEFORE INSERT OR DELETE ON emp

BEGIN

IF TO_CHAR (sysdate,'DAY') IN ('SAT','SUN') OR

TO_CHAR (sysdate,'HH24') NOT BETWEEN '08' and '18'

THEN

IF INSERTING THEN

8
RAISE_APPLICATION_ERROR (-20502,'you may delete from emp table only
during business hours');
9

END IF;

10

END IF;

11

END;

12

Trigger created.
The above trigger restricts inserts into or deletes from the emp table to certain business hours. If a user
attempts to insert or delete rows on Saturday or Sunday, the user receives the message, the trigger fails,
and the triggering DML statement is rolled back.
Note: RAISE_APPLICATION_ERROR is a server-side built-in procedure that returns an error to the user.

167
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating a Row Level Trigger


Scope
Create a DML row trigger.

Focused Explanation
A row level trigger fires for each row affected by the triggering DML statement. A row level trigger does
not fire if there are no rows affected by the associated triggering DML statement.
The syntax for creating a row level DML trigger is:
CREATE [OR REPLACE] TRIGGER <trigger name>
timing
event1 [or event2 or event3]
ON <table name>
[REFERENCING OLD AS old / NEW AS new]
FOR EACH ROW
[WHEN (condition)]
trigger body
The components of the syntax are explained in the Table 9-1:
Components

Description

trigger name

Indicates the name of the trigger

Timing

Indicates whether the trigger should fire before or after the triggering event. The
possible values are: BEFORE, AFTER, and INSTEAD OF (for views).

event1 [or
event2 or
event3]

Indicates the DML statement on which the trigger fires. The possible values are:
UPDATE, DELETE, and INSERT.

REFERENCING

Indicates that the user can reference the incoming data using the :NEW prefix and
refer to the data already in the database using the :OLD prefix. The default values
are OLD and NEW. The referencing clause enables the user to change the default
prefixes.

FOR EACH ROW

Indicates that the trigger is a row trigger.

WHEN

Specifies the condition for the trigger. This optional clause is valid only for row
triggers.

trigger body

Determines the action that the trigger is supposed to perform.


Table 9-1

168
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

You can create a row level trigger that fires before the triggering DML, to roll back the DML on the table if
the data does not conform to specified requirements.
The following example creates a trigger named check_comm that fires before INSERT or UPDATE on the
emp table. The trigger also uses the qualifier :NEW to reference the new incoming values when the user
attempts to update or insert the table. When an update is performed on the comm column of the emp
table, the value of the comm column is set to 2000, irrespective of any value that the UPDATE statement
tries to define for the comm column. Similarly, when an insert is performed on the emp table, the value of
the comm column in the table is set to 0, irrespective of the value that the INSERT statement tries to
define for the column. The first_name column in the emp table is assigned the name of the Oracle user
who attempts to insert or update the table, irrespective of the value that the INSERT or UPDATE
statements define for this column. The trigger also uses the conditional predicates to determine which
DML caused the trigger to fire:
SQL>

CREATE OR REPLACE TRIGGER check_comm

BEFORE INSERT OR UPDATE OF comm ON emp

FOR EACH ROW

BEGIN

IF UPDATING ('comm')

:NEW.comm :=2000;

:NEW.first_name := USER;

ELSE

IF INSERTING THEN

THEN

10

:NEW.comm :=0;

11

:NEW.first_name :=USER;

12

END IF;

13

END IF;

14

END;

15

Trigger created.

169
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following statement then updates the emp table:


SQL> UPDATE emp SET comm = 1000 WHERE last_name='CLARK';
1 row updated.
The following statement queries the emp table to view the data:
SQL> SELECT first_name, comm FROM emp WHERE last_name='CLARK';
FIRST_NAME

COMM

-------------------------------------------------SCOTT

2000

In the above statements, the comm column is updated with the value of 2000 despite the fact that the
UPDATE statement tried to update the comm column to a value of 1000. The column first_name is
updated to reflect the name of the user, SCOTT, who updated the emp table.
The qualifiers :OLD and :NEW can only be used with row triggers. If you attempt to create a statement
level trigger using the qualifiers, Oracle generates the following error message at compile time:
ORA-01912: ROW keyword expected

170
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Creating a Statement Level Trigger


Scope
Create a statement trigger.

Focused Explanation
A statement level trigger fires once for each triggering event. Even if the DML statement on which the
statement level trigger is defined does not affect any rows, the statement level trigger will fire. This is in
contrast with row level triggers, which do not fire if the DML statement does not affect any rows.
A row level trigger can be converted to a statement level trigger by removing the FOR EACH ROW clause.
Note: If no clause is specified when the trigger is created, the trigger is assumed to have the FOR EACH
STATEMENT clause by default.
The syntax for creating statement level triggers is similar to that of creating row level triggers, except for
the use of the FOR EACH ROW clause.
The following example creates a statement level trigger that allows modifications only during certain
business hours. The trigger fires before the UPDATE, DELETE, and INSERT statements on the emp table:
SQL> CREATE OR REPLACE TRIGGER restrict_dml
2

BEFORE INSERT OR UPDATE OR DELETE ON emp

BEGIN

IF TO_CHAR (sysdate,'HH24:MI') NOT BETWEEN '08:00' and '18:00'

THEN

RAISE_APPLICATION_ERROR (-20500,'DML

RESTRICTED ON EMP TABLE DURING CERTAIN HOURS');

END IF;

END;

10

Trigger created.

171
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The trigger will disallow DML activity on the emp table during certain hours. An attempt to perform DML
during hours that fall within the range of the trigger will cause the trigger to fire and roll back the DML
triggering statement:
SQL> UPDATE emp SET comm = 1000 WHERE last_name='clark';
UPDATE emp SET comm = 1000 WHERE last_name='clark'
*
ERROR at line 1:
ORA-20500: DML restricted on EMP table during certain hours
ORA-06512: at "SCOTT.RESTRICT_DML", line 4
ORA-04088: error during execution of trigger 'SCOTT.RESTRICT_DML'

172
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Using :OLD and :NEW Qualifiers


Scope
Use :OLD and :NEW qualifiers in DML triggers.

Focused Explanation
You can use the :OLD and :NEW qualifiers in a row level trigger to reference the old and new values of a
column, respectively. The old and new values refer to values before and after the data change by the
DML statement. Different DML statements have different values for the qualifiers. Table 9-2 shows the
different values for the DML statements:

DML statement

Old Value

New Value

INSERT

NULL

Inserted value

UPDATE

Value before the update

Value after the update

DELETE

Value before the delete

NULL

Table 9-2
You should consider the following points when you use qualifiers in a trigger:

Qualifiers can only be used in row triggers.

Qualifiers should be prefixed with a colon (:) in each SQL or PL/SQL statement.

Qualifiers should not be prefixed with a colon (:) when the qualifiers are used in the WHEN clause.

The following example uses the qualifiers in a trigger that fires after an update on the emp table. The
trigger then records the audit information and the old and new values of the column that the update
statement changes in a table:
SQL>

CREATE OR REPLACE TRIGGER audit_emp

AFTER UPDATE ON emp

FOR EACH ROW

BEGIN

INSERT INTO aud_table

(username,time_stamp,empid,old_name,new_name,old_salary,new_salary)

173
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

7
VALUES
(user,sysdate,:OLD.emp_id,:OLD.first_name,:NEW.first_name,:OLD.salary,:NEW.sal
ary);
8

END;

Trigger created.
The following statement queries the emp table:
SQL> SELECT first_name FROM emp WHERE last_name ='warne';
FIRST_NAME
----------------------------------------------------------------------------shane
The UPDATE statement is executed next causing the trigger audit_emp to fire and the old and new
values to be recorded in the audit table:
SQL>

UPDATE emp SET first_name='steve' WHERE last_name='warne';

1 row updated.
The following information is recorded in the table aud_table:
SQL> SELECT * FROM aud_table;
USERNAME

TIME_STAMP

-------

-----------

SCOTT

23-APR-04

EMPID

OLD_NAME

NEW_NAME

OLD_SALARY

NEW_SALARY

------- -------- ---------- ---------- ---------2

shane

steve

174
www.selftestsoftware.com

7000

7000

Oracle 1Z0-147 Study Guide

Create an INSTEAD OF Trigger


Scope
Create an INSTEAD OF trigger on a view.

Focused Explanation
INSTEAD OF triggers are created on views to allow DML statements on a non-updatable view. Note that
the view is non-updatable if it contains any of the following:

A table join of two or more tables

The GROUP BY clause

The START WITH ...CONNECT BY clause

Any aggregate functions

The DISTINCT function

Set operations

Columns based on expressions such as concatenation and pseudocolumns

The INSTEAD OF trigger fires instead of the triggering statement and performs the DML activity on the
underlying tables of the view. To understand this, assume that a view is created based on the join of two
tables. This view is inherently not updatable, which means that you cannot issue a DML statement on the
view to modify the base tables. An INSTEAD OF trigger provides this functionality by allowing the DML
statements on the view. An INSTEAD OF trigger fires in place of the DML statement and updates the
underlying tables of the view.
Some of the points to remember when creating INSTEAD OF triggers are:

INSTEAD OF triggers can only be created on views.

INSTEAD OF triggers must always be FOR EACH ROW.

If the view is updatable and has an INSTEAD OF trigger, the trigger takes precedence.

The timing event is not applicable for INSTEAD OF triggers. An INSTEAD OF trigger is based on
a view, and BEFORE and AFTER timing events are not applicable to it.

An INSTEAD OF trigger can fire for all three DML statements, INSERT, DELETE, and UPDATE [
OF column].

175
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

For example, consider the following two tables:


SQL> CREATE TABLE employee
2

emp_id NUMBER,

emp_name VARCHAR2(50),

dept_id NUMBER,

CONSTRAINT pk_empolyee PRIMARY KEY (emp_id));

Table created.
SQL>

CREATE TABLE dept

dept_id NUMBER,

dept_name VARCHAR2(50),

CONSTRAINT pk_dept PRIMARY KEY (dept_id));

Table created.
The following view is created based on these two tables:
SQL> CREATE VIEW employee_dept
2

AS

SELECT e.emp_id,e.emp_name,d.dept_name

FROM employee e, dept d

WHERE e.dept_id=d.dept_id;

View created.
This view is created based on columns from the two tables. This view, however, does not contain the
primary key column of the dept table. According to the rules of the database, this view will not accept
any INSERT statements because it is not possible to provide the value for the primary key column of
the dept table. This functionality can be provided to this view by the INSTEAD OF trigger.

176
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following example creates an INSTEAD OF trigger on the employee_dept view:


SQL>

CREATE OR REPLACE TRIGGER trig_employee_dept

INSTEAD OF INSERT ON employee_dept

BEGIN

INSERT INTO dept VALUES (seq_deptid.nextval,:NEW.dept_name);

INSERT INTO employee VALUES

6
7
8

(:NEW.emp_id,:NEW.emp_name,seq_deptid.currval);
END;
/

Trigger created.
Next, the INSERT statement is executed on the view:
SQL> INSERT INTO employee_dept VALUES (1,'craig','accounts');
1 row created.
The INSTEAD OF trigger fires on this view in the background. This causes the view to accept the
INSERT statement. The values provided by the INSERT statement are accessed using the :NEW
qualifier in the trigger to insert the values into the two tables, employee and dept. The value for the
dept_id column is generated using the sequence seq_deptid.

177
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Difference Between Database Triggers and Stored Procedures


Scope
List the differences between database triggers and stored procedures.

Focused Explanation
Table 9-3 describes the differences between database triggers and stored procedures:

Triggers

Procedures

Created with the CREATE TRIGGER statement

Created with the CREATE PROCEDURE statement

Source code stored in the USER_TRIGGERS data


dictionary view

Source code stored in the USER_SOURCE data


dictionary view

Invoked implicitly when the triggering event


occurs

Invoked explicitly by calling them

Transaction control statements, such as COMMIT,


ROLLBACK, and SAVEPOINT, not allowed inside
the trigger body

Transaction control statements allowed inside the


procedure body

Table 9-3
The CREATE TRIGGER statement creates a database trigger and stores the code in the data dictionary,
even if the trigger code contains compilation errors.
Inside the trigger body, it is possible to call a procedure that issues the transaction control statements.
However, this programming practice is not recommended because of the possible side effects to
transactions.

178
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe the Trigger Execution Model


Scope
Briefly describe the trigger execution model.

Focused Explanation
You can create up to four types of triggers for a single DML statement. For example, there can be a
trigger on a table, which fires before the DML statement for each row and another trigger on the same
table, which fires before the DML statement for each statement.
The triggers fire according to an execution plan. The execution plan is as follows:

All BEFORE STATEMENT level triggers are fired.

All BEFORE ROW triggers are fired.

All AFTER ROW triggers are fired.

The DML statement is executed and integrity constraint checking is performed.

All AFTER STATEMENT triggers are fired.

By default, triggers check the integrity constraints for any violation. This ensures that integrity constraints
are not compromised by the triggers. For example, consider the following two tables:
SQL> CREATE TABLE child
2

child_id NUMBER,

child_name VARCHAR2(50),

CONSTRAINT pk_child PRIMARY KEY (child_id));

Table created.
SQL>

CREATE TABLE master

master_id NUMBER,

master_name VARCHAR2(50),

child_id NUMBER,

CONSTRAINT pk_master PRIMARY KEY (master_id),

CONSTRAINT fk_master FOREIGN KEY (child_id) REFERENCING child(child_id));

Table created.

179
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The master table has a foreign key relationship with the child table. The following INSERT statement
fails because records are not present in the child table:
SQL> INSERT INTO master VALUES (1,'primary',10);
INSERT INTO master VALUES (1,'primary',10)
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK_MASTER) violated - parent key not
found
A trigger check_cons is created, which inserts the records in the child table:
SQL> CREATE OR REPLACE TRIGGER check_cons
2

BEFORE INSERT ON master

FOR EACH ROW

BEGIN

INSERT INTO child VALUES (10,'secondary');

END;

Trigger created.
The INSERT statement is issued again. This causes the trigger to fire. Next, the foreign key constraint is
checked. This time, however, the INSERT statement is successful because the trigger check_cons
inserts the records into the child table, and there is no exception:
SQL> INSERT INTO master VALUES (1,'primary',10);
1 row created.
Note: A trigger can also fire another trigger (cascading triggers).

180
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Managing Triggers
Scope
Understand how to disable, enable, and compile triggers.

Focused Explanation
When a trigger is created, it is enabled by default. Triggers can also be disabled. For example, to avoid
integrity checks or improve performance when loading data from utilities, such as SQL*Loader, you can
disable a trigger. You may also need to disable the trigger because the object that the trigger refers to is
unavailable because of a failed network connection or disk crash.
Triggers that are disabled can be enabled later. Disabling the trigger maintains the trigger in the
database. The syntax for enabling or disabling the trigger is:
ALTER TRIGGER <trigger name> DISABLE | ENABLE
The syntax to disable or re-enable all triggers on a particular table is:
ALTER TABLE <table name> DISABLE | ENABLE ALL TRIGGERS
To compile the trigger that is invalid, you use the following syntax:
ALTER TRIGGER <trigger name> COMPILE
Note: The trigger will recompile if the ALTER TRIGGER...COMPILE statement is issued, irrespective of
the validity or invalidity of the trigger.

181
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Dropping Triggers
Scope
Understand how to remove triggers from a database.

Focused Explanation
To permanently remove a trigger from a database, you can use the DROP TRIGGER statement. The
syntax of this statement is:
DROP TRIGGER <trigger name>;
For example:
SQL> DROP TRIGGER check_cons;
Trigger dropped.
Note: When a table is dropped from a database, all its associated triggers are automatically dropped from
the database. This is in contrast to procedures, which are marked INVALID when the tables that they
reference are dropped from the database.

182
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Creating Database Triggers: Program with PL/SQL


Identify the characteristics of triggers.
List the different types of triggers.
Identify syntax errors in trigger code.
Use a BEFORE UPDATE trigger.
List the guidelines for creating triggers.
Identify the elements of a trigger.
Identify valid timing information for a DML trigger.
Create a trigger that fires when a value is changed.
Create an UPDATE ON trigger that inserts a record in an audit table.
Identify the components of a DML trigger.
Know the trigger firing sequence.
Describe conditional predicates in a DML trigger.
Create a DML row trigger.
Create a statement trigger.
Use :OLD and :NEW qualifiers in DML triggers.
Create an INSTEAD OF trigger on views.
List the differences between database triggers and stored procedures.
Briefly describe the trigger execution model.
Understand how to disable, enable, and compile triggers.
Understand how to remove triggers from a database.

183
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

More Trigger Concepts: Program with


PL/SQL

184
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Define a Database Trigger


Scope
Identify characteristics of database triggers. Identify when to use database triggers.

Focused Explanation
Database triggers are triggers stored in the database. Database triggers fire on DML events, DDL events,
and system events. Database triggers created on DDL events and system events are not built on a table
or view, but are designed to fire on DDL events, such as CREATE, ALTER, or DROP, for a given schema or
on system events, such as shutting down or starting up the database. Triggers created on system events
fire at the database level or the schema level. Triggers that are created at the database level fire for all
the users, and triggers that are created at the schema level fire only when the triggering event involves
that schema. For example, a database trigger can be created that fires before shutting down the
database. Triggers created on DDL (Data Definition Language) events can fire either at the database or
the schema level.
The triggering events that cause the triggers created on system events to fire can be listed as:

A data definition statement on an object

Users logging on or off the database

Database shutdown or startup

Server errors

Note: Triggers created at the database level fire for all the users (schemas). Triggers created at the
schema level fire for the schema in which the trigger was created, in other words, the triggers owner.
The following are the characteristics of database triggers:

A database trigger is a PL/SQL block or a Java procedure. A database trigger can also be
developed using object-oriented languages, such as C.

Database triggers are invoked implicitly when the specified event occurs in the database.

Database triggers can fire when a DML statement is issued against a table.

Database triggers can fire when a DDL event or a system event, such as logging on, occurs.

Database triggers are associated either at the schema or database level.

Database triggers are stored in the database, and as such they fire regardless of the user or the
application accessing the database. Database triggers can be used to perform an action whenever a
specific event occurs in the database.

185
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List How Database Triggers are Used


Scope
Identify events that cause database triggers to fire. Identify the timings that can be specified for a
database trigger.

Focused Explanation
Database triggers are stored in the database. Database triggers can fire either ON DATABASE, ON
SCHEMA, or at the table or view. Database triggers can fire BEFORE or AFTER the triggering event. The
events on which the database triggers fire include:

Shutting down or starting up of the database. You can create a database trigger for starting up or
shutting down the database that fires only ON DATABASE level. You cannot create a schema
level trigger for starting up or shutting down events.

A specific user (or any user) logging on or off the database. You cannot create a BEFORE LOGON
or AFTER LOGOFF trigger.

Whenever a DML statement is issued against a table or an updatable view. The triggers for DML
statements are built on specific tables and views, and the triggers are invoked only when the
triggering event occurs on the specified table or view.

Whenever a DDL statement on an object is issued, both schema level and database level triggers
can be created for DDL statements. Some of the examples of DDL statements are: CREATE,
ALTER, DROP, GRANT, and REVOKE.

When a specific error or any other error occurs.

Note: Although triggers can fire for CREATE statements, triggers will not fire for the CREATE
CONTROLFILE and CREATE DATABASE statements.

186
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List Guidelines for Designing Triggers


Scope
Identify DDL events for which you can create a trigger. Identify objects on which a DDL trigger can be
built.

Focused Explanation
Database triggers can also be created on data definition statements. You can create a database trigger
that fires when a CREATE statement is issued in the database or at the schema level. You can also create
a trigger that fires when an object is dropped from the database. Triggers created on ALTER statements
fire when an object is modified in the database.
The following list provides the objects, which when created, cause a DDL trigger to fire:

INDEX

CLUSTER

PACKAGE

FUNCTION

TABLE

PROCEDURE

ROLE

SEQUENCE

SYNONYM

TABLESPACE

TRIGGER

TYPE

VIEW

USER

187
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following GRANT statement is required to access the trigger on a table from a different schema, other
than the one that created the trigger:
GRANT SELECT, INSERT, UPDATE, DELETE ON <table name>;

For example, a user creates a trigger that fires for the DML activity on table X. If other users of the
database try to access the table X, they will require the above GRANT statement, granted on table X to
invoke the trigger in their schema.

188
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Create a DML Trigger


Scope
Identify the statements that can be included in a trigger body.

Focused Explanation
Database triggers are similar to named program units and include a declarative, an executable, and an
exception-handling section. The declarative section includes information about the trigger, such as the
trigger name, timing, trigger level, and the declaration of variables. The executable section forms the body
of the trigger. The trigger can also optionally include an exception-handling section. The executable
section of the trigger, which fires on the triggering data manipulation statement, cannot include any data
definition statements. For example, you can create a trigger that issues a SELECT, INSERT, UPDATE, or
DELETE statement on a table, but you cannot include DDL statements, such as GRANT, REVOKE, DROP,
and ALTER. The trigger body also cannot include any transaction control statements, such as COMMIT,
ROLLBACK, or SAVEPOINT.
Note: The PL/SQL parser will not issue any errors if the trigger body includes any transaction control
statements. It is only during the execution of the trigger that the error will be generated.
For example, the following code creates a trigger, which includes a transaction control statement COMMIT:
SQL>

CREATE OR REPLACE TRIGGER my_test

AFTER INSERT ON test

BEGIN

COMMIT;

END my_test;

Trigger created.
An INSERT statement on the table test causes the trigger to fire, as shown below:
SQL> INSERT INTO test (test_no,test_desc) VALUES (11,'CHECKING TCL
STATEMENTS');
INSERT INTO test (test_no,test_desc) VALUES (11,'CHECKING TCL STATEMENTS')
*
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at "SCOTT.MY_TEST", line 2
ORA-04088: error during execution of trigger 'SCOTT.MY_TEST'

189
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above example, the trigger my_test fails because of the presence of the transaction control
statement. The triggering statement is also rolled back.
A trigger body cannot include any DDL statements. The PL/SQL engine will issue a compilation error, if
the trigger body includes any DDL statements. For example:
SQL>

CREATE OR REPLACE TRIGGER my_test

AFTER INSERT ON test

BEGIN

DROP TABLE employee;

END my_test;

Warning: Trigger created with compilation errors.


To view the compilation errors, you issue the SHOW ERRORS or SHOW ERR command at the SQL*Plus
environment:
SQL> SHOW ERRORS
Errors for TRIGGER MY_TEST:
LINE/COL ERROR
-------- ----------------------------------------------------------------2/2

PLS-00103: Encountered the symbol "DROP" when expecting one of


the following:

Note: If you need to include a DDL statement inside the trigger body, you should use the EXECUTE
IMMEDIATE statement, the DBMS_SQL Oracle-supplied package, or call a stored procedure from within
the trigger body.

190
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List the DML Trigger Components


Scope
Identify the rules for using CALL statements.

Focused Explanation
You can invoke a PL/SQL block or a Java procedure from within the trigger. You can also invoke a
procedure developed using object-oriented languages, such as C. This functionality allows the users to
call the procedure from the trigger body instead of writing the complete code inside the trigger. A CALL
statement is used to invoke a stored procedure. The syntax is:
CREATE [OR REPLACE] TRIGGER <trigger name>
timing
event1 [or event2 or event3]
ON <table name>
[REFERENCING OLD AS old | NEW AS new]
[FOR EACH ROW]
[WHEN condition]
CALL <procedure name>
For example:
CREATE OR REPLACE TRIGGER trig_emp
BEFORE INSERT ON EMP
CALL check_sal
Note: There is no semicolon at the end of the CALL statement.
The CALL statement invokes the check_sal procedure, which is used to perform checking on the salary,
which is inserted by the triggering DML statement.

191
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Mutating Tables
Scope
Identify the cause of mutating tables.

Focused Explanation
A mutating table is a table against which a data manipulation statement has been issued and the
corresponding trigger on the DML statement is reading from the same table, at the same time. For
example, you create a trigger named check_salary on the table employee, which guarantees that
whenever an INSERT or UPDATE is issued on the table, the salary conforms to the specified limits. This
trigger issues a SELECT statement on the employee table. Now, an UPDATE statement is issued against
the table employee, which fires the trigger causing the table employee to become a mutating table. This
is because the trigger is trying to read from the table, at the same time the table is being modified.
The following example illustrates the concept of mutating tables:
SQL> CREATE OR REPLACE TRIGGER check_salary
2

BEFORE INSERT OR UPDATE OF salary ON employee

FOR EACH ROW

DECLARE

v_min_salary employee.salary%TYPE;

v_max_salary employee.salary%TYPE;

BEGIN

SELECT MIN(salary), MAX(salary) INTO v_min_salary,v_max_salary

FROM employee;

10

IF :NEW.salary < v_min_salary OR

11

:NEW.SALARY > v_max_salary THEN

12

RAISE_APPLICATION_ERROR (-20500,'SALARY IS OUT OF RANGE');

13

END IF;

14

END;

15

Trigger created.

192
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

In the above code, the trigger is created on the table employee, and also issues a SELECT statement
against the table. Now, an UPDATE or an INSERT statement on the employee table causes the trigger
check_salary to fire:
SQL> UPDATE employee SET salary=50000 WHERE emp_id=1;
UPDATE employee SET salary=50000 WHERE emp_id=1
*
ERROR at line 1:
ORA-04091: table SCOTT.EMPLOYEE is mutating, trigger/function may not see it
ORA-06512: at "SCOTT.CHECK_SALARY", line 5
ORA-04088: error during execution of trigger 'SCOTT.CHECK_SALARY'
The trigger reads from the employee table at the same time the table is being modified, thus causing the
table employee to mutate.
Mutating tables are not valid for statement triggers because statement triggers fire only once for each
event and allow the process to complete before the trigger is actually fired. However, row triggers can
cause a table to mutate because row triggers fire for each row, and therefore, the table is in the middle of
a modification when the trigger is actually fired.
In case of the DELETE trigger FOR EACH STATEMENT, any tables with foreign key constraints that
reference the triggering table and include the ON DELETE CASCADE option are considered mutating
tables. This is in addition to the triggering table itself. Consider an example, where a table called master
has a detail table child, with a foreign key constraint that references the master table and includes the
ON DELETE CASCADE clause in the foreign key. A DELETE trigger FOR EACH STATEMENT on the
master table will recognize both the master and the child table as mutating tables when a DELETE
statement is issued.

193
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Implementing Triggers
Scope
Describe situations for which triggers can be implemented.

Focused Explanation
Database triggers can de developed to implement features that are otherwise not provided by Oracle
server or as an alternative to those features provided by the Oracle server. Triggers can be used for:

Security Oracle server provides access to tables, to users, or to roles. On the other hand,
triggers allow access to tables based on the data values. For example, you may create a trigger
that restricts access to certain tables in the database during weekends.

Auditing Oracle server provides auditing on tables based on data operations. On the other
hand, triggers track data values for data operations on tables. For example, you may create a
trigger that tracks the data manipulation statements issued against a table and records the audit
information to a table.

Data integrity Oracle server enforces integrity constraints. On the other hand, triggers enforce
complex integrity constraints. For example, you may create a trigger that enforces the constraints
dynamically using the :OLD and the :NEW qualifiers.

Referential integrity Oracle server enforces referential integrity rules. On the other hand,
triggers enforce non-standard data integrity checks. For example, you may create a trigger that
enforces referential integrity constraints by cascading the effect of updates and setting the
columns to default or null values during updates and deletes.

Table replication Oracle server copies tables asynchronously into snapshots. On the other
hand, triggers copy tables synchronously into replicas. For example, you may create a trigger that
replicates the local table to a new location in real time.

Derived data Oracle server computes derived values asynchronously, at user-defined intervals.
On the other hand, triggers compute derived column values synchronously in real time. For
example, you may create a trigger that computes derived values using the :OLD and the :NEW
qualifiers in real time.

Event logging Oracle server logs events explicitly. On the other hand, triggers log events
implicitly. For example, you may create a trigger that uses the :OLD and the :NEW qualifiers and
logs events when the data in the base table is changed.

194
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Managing Triggers
Scope
List the privileges associated with triggers.

Focused Explanation
To create a trigger in the database, you need the CREATE TRIGGER privilege. The table on which the
trigger is to be created must be present in your schema, you must have the ALTER privilege on the table,
or you must have the ALTER ANY TABLE system privilege. The CREATE TRIGGER privilege includes the
ability to alter or drop the triggers in your schema.
The CREATE ANY TRIGGER system privilege empowers the user to create, alter, or drop the triggers in
their schema, as well as in any other schema. The triggers can be associated with any tables in the
database.
There is no separate privilege to invoke a trigger present in your schema. Triggers are invoked implicitly
by the DML statements. If the trigger references an object, such as the procedures, functions, or
packages that are not present in your schema, you need to have the EXECUTE privilege on these objects.
As per Oracle guidelines, the EXECUTE privilege should not be granted through roles.
Note: Triggers operate under the privileges of the owner, and not under the privileges of the user that
invokes the trigger by issuing the corresponding triggering statement.
The ADMINISTER DATABASE TRIGGER privilege allows the user to create a trigger on the DATABASE
event. If this privilege is later revoked from the user, the user can drop the trigger but cannot alter it.

195
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Viewing Trigger Information


Scope
Describe what happens if errors occur during trigger creation. Identify data dictionary views to gather
trigger information.

Focused Explanation
Triggers are created with the CREATE TRIGGER <trigger name> statement. The OR REPLACE
clause in the CREATE statement replaces any existing triggers on the table with the same name, with the
newer version of the trigger.
Note: You cannot create a trigger with a name that an already existing trigger on any table in your
schema uses. Trigger names need not be unique with respect to other objects in your schema, such as
tables, views, and procedures.
Even if there are compilation errors in the CREATE TRIGGER statement, the trigger is still created and
stored in the database. The status of such triggers is marked as INVALID. The status can be queried
from the STATUS column of the data dictionary view USER_OBJECTS. Triggers marked as invalid cannot
be invoked by the Oracle server, and the triggering statement on which these triggers are built will fail to
execute. The CREATED column of the USER_OBJECTS view displays the date that the trigger was created.
The compilation errors are stored in the data dictionary view USER_ERRORS. The compilation errors are
not displayed automatically. You must extract the compilation errors from the data dictionary. One way of
viewing the compilation errors is to query the USER_ERRORS views TEXT column to get the compilation
errors. The LINE column in the view displays the line number in the original program unit where the error
occurred. The POSITION column indicates the character position of the line identified in the LINE
column, where the error occurred. Another way to view the compilation errors in the SQL*Plus
environment is to issue the SHOW ERRORS or SHOW ERR command. These commands extract the errors
from the USER_ERRORS view.
Note: The USER_ERRORS view retains the information until the trigger is successfully compiled. The SHOW
ERRORS command displays the compilation errors from the most recent attempt made to store a program
unit.
The USER_TRIGGERS data dictionary view stores the source code of the trigger present in your schema.
The column of the view that contains the code is TRIGGER_BODY. The data dictionary view
ALL_TRIGGERS is similar to the USER_TRIGGERS view, except that the view contains the column OWNER
and displays the information about all triggers to which you have access.
Note: If you are granted the CREATE ANY TRIGGER system privilege, then the ALL_TRIGGERS view will
display the information about all the triggers in the database.

196
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: More Trigger Concepts: Program with PL/SQL


Identify characteristics of database triggers.
Identify when to use database triggers.
Identify events that cause database triggers to fire.
Identify the timings that can be specified for a database trigger.
Identify DDL events for which you can create a trigger.
Identify objects on which a DDL trigger can be built.
Identify the statements that can be included in a trigger body.
Identify the rules for using CALL statements.
Identify the cause of mutating tables.
Describe situations for which triggers can be implemented.
List the privileges associated with triggers.
Describe what happens if errors occur during trigger creation.
Identify data dictionary views to gather trigger information.

197
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Managing Dependencies: Program


with PL/SQL

198
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Track Procedural Dependencies


Scope
Describe dependent objects. Identify referenced objects. Identify when referenced and dependent objects
become invalid. Identify when procedures are automatically recompiled on being invoked.

Focused Explanation
Program units or objects in a database can refer to other objects. For example, you may create a
procedure that inserts data into a table in the database or a procedure that calls another procedure. In
such cases, the procedure that inserts the data into the table is called a dependent procedure. The table
into which the data is inserted by the procedure is called a referenced object. Similarly, the procedure that
calls another procedure is also a dependent procedure. The called procedure is the referenced object.
If the definition of a referenced object is changed or modified, its dependent objects become invalid. For
example, adding a new column to the table that is being referenced by the procedure will cause the
procedure to become invalid. Similarly, if the code of a called procedure is changed or if a called
procedure is dropped from the database, the dependent procedure will become invalid.
Program units, such as stored procedures, are automatically compiled by the Oracle server when they are
invoked. If the compilation succeeds, the procedures are executed. Otherwise, an error message is
generated. The following example creates a procedure named dep_proc, which calls another procedure
named ref_proc from within the procedure body:
SQL>

CREATE OR REPLACE PROCEDURE dep_proc

AS

BEGIN

ref_proc;

INSERT INTO test (test_no,test_desc) VALUES (2,'TESTING');

END;

Procedure created.

199
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

If the referenced procedure ref_proc is dropped from the database, the status of the dependent
procedure dep_proc is marked as invalid. When the dependent procedure is subsequently invoked,
Oracle tries to recompile the procedure. If the referenced procedure ref_proc has not been re-created,
the compilation fails, and the following error message is generated:
SQL> EXECUTE dep_proc;
BEGIN dep_proc; END;
*
ERROR at line 1:
ORA-06550: line 1, column 7:
PLS-00905: object SCOTT.DEP_PROC is invalid
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Note: If the procedure is invoked and the compilation is unsuccessful, the developer needs to view the
code and make changes accordingly.

200
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe Dependent and Referenced Objects


Scope
Identify objects that can be directly or indirectly referenced by a dependent procedure or function. Identify
the characteristics of dependent objects.

Focused Explanation
A procedure or function can either directly or indirectly reference other objects in a database. Indirect
reference indicates that a procedure or function references objects in the database through an
intermediate view, procedure, or function, or a packaged procedure or function.
A procedure or function can either directly or indirectly refer to the following objects:

Tables

Views

Sequences

Procedures

Functions

Packaged procedures and functions

The Oracle server automatically keeps track of all dependency issues. If the definition of the referenced
object is changed, all dependent objects will be assigned an invalid status.
Note: Invalid objects will produce errors when they are executed.
The data dictionary is continuously updated to reflect the status of the objects. You can view the STATUS
column of the data dictionary view USER_OBJECTS to note the status of the objects. The STATUS column
has two possible values:

VALID Indicates that the object has been compiled successfully and can be used without any
errors

INVALID Indicates that the object needs to be compiled before it can be used

201
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Define Local Dependencies


Scope
Identify local dependent objects.

Focused Explanation
Local dependencies refer to the dependent and the referenced objects that are present in the same node
in the same database. When a referenced object is modified, the Oracle server automatically keeps track
of all the dependency issues using an internal depends-on table. The Oracle server flags the status of
all dependent objects as invalid if the referenced objects are changed. The next attempt to invoke an
invalid dependent object causes the Oracle server to recompile it. If the compilation is successful, the
object is executed; otherwise, an error is generated.
Note: The Oracle server automatically compiles an object when it is invoked, and if the compilation is
successful, the status of the objects is marked as VALID.
For example, if the structure of the base table is modified, the view on the table will be marked as invalid.
If you try to issue the DESCRIBE command for the view, the statement will fail and the Oracle server will
issue the following error:
ORA-24372: invalid object for describe
This is because the status of the view has been marked as invalid.
Program units, such as procedures, can directly or indirectly reference other database objects, such as
tables. For example, the procedure add_test inserts the data into the test table by using the view
view_test. The procedure query_test directly references the table test by selecting data from it.
Consider the following scenarios:

The code of the procedure query_test is modified Both the procedures query_test and
add_test will have a status of valid.

A new column is added to the table test Both the procedures will be marked as invalid.
However, when the procedures are subsequently invoked, the Oracle server will try to recompile
them and, in this case, both the procedures will be validated.

The view view_test is removed from the database This will cause the status of the dependent
procedure add_test to be marked as invalid. However, on next invocation, Oracle will attempt to
recompile it. If the view view_test is not re-created, the status of the procedure add_test will
remain invalid, at the time of compilation. There will be no effect on the status of the procedure
query_test because the procedure is not dependent on the view.

202
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

View Dependency Information from the Data Dictionary Views


Scope
Query the USER_DEPENDENCIES view to display information about package dependencies.

Focused Explanation
The data dictionary view USER_DEPENDENCIES displays information about all direct dependencies within
your schema.
Note: Direct dependencies are present when an object directly references another object.
For example, consider the following package specification that includes a procedure definition:
SQL>

CREATE OR REPLACE PACKAGE dir_dep

IS

PROCEDURE add_test (p_id NUMBER, p_desc VARCHAR2);

4*

END;

Package created.
The package body is then created, which includes a call to the stand-alone procedure validate_test:
SQL>

CREATE OR REPLACE PACKAGE BODY dir_dep

IS

PROCEDURE add_test (p_id NUMBER, p_desc VARCHAR2)

IS

BEGIN

INSERT INTO test (test_id,test_desc ) VALUES (p_id, p_desc);

validate_test;

END add_test;

END dir_dep;

10

Package body created.

203
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

The following statement queries the data dictionary view USER_DEPENDENCIES to determine the
package dependencies:
SQL> SELECT REFERENCED_NAME, REFERENCED_TYPE FROM USER_DEPENDENCIES WHERE
NAME='DIR_DEP';
This statement will fetch the following results:
REFERENCED_NAME

REFERENCED_TYPE

------------------------------------------------------------------STANDARDPACKAGE

STANDARDPACKAGE

TEST

TABLE

VALIDATE_TEST

PROCEDURE

DIR_DEP

PACKAGE

The columns of the view USER_DEPENDENCIES are explained in Table 11-1:

Column

Column Description

NAME

Dependent objects name

TYPE

Dependent objects type (procedure, function, package, package body,


trigger, or view)

REFERENCED_OWNER

Owner of the referenced object

REFERENCED_NAME

Name of the referenced object

REFERENCED_TYPE

Type of the referenced object (table or procedure)

REFERENCED_LINK_NAME

Name of the link used to access the referenced object, if the referenced
object is remote

SCHEMAID

ID of the schema that is current

DEPENDENCY_TYPE

Type of dependency (REF dependency or HARD dependency)


Table 11-1

204
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe How the UTLDTREE Script is Used


Scope
Use the utldtree.sql script to create objects that track dependencies. Use the Oracle-supplied
procedure DEPTREE_FILL. Use the table DEPTREE_TEMPTAB and the view USER_DEPENDENCIES to
track dependencies.

Focused Explanation
You can also track direct and indirect dependencies from data dictionary views other than
USER_DEPENDENCIES. The views to do this are DEPTREE and IDEPTREE.
The Oracle server provides these views, but they need to be created and populated with data if you need
to use them. The following are the steps for creating the views DEPTREE and IDEPTREE:
1. Execute the script utldtree.sql found in the $ORACLE_HOME/rdbms/admin directory. This
script will create the views DEPTREE and IDEPTREE.
2. Populate the views with data. You execute the Oracle-supplied procedure DEPTREE_FILL. This
procedure has three arguments that must be supplied at run time:
o

object_type Type of the referenced object

object_owner Schema of the referenced object

object_name Name of the referenced object

For example, to view all the objects that are dependent on the table test, you execute the procedure
DEPTREE_FILL as follows:
SQL> EXEC DEPTREE_FILL ('TABLE','SCOTT','TEST');
PL/SQL procedure successfully completed.
The procedure DEPTREE_FILL also populates the table DEPTREE_TEMPTAB with the information of the
particular referenced object. You should execute this procedure each time you want to analyze a program
unit.
Note: The script utldtree.sql creates the views DEPTREE and IDEPTREE. The procedure
DEPTREE_FILL, when executed, will populate the views with the data related to the object whose name
is passed as an argument.

205
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe How the DEPTREE and IDEPTREE Views are Used


Scope
Query the data dictionary views USER_DEPENDENCIES and IDEPTREE to track object dependencies.
Query the data dictionary view IDEPTREE.

Focused Explanation
IDEPTREE and DEPTREE views are good for displaying information about indirect dependencies. If a
procedure calls a second procedure and the second procedure calls a third procedure, you will not be
able to view the indirect relationship between the first and the third procedure without making multiple
queries on the view USER_DEPENDENCIES. The view DEPTREE displays information about all the
dependent objects on a particular referenced object. The following query displays all dependent objects
on the table test:
SQL> SELECT NESTED_LEVEL, TYPE, NAME FROM DEPTREE ORDER BY SEQ#;
NESTED_LEVEL TYPE

NAME

------------ ------------------ -----------------------------0 TABLE

TEST

1 PROCEDURE

TESTIFY

1 PROCEDURE

HELLO

2 PROCEDURE

INSERT_INTO_EMP

1 TRIGGER

ONLYPOSITIVE

1 PROCEDURE

DEP_PROC

1 PROCEDURE

QUERY_EMP

2 PACKAGE BODY

DIR_DEP

1 PACKAGE BODY

DIR_DEP

9 rows selected.

206
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Table 11-2 describes the columns of the view DEPTREE:

Column

Column Description

NESTED_LEVEL

Nesting level in the dependency tree

TYPE

Type of dependent object

OWNER

Owner of dependent object

NAME

Name of dependent object

SEQ#

Sequence number in the dependency tree, used for ordering queries


Table 11-2

You can also view the dependency in a hierarchy by querying the view IDEPTREE. This view has only
one column named DEPENDENCIES. The following output is generated when querying the view:
SQL> SELECT * FROM IDEPTREE;
DEPENDENCIES
----------------------------------------------------------------------------TABLE SCOTT.TEST
PROCEDURE SCOTT.TESTIFY
PROCEDURE SCOTT.HELLO
PROCEDURE SCOTT.INSERT_INTO_EMP
TRIGGER SCOTT.ONLYPOSITIVE
PROCEDURE SCOTT.DEP_PROC
PROCEDURE SCOTT.QUERY_EMP
PACKAGE BODY SCOTT.DIR_DEP
PACKAGE BODY SCOTT.DIR_DEP
9 rows selected.
Note: Dependent objects can exist in any schema of the database.

207
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Understanding Remote Dependencies


Scope
Describe remote dependencies.

Focused Explanation
The Oracle server resolves local dependencies implicitly whenever a referenced object is changed or
modified. The status of dependent objects is marked as INVALID when the objects are present in the
same database. However, if the object is in a remote database connected to the local database via a
database link, the INVALID status is not marked immediately. When a local dependent object that calls a
remote object is executed, the status of the referenced object is checked to determine whether or not the
local object needs recompilation.
Note: The local dependent object is immediately set to a status of INVALID whenever the referenced
object is changed. In case of local dependencies, the Oracle server tries to recompile the dependent
object at execution. In case of remote dependencies, the status of the referenced object is checked only
when executing the local object.
For example, assume that the procedure update_emp calls another procedure validate_emp that is
stored in a remote database. The status of both the procedures is marked as VALID. Now, the procedure
validate_emp is re-created in the remote database using the CREATE OR REPLACE PROCEDURE
statement. If both procedures were in the same database, the status of the update_emp procedure
would have been marked as INVALID immediately. However, in case of a remote dependency, the status
of the procedure update_emp is not modified. The status of the local procedure update_emp remains
VALID even though the referenced procedure has been changed. The next time the local procedure is
invoked, the Oracle server checks whether or not the local procedure needs compilation. If the local
procedure needs compilation, the first attempt will fail and the status of the local procedure is marked as
INVALID. The second time the local procedure is invoked, the Oracle server will try to recompile the
INVALID procedure. If the compilation succeeds, the procedure will be executed.

208
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe How Remote Dependencies are Governed


Scope
Briefly describe how remote dependencies are governed.

Focused Explanation
Remote dependencies are resolved according to the method or mode chosen by the user. The two
modes are TIMESTAMP checking and SIGNATURE checking.
TIMESTAMP Checking
Each object created or compiled in a database carries a time stamp. This method uses the time stamp to
resolve remote dependency issues. For example, assume that there is a local procedure A that calls a
remote procedure B. The remote procedure is compiled at 8:00 A.M. This time stamp is recorded in the pcode of the procedure. The local procedure is compiled at 9:00 A.M. This time stamp, along with the time
stamp of the remote procedure (8:00 A.M.), is recorded in the p-code of the local procedure A.
When the local procedure A is invoked, the Oracle server compares the time stamp of the remote
procedure that is recorded in the p-code of procedure A to that recorded in the p-code of procedure B.
The Oracle server finds that the time stamp of procedure B (8:00 A.M.) matches the time stamp of the
procedure B recorded in procedure A (8:00 A.M.), and the local procedure executes successfully.
Next, assume that the remote procedure B is recompiled at 11:00 A.M. This new time stamp is now
recorded in the p-code of procedure B. The new time stamp is now different from the time stamp of
remote procedure B that is recorded in the local procedure A (8:00 A.M.). When the local procedure is
invoked for the first time, the Oracle server compares the time stamp of the remote procedure recorded in
the p-code of the remote procedure and the time stamp of the remote procedure recorded in the p-code
of the local procedure. If the time stamps are not equal, the execution of the local procedure fails and a
run-time error is generated. The execution of procedure A fails, and its status is marked as INVALID.
When the local procedure is invoked for the second time, the Oracle server attempts to recompile the
local procedure. If the compilation is successful, the procedure is executed and the status is flagged as
VALID.
Note: When using the TIMESTAMP mode, you must develop a strategy to invoke the local procedure for
the second time.

209
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

SIGNATURE Checking
Each program unit has its time stamp and signature recorded. This method uses both the time stamp and
the signature. The signature of a PL/SQL program unit consists of the following:

The name of the unit (procedure, function, or package)

The data types of the parameters

The modes of the parameters

The number of the parameters

The data type of the return value, if the program unit is a function

Note: The signature of the remote object is also stored in the local program unit along with the time
stamp.
The SIGNATURE mode first compares the time stamp of the remote procedure recorded in the p-code of
the remote procedure to that recorded in the local procedure. If both the time stamps match, the local
procedure is executed. If the time stamps do not match, the Oracle server checks whether or not the
signature of the remote procedure has changed. If the remote program unit has been recompiled but its
signature has not changed, the local program is executed without any errors even when the time stamp
does not match. If the signature of the remote program is also changed during its recompilation, the local
program is not executed and an error is generated. If the same condition had been applied to the
TIMESTAMP model, it would have resulted in an error.
Note: The parameter REMOTE_DEPENDENCIES_MODE defines the mode the Oracle server will use to
compare the validity of the remote program units. This parameter can be set in the initialization parameter
file. You can also specify or change the parameter at the session or system level using the ALTER
SESSION or ALTER SYSTEM commands. The syntax for setting the parameter in the initialization file is:
REMOTE_DEPENDENCIES_MODE = VALUE
For example:
REMOTE_DEPENDENCIES_MODE = TIMESTAMP

210
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe When a Remote Dependency is Unsuccessfully Recompiled


Scope
Describe when a remote dependency is unsuccessfully recompiled.

Focused Explanation
There may be several instances when the local program containing remote dependencies is unable to
recompile. Some of the reasons for this include:

The referenced object is removed or dropped from the database.

The referenced object, such as a table, is renamed.

The referenced column is dropped.

A referenced view is re-created but with columns that are different from the ones required for
successful execution.

The referenced procedures parameter list is changed.

211
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Describe When a Remote Dependency is Successfully Compiled


Scope
Describe when a remote dependency is successfully compiled.

Focused Explanation
The local procedures and functions that are dependent on remote objects are successfully recompiled
when:

The referenced table has new columns.

The data type of the columns of the table that are referenced has not been changed.

The referenced table is dropped from the database, but a public table having the same name and
structure is present in the database.

The body of the referenced procedure has been changed and recompiled without any compilation
errors.
Note: When a private table is dropped, the public table must contain the column that the
dependent procedure requires. Otherwise, the procedure will remain invalid. A public table is the
synonym for the private table, created in the database. The schema from where the private table
is dropped must have appropriate privileges on the public synonym or the user group PUBLIC
must be granted appropriate privileges on the public synonym. This ensures that the
recompilation of the local program units can be successful. Oracle resolves the dependency
issues by firstly searching for the private table in the schema, secondly searching for any private
synonyms for the table, and finally searching for the public synonyms for the table.

The dependent objects are successfully recompiled when:

New columns are added to the table.

All INSERT statements contain a column list.

Newly created columns do not have a NOT NULL constraint defined.

212
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

List How to Minimize Dependency Failures


Scope
Describe ways to minimize dependency failures.

Focused Explanation
A program unit that is marked invalid will need to be recompiled. The Oracle server will automatically
attempt to recompile the program unit when it is subsequently invoked. The program unit may or may not
compile successfully. To ensure that the program unit recompiles successfully, the following guidelines
are recommended:

Use %ROWTYPE to declare records and %TYPE to declare variables This feature enables you to
declare records and variables that inherit the data types of the underlying columns of the base
tables. Rather than defining the data type of each variable in the program unit, the %ROWTYPE
and %TYPE attributes provide you the flexibility to change the data types of the columns of the
table without having to modify the data types specified in the program unit.

Use the SELECT * notation This feature minimizes recompilation failures because SELECT *
will select all the columns of the table. Even if you add or remove any column from the table later,
the SELECT statement will automatically pick up the change in the table and will require no
changes to the program unit.

Include a column list with INSERT statements The Oracle server assumes that for the INSERT
statements that do not have a column list, values passed are in the exact order of the columns
description in the database. If the column list is changed by virtue of the ALTER statement or by
the DROP and CREATE statements, the result may be unexpected. For example, if a new column
is added to the table, the INSERT statement will fail if it does not supply the value for the new
column. On the other hand, the INSERT statement may execute successfully but insert data into
the wrong columns if the data types of the columns match. This is because the values list in the
INSERT statement only requires the data types of the inserted value to match the column list in
order.

213
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Review Checklist: Managing Dependencies: Program with PL/SQL


Describe dependent objects.
Identify referenced objects.
Identify when referenced and dependent objects become invalid.
Identify when procedures are automatically recompiled on being invoked.
Identify objects that can be directly or indirectly referenced by a dependent procedure or
function.
Identify the characteristics of dependent objects.
Identify local dependent objects.
Query the USER_DEPENDENCIES view to display information about package dependencies.
Use the utldtree.sql script to create objects that track dependencies.
Use the Oracle-supplied procedure DEPTREE_FILL.
Use the table DEPTREE_TEMPTAB and the view USER_DEPENDENCIES to track dependencies.
Query the data dictionary views USER_DEPENDENCIES and IDEPTREE to track object
dependencies.
Query the data dictionary view IDEPTREE.
Describe remote dependencies.
Briefly describe how the remote dependencies are governed.
Describe when a remote dependency is unsuccessfully recompiled.
Describe when a remote dependency is successfully compiled.
Describe ways to minimize dependency failures.

214
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Test Taking Strategies


The Oracle Certified Associate, Professional, and Master Credentials
identify a standard of competence for entry-level and professional job roles
that utilize Oracle products. Oracles certification program is a recognized
credential that signifies a proven level of knowledge and ability. With each
level of certification, a higher benchmark of ability is set for greater
opportunities and higher pay.
The 1Z0-147 exam is the second exam required to obtain Oracle9i
Developer Certified Associate status. Passing this exam and earning this
certification demonstrates your ability to function as an Oracle Certified
Associate Developer. The OCA credential is a prerequisite for earning the
OCP Developer credential.

1Z0-147 TEST
DETAILS:
Number of questions:
66
Time allotted:
90 minutes
OVERVIEW OF
ITEM TYPES:
Multiple Choice

This exam is proctored, meaning you can take the exam at an Oracle
University Training Center or an Authorized Prometric Testing Center.

Oracle Certification Roadmap


The 1Z0-147 is required whether you are seeking an Oracle9i and Oracle 10g Developer Associate or
Professional credential.
An Oracle candidate should combine training with on-the-job experience. Many of the exam questions are
based on real-world scenarios so hands-on experience with the software is vital.
To review the Developer OCA and OCP certification tracks:
http://www.oracle.com/education/certification/index.html?appdev9i_track.html
To review the objectives for the 1Z0-147 exam:
http://education.oracle.com/pls/web_prod-plqdad/db_pages.getpage?page_id=41&p_org_id=1001&lang=US&p_exam_id=1Z0_147

Registering for the Exam


To register for the exam:
http://www.oracle.com/education/certification/index.html?testreg.html

215
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Resources
Because the exam is based on the Oracle9i: Program with PL/SQL instructor-led training, attending this
course is the best preparation.

Test Day Strategies


The most important test day strategy is be thoroughly prepared for the exam beforehand. You must know
the material. Cramming the day of the exam is not a good strategy to use for any type of test, especially
certification exams. Oracle highly discourages cheating on the un-proctored version. The consecutive
proctored exams require SQL proficiency and cheating on this exam will prevent you from passing the
other exams.
Oracle allows you to go back to questions that you previously answered, so manage your time wisely. If a
question is requiring too much time to answer, you can always select the best possible response, and
then return to the question after answering all of the other questions.

General Tips:

Schedule your exam only after you are confident that you have mastered the subject matter.

Schedule your exam for a time of day when you perform at your best.

Wear comfortable clothing.

Allow 2 hours to complete the exam.

Eat a light meal beforehand.

Review the question types carefully before starting the actual exam. Be careful not to bypass this
option because you are in a hurry to finish the exam.

Everything we do has time limitations, so dont let the pressure overwhelm you.

Oracle9i: Program with PL/SQL - Specific Tips:

Before starting the exam, flip through your short stack of reserved flash cards, Review Checklists
and/or personal study notes to remind yourself about terms, topics, and syntax that are likely to
appear on the exam.

Determine how much time you are allotted to answer each question. Do not spend too much time
on a given question during your first pass through the exam. If a question is requiring too much
time to answer, select the best possible answer, mark the question for review, and return to the
question after answering all of the other questions.

216
www.selftestsoftware.com

Oracle 1Z0-147 Study Guide

Test Items
The 1Z0-147 exam contains only multiple-choice items. While knowing the technical content for this exam
is the most important thing you can do to pass the exam, understanding the methodology of the question
type and following a strategy of how to answer each type can mean the difference between passing and
failing. Below we provide you with specific advice for multiple-choice questions.
Multiple-Choice
1. Read each multiple-choice question with the intention of answering the question without the
alternatives that follow. Focus on finding an answer without the help of the alternatives. This will
increase your concentration and help you read the question more clearly.
2. Use the process of elimination when you do not know the answer for sure. If the question has a
single answer, and four options are listed, eliminate two of these options quickly and then make
the decision between the two that remain. This increases your probability to 50/50. Another
helpful method of elimination is to use a true-false approach where you identify a likely false
alternative. Then, you eliminate it. The true-false elimination method is particularly helpful when
the question requires more than one answer.
3. When two very similar answers appear, it is likely that one of them is the correct choice. Test
writers often disguise the correct option by giving another option that looks very much like the
correct one.
You can download a free demo on our website that mimics the types of questions that will appear on the
exam. Sample questions do not cover all the content areas on the exam.

217
www.selftestsoftware.com

YOURE ALREADY SMART, WE HELP YOU BE SMARTER.

Thank You and Good Luck on your Exams!


Thank you for purchasing a Self Test Software certification exam preparation product.
Self Test helps you figure out what you know and gives you the answers to what you
dont its the best way to prepare for your certification exams.
For your upcoming exam and throughout your IT career, Self Test is the only tool you
need to improve your IT IQ and succeed on exam day.

The Self Test Software Team

You might also like