You are on page 1of 34

UNIT - 5

PL/SQL

PL/SQL Procedure

The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks. It is just like procedures in other programming languages.
A Procedure is a subprogram unit that consists of a group of PL/SQL statements. Each procedure
in Oracle has its own unique name by which it can be referred. This subprogram unit is stored as
a database object
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the parameters or variables passed
to the procedure.
Body: The body contains a declaration section, execution section and exception section similar
to a general PL/SQL block.

characteristics

• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these procedures can be made by referring to their name, to execute the PL/SQL
statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the procedure or fetched from the procedure through
parameters.
• These parameters should be included in the calling statement.
• Procedure can have a RETURN statement to return the control to the calling block, but it
cannot return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called from
another block or through EXEC keyword.
Parameter:

1 | Page
• The parameter is variable or placeholder of any valid PL/SQL datatype through which the
PL/SQL subprogram exchange the values with the main code. This parameter allows to
give input to the subprograms and to extract from these subprograms.
• These parameters should be defined along with the subprograms at the time of creation.
• These parameters are included n the calling statement of these subprograms to interact
the values with the subprograms.
• The datatype of the parameter in the subprogram and the calling statement should be
same.
• The size of the datatype should not mention at the time of parameter declaration, as the
size is dynamic for this type.
How to pass parameters in procedure:
When you want to create a procedure or function, you have to define parameters.
There is three ways to pass parameters in procedure:
1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter
1. IN Parameter
• This parameter is used for giving input to the subprograms.
• It is a read-only variable inside the subprograms. Their values cannot be changed inside
the subprogram.
• In the calling statement, these parameters can be a variable or a literal value or an
expression, for example, it could be the arithmetic expression like '5*8' or 'a/b' where 'a'
and 'b' are variables.
By default, the parameters are of IN type.

2. OUT Parameter:

• This parameter is used for getting output from the subprograms.


• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
• In the calling statement, these parameters should always be a variable to hold the value
from the current subprograms.
3. IN OUT Parameter:
2 | Page
• This parameter is used for both giving input and for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
• In the calling statement, these parameters should always be a variable to hold the value
from the subprograms.
RETURN

• RETURN is the keyword that instructs the compiler to switch the control from the
subprogram to the calling statement. In subprogram RETURN simply means that the
control needs to exit from the subprogram. Once the controller finds RETURN keyword
in the subprogram, the code after this will be skipped.

● Normally, parent or main block will call the subprograms, and then the control will shift
from those parent block to the called subprograms. RETURN in the subprogram will
return the control back to their parent block. In the case of functions RETURN statement
also returns the value. The datatype of this value is always mentioned at the time of
function declaration. The datatype can be of any valid PL/SQL data type.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];

Subprogram

Create procedure procedurename


Is
Variable declaration
Begin
---stmts;
---stmts;

3 | Page
End;

Explanation
• CREATE PROCEDURE instructs the compiler to create new procedure.
• Keyword 'OR REPLACE' instructs the compile to replace the existing procedure (if any)
with the current one.
• Procedure name should be unique.
• Keyword 'IS' will be used, when the procedure is nested into some other blocks.
If the procedure is standalone then 'AS' will be used. Other than this coding standard, both have
the same meaning.

Example

The following example creates a simple procedure that displays the string 'Hello World!' on the
screen when executed.

CREATE OR REPLACE PROCEDURE greetings


AS BEGIN
dbms_output.put_line('Hello World!');
END;
/
Create procedure arun
As
begin
Dbms_output.put_line(“deepak”);
End;
/ execute arun;

When the above code is executed using the SQL prompt, it will produce the following result

Procedure created.

Executing a Standalone Procedure

A standalone procedure can be called in two ways


Using the EXECUTE keyword
Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings'

4 | Page
EXECUTE greetings;
The above call will display
Hello World
PL/SQL procedure successfully completed.

Example 2

Creating Procedure and calling it using EXEC


In this example, we are going to create a procedure that takes the name as input and prints the
welcome message as output. We are going to use EXEC command to call procedure.

Code Explanation:

Code line 1: Creating the procedure with name 'welcome_msg' and with one parameter 'p_name'

of 'IN' type.

Code line 4: Printing the welcome message by concatenating the input name.

Procedure is compiled successfully.

Code line 7: Calling the procedure using EXEC command with the parameter 'Guru99'.
Procedure is executed, and the message is printed out as "Welcome Guru99".

Create procedure example

In this example, we are going to insert record in user table. So you need to create user table first.
Table creation:

5 | Page
create table user(id number(10) primary key,name varchar2(100));
IN & OUT Mode Example 1

This program finds the minimum of two values. Here, the procedure takes two numbers using the
IN mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number)


IS BEGIN
IF x < y THEN
z:= x;
ELSE

6 | Page
z:= y;
END IF;
END;

BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/

When the above code is executed at the SQL prompt, it produces the following result

Minimum of (23, 45) : 23


PL/SQL procedure successfully completed.

IN & OUT Mode Example 2

This procedure computes the square of value of a passed value. This example shows how we can
use the same parameter to accept a value and then return another result.

Sub program Main program


DECLARE BEGIN
a number; a:= 23;
PROCEDURE squareNum(a);
squareNum(x IN OUT number) dbms_output.put_line('
IS BEGIN Square of (23): ' || a);
x := x * x; END;
END; /

When the above code is executed at the SQL prompt, it produces the following result
Square of (23): 529
PL/SQL procedure successfully completed.

PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure.

7 | Page
The main difference between procedure and a function is, a function must always return a value,
and on the other hand a procedure may or may not return a value.
Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.

Characteristics

• Functions are a standalone block that is mainly used for calculation purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at
the time of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in
functions.
• Function with no DML statements can be directly called in SELECT query whereas the
function with DML operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or
packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the
parameters.
• These parameters should be included in the calling statement.
• Function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with
assignment operator to populate the variables.

8 | Page
Function_name: specifies the name of the function.
[OR REPLACE] option allows modifying an existing function.
The optional parameter list contains name, mode and types of the parameters.
IN represents that value will be passed from outside and OUT represents that this parameter will
be used to return a value outside of the procedure.

The function must contain a return statement.


RETURN clause specifies that data type you are going to return from the function.
Function_body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.

9 | Page
PL/SQL function example using table
Let's take a customer table. This example illustrates creating and calling a standalone function.
This function will return the total number of CUSTOMERS in the customers table.

Calling PL/SQL Function:

• While creating a function, you have to give a definition of what the function has to do.
• To use a function, you will have to call that function to perform the defined task. Once
the function is called, the program control is transferred to the called function.
• After the successful completion of the defined task, the call function returns program
control back to the main program.
• To call a function you have to pass the required parameters along with function name and
if function returns a value then you can store returned value.
Following program calls the function totalCustomers from an anonymous block:

10 | Page
11 | Page
PL/SQL Composite Data Types:- Records, Tables and Varrays

Composite data types


Like scalar data types. Scalar data types are atomic do not consist of a group.
Composite data types consists of group or collections.

Eg:
RECORD
TABLE
NESTED TABLE
VARRAY

PL/SQL records

A PL/SQL record is a data structure that can hold data items of different kinds. Records consist
of different fields, similar to a row of a database table.
For example,To keep track of books in a library. we might want to track the following attributes
about each book like, Title, Author, Subject, Book ID. A record containing a field for each of
these items allows treating a BOOK as a logical unit and allows you to organize and represent its
information in a better way.

PL/SQL can handle the following types of records:


Table-based
Cursor-based records
User-defined records

A record can be explicitly declared based on a cursor or table:

CURSOR cursorname IS

12 | Page
SELECT query;
Recordname CursorName%ROWTYPE;

Creating a PL/SQL Record

The record type is defined as:


TYPE record type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
record-name type_name;
Example: Declare the Book record

DECLARE
TYPE books IS RECORD(title varchar(50), author varchar(50), subject varchar(100),
book_id number);
book1 books;
book2 books;
Referencing Fields in a Record
Fields can be referenced by using record name as qualifier.
Recordname.fieldname
Eg: Books.title

The value can be assigned to it by


Books.title:=’RDBMS’;
Working with Records

DECLARE
type books is record
(title varchar2(50),
author varchar2(50),
subject varchar2(100),
book_id number);
book1 books;
book2 books;
BEGIN -- Book 1 specification

13 | Page
book1.title := 'C Programming';
book1.author := 'Nuha Ali ';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
End;
/

Working with Records

-- Print book 1 record


dbms_output.put_line('Book1 ,title : '|| book1.title); dbms_output.put_line('Book 1 author : '||
book1.author); dbms_output.put_line('Book 1 subject : '|| book1.subject);
dbms_output.put_line('Book 1 book_id : ' || book1.book_id);
-- Print book 2 record
dbms_output.put_line('Book 2 title : '|| book2.title); dbms_output.put_line('Book 2 author : '||
book2.author); dbms_output.put_line('Book 2 subject : '|| book2.subject);
dbms_output.put_line('Book 2 book_id : '|| book2.book_id);
END;
/

When the above code is executed at SQL prompt, it produces the following result:

Book1, title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
PL/SQL procedure successfully completed.

14 | Page
Nested Records

We can create nested record by including a record into another record as a field. The record that
contains another record as a field is called the enclosing record
. Eg:
DECLARE
TYPE address_rectype IS RECORD
(first VARCHAR2(10),
Last VARCHAR2(10),
Street VARCHAR2(10),
City VARCHAR2(10),
State VARCHAR2(10));
TYPE ALL_ADDRESS_RECTYPE IS RECORD
(HOME_ADDRESS ADDRESS_RECTYPE,
BUS_ADDRESS ADDRESS_RECTYPE,
VACATION_ADDRESS ADDRESS_RECTYPE);
ADDRESS_REC ALL_ADDRESS_RECTYPE;

15 | Page
PL/SQL TABLES/ Associate Array

Nesting records makes code more readable and easier to maintain. We Dot notation is also used
to reference fields in the nested situation.

TPL/SQL tables help you move bulk data. They can store columns or rows of Oracle data, and
they can be passed as parameters. So, PL/SQL tables make it easy to move collections of data
into and out of database tables or between client-side applications and stored subprograms.

Declaring PL/SQL TABLE

To create PL/SQL tables, take two steps.


• Define a TABLE type with TYPE statement. The structure could use any of the scalar
data types.
• Declare an actual table based on the type declared in the previous step.
General syntax is

TYPE table_type_name IS TABLE OF datatype [NOT NULL] INDEX BY


BINARY_INTEGER;
Actual table based on the table type declared earlier by
Tablename tabletypename;

Referencing Table Elements/Rows

The rows in a table are referenced in the same way that an element in an array is referenced. We
must use the primary key values in a pair of parentheses as its subscript or index.
Tablename(primarykeyvalue)
Assigning values to rows in a PL/SQL Table
We can assign values to the rows in a table in three ways:
Direct assignment
Assignment in a loop

16 | Page
Aggregate assignment
Direct assignment
We can assign a value to a row with an assignment. This is preferable if only a few assignments
are to be made.
Assignment in a loop

We can use any of the three PL/SQL loops to assign values to rows in a table.
Aggregate assignment

We can assign a table’s values to another table.


Data types of both tables must be matched.
Eg:
DECLARE
TYPE salary IS TABLE OF NUMBER INDEX BY INTEGER;
salary_list salary;
name VARCHAR2(20);
BEGIN -- adding elements to the table
salary_list('Rajnish') := 62000;
salary_list('Minakshi') := 75000;
salary_list('Martin') := 100000;
salary_list('James') := 78000;
-- printing the table
name := salary_list.FIRST;
WHILE name IS NOT null LOOP
dbms_output.put_line ('Salary of ' || name || ' is ' || salary_list(name));
name := salary_list.NEXT(name);
END LOOP;
END;
/
output
Salary of James is 78000
Salary of Martin is 100000
Salary of Minakshi is 75000
Salary of Rajnish is 62000
PL/SQL procedure successfully completed.

PL/SQL VARRAYS

A varray is another composite data type or collection type in PL/SQL.


Variable-size array – single dimensional array- collection of elements with the same data type.
VARRAY declaration is done in two steps

17 | Page
• Declare a PL/SQL VARRAY type with a TYPE statement. The TYPE declaration
includes a size to set the upper bound of a varray. The lower bound is always one.
• Declare an actual varray based on the type declared in the previous step.
A varray is another composite data type or collection type in PL/SQL.
Variable-size array – single dimensional array- collection of elements with the same data type.
VARRAY declaration is done in two steps
• Declare a PL/SQL VARRAY type with a TYPE statement. The TYPE declaration
includes a size to set the upper bound of a varray. The lower bound is always one.
• Declare an actual varray based on the type declared in the previous step.

VARRAYS syntax

Declare a VARRAY type


To declare a VARRAY type, you use this syntax:
TYPE type_name IS VARRAY(max_elements)
OF element_type [NOT NULL];
varray_name type_name
In this declaration:
type_name is the type of the VARRAY.
max_elements is the maximum number of elements allowed in the VARRAY.
NOT NULL specifies that the element of the VARRAY of that type cannot
have NULL elements. Note that a VARRAY variable can be null, or uninitialized.
element_type is the type of elements of the VARRAY type’s variable.
Example:
DECLARE
type namesarray IS VARRAY(5) OF VARCHAR2(10);
type grades IS VARRAY(5) OF INTEGER;
names namesarray;
marks grades;
total integer;
BEGIN
names := namesarray('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz');
marks:= grades(98, 97, 78, 87, 92);
total := names.count;
dbms_output.put_line('Total '|| total || ' Students');
FOR i in 1 .. total LOOP
dbms_output.put_line('Student: ' || names(i) || ' Marks: ' || marks(i));
END LOOP;
END;
/
output
SQL> /
Total 5 Students

18 | Page
Student: Kavita
Marks: 98
Student: Pritam
Marks: 97
Student: Ayan
Marks: 78
Student: Rishav
Marks: 87
Student: Aziz
Marks: 92

PL/SQL procedure successfully completed.

Sample query for procedure

Main program- pl/sql


Declare
Begin
Add();-----calling procedure
End;
Sub program==== add()
Create procedure add()---called procedure
is
Begin
End;

Sample query for procedure

Main program- pl/sql


Declare
Begin
Add();-----calling procedure
End;
Sub program==== add()
Create procedure add()---called procedure
is
Begin
Dbms_output.put_line(“hello”); output
hello
End;

Sample query for procedure


Main program- pl/sql
Declare

19 | Page
a number(2):=23;
b number(2):=2;
Begin
Add(a,b);-----calling procedure
End;
Sub program==== add() )---called procedure
Create procedure add(x in number, y in number)
is
Begin
Dbms_output.put_line(x || y); output
23 2
End;
Sample query for record
Declare
Type ss is record( a number(3), b varchar2(12))
x1 ss;
X2 ss;
X3 ss;
Begin
X1.a=22;
X1.b=‘arun’;
X2.a=33;
X2.b=‘brindha’;
X3.a=44
X3.b=‘chandru’;
Dbms_output.put_line(x1.a);
Dbms_output.put_line(x1.b);
Dbms_output.put_line(x2.a);
Dbms_output.put_line(x2.b);
Dbms_output.put_line(x3.a);
Dbms_output.put_line(x3.b);
End;
Output:
22
Arun
33
Brindha
44
Chandru

Sample query for nestedrecord


Declare
Type BCAA is record(name varchar2(23), address varchar2(12),age number(2)
Type BCAB is record(std1 BCAA, std2 BCAA)
x BCAA;
Begin
x.Std1.name:=‘’akash”;
20 | Page
x.Std1.address:=‘coimbatore’;
x.Std1.age:=19;
x.Std2.name:=‘’balu”;
x.Std2.address:=‘coimbatore’;
x.Std2.age:=20;
End;
Sample query for varray
declare
Type a is varray(name varchar2(12),address varchar2(12))
b a;
Begin
b:=a(‘priya’,’kovai’);
Dbms_output.put_line(b(0));
Dbms_output.put_line(b(1));
End;
Output:
priya
kovai

A package is a way of logically storing the subprograms like procedure, function, exception or
cursor into a single common unit. A package can be defined as an oracle object that is compiled
.and stored in the database

Once it is compiled and stored in the database it can be used by all the users of database who
.have executable permissions on Oracle database

Components of Package
Package has two basic components:
Specification: It is the declaration section of a Package
Body: It is the definition section of a Package.
1. Package specification or declaration
It mainly comprises of the following:
1. Package Name.
2. Variable/constant/cursor/procedure/function/exception declaration.
3. This declaration is global to the package.
Syntax

21 | Page
• where,

• CREATE OR REPLACE PACKAGE are keywords used to create a package

• FUNCTION and PROCEDURE are keywords used to declare function and procedure

while creating package.

• <package_name>, <function_name>, <procedure_name> are user-defined names.

• IS/AS are keywords used to declare package.

.RETURN is a keyword specifying value returned by the function declared

Example:

The following code shows a package specification having a single procedure.


You can have many global variables defined and multiple procedures or functions inside
a package.

22 | Page
CREATE PACKAGE cust_sal AS
PROCEDURE find_sal(c_id customers.id%type);
END cust_sal;
/
When the above code is executed at SQL prompt, it produces the following result:
Package created.

Package Body

It mainly comprises of the following:

It contains the definition of procedure, function or cursor that is declared in the package

specification.

It contains the subprogram bodies containing executable statements for which package

has been created

syntax:

CREATE OR REPLACE PACKAGE BODY are keywords used to create the package
with a body.
FUNCTION and PROCEDURE are keywords used to define function and procedure
while creating package.
<package_name>, <function_name>, <procedure_name> are user-defined.
IS/AS are keywords used to define the body of package, function and procedure.
RETURN is a keyword specifying value returned by the function defined.
DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code
block containing variable declaration,
executable statements, error handling statements and marking end of PL/SQL block
respectively where DECLARE and EXCEPTION part are optional.
Following is the syntax for referring a package object:
Packagename.objectname;
The Object can be a function, procedure, cursor, exception that has been declared in the
package specification and defined in the package body and to access their executable
statements above syntax is used.

23 | Page
The CREATE PACKAGE BODY Statement is used for creating the package body.
The following code snippet shows the package body declaration for the cust_sal package
created above.

Package Body

CREATE PACKAGE BODY cust_sal AS


PROCEDURE find_sal(c_id customers.id%TYPE) IS
c_sal customers.salary%TYPE;
BEGIN
SELECT salary INTO c_sal
FROM customers WHERE id = c_id;
dbms_output.put_line('Salary: '|| c_sal);
END find_sal;
END cust_sal;
/
When the above code is executed at SQL prompt, it produces the following result:
Package body created.

Using the Package Elements


The package elements (variables, procedures or functions) are accessed with the
following syntax:
package_name.element_name;
Consider, we already have created above package in our database schema, the following
program uses the find_sal method of the cust_sal package:
DECLARE
code customers.id%type := &cc_id;
BEGIN
cust_sal.find_sal(code);
END;
/
When the above code is executed at SQL prompt, it prompt to enter customer ID and
when you enter an ID, it displays corresponding salary as follows:

24 | Page
Enter value for cc_id: 1
Salary: 3000
PL/SQL procedure successfully completed.
Example
write a simple program to demonstrate the use of Package in PL/SQL.
PL/SQL code for package specification:

Output: Package Created

25 | Page
PL/SQL code for package body:

write the PL/SQL code for calling the Procedure and Function used in Package.
:
Output:
Enter value for sno: 12
Enter value for snm: Neha
RECORD UPDATED
RECORD NOT FOUND

PL/SQL procedure successfully completed.

If the package specification or package body has been created with compilation errors
then a following warning message is displayed on the screen:

WARNING: Package Body created with compilation errors


.
In that case, the errors can be seen by executing following statement:
Example program 2:
Table name: emp1

26 | Page
Package Specification
Create Package specification code for defining procedure, function IN or OUT parameter

and execute package specification program.


CREATE or REPLACE PACKAGE pkg1 IS | AS
PROCEDURE pro1
(no in number, name out varchar2);
FUNCTION fun1
(no in number) RETURN varchar2;
END;

Package Body
Create Package body code for implementing procedure or function that are defined
package specification. Once you implement execute this program.
CREATE PACKAGE BODY pkg1
IS
PROCEDURE pro1(no in number, info out varchar2)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;
FUNCTION fun1(no in number) return varchar2
IS
name varchar2(20);

27 | Page
BEGIN
SELECT ename INTO name FROM emp1 WHERE eno = no;
RETURN name;
END;
END;
/
Pl/SQL Program calling Package (main program)
Now we have a one package pkg1, to call package defined function, procedures also pass
the parameter and get the return result.

Result
Now execute the above created pkg_prg.sql program to asking which user information
you want to get, you put user id and give information.
no number &n=2
Procedure Result
2 marks jems Program Developer 38K
Function Result
marks jems

28 | Page
PL/SQL procedure successfully completed.

Sample query
1.Package specification
2. Package body
3. Main program

1.Package specification

PL/SQL – TRIGGERS

Triggers are stored programs, which are automatically executed or fired when some events
occur.
Triggers are, in fact, written to be executed in response to any of the following events:
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.

Trigger is stored into database and invoked repeatedly, when specific condition match.

Triggers are stored programs, which are automatically executed or fired when some event
occurs.

Syntax Explanation:

29 | Page
The above syntax shows the different optional statements that are present in trigger creation.

1. BEFORE/ AFTER will specify the event timings.


2. INSERT/UPDATE/LOGON/CREATE/etc. will specify the event for which the trigger
needs to be fired.
3. ON clause will specify on which object the above-mentioned event is valid. For example,
this will be the table name on which the DML event may occur in the case of DML
Trigger.
4. Command "FOR EACH ROW" will specify the ROW level trigger.
5. WHEN clause will specify the additional condition in which the trigger needs to fire.
The declaration part, execution part, exception handling part is same as that of the other
PL/SQL blocks. Declaration part and exception handling part are optional.

NEW and :OLD Clause


In a row level trigger, the trigger fires for each related row. And sometimes it is required to know
the value before and after the DML statement.
Oracle has provided two clauses in the RECORD-level trigger to hold these values. We can use
these clauses to refer to the old and new values inside the trigger body.
:NEW – It holds a new value for the columns of the base table/view during the trigger execution
:OLD – It holds old value of the columns of the base table/view during the trigger
execution

30 | Page
Example:
To start with, we will be using the CUSTOMERS table we had created and used in the previous
chapters:

Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
the following program creates a row level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.

This trigger will display the salary difference between the old values and new values:
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROWWHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.

Here following two points are important and should be noted carefully:

31 | Page
● OLD and NEW references are not available for table level triggers, rather you can use

them for record level triggers.

● If you want to query the table in the same trigger, then you should use the AFTER

keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.

● Above trigger has been written in such a way that it will fire before any DELETE or

INSERT or UPDATE operation on the table, but you can write your trigger on a single or
multiple operations, for example BEFORE DELETE, which will fire whenever a record
will be deleted using DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)VALUES (7,


'Kriti', 22, 'HP', 7500.00 );
When a record is created in CUSTOMERS table, above create trigger
display_salary_changes will be fired and it will display the following result:

Old salary: New salary: 7500 Salary difference:


Because this is a new record so old salary is not available and above result is coming as
null.
Now, let us perform one more DML operation on the CUSTOMERS table.
Here is one UPDATE statement, which will update an existing record in the table:
UPDATE customers SET salary = salary + 500 WHERE id = 2;
When a record is updated in CUSTOMERS table, above create trigger
display_salary_changes will be fired and it will display the following result:
Old salary: 1500
New salary: 2000
Salary difference: 500
Example -2:

32 | Page
Output: trigger created

After initializing the trigger CheckAge, whenever we will insert any new values or update the
existing values in the above table STUDENT our trigger will check the age before
executing INSERT or UPDATE statements and according to the result of triggering restriction or
condition it will execute the statement.

33 | Page
34 | Page

You might also like