0% found this document useful (0 votes)
11 views77 pages

Updates - Lec 5

This document provides an overview of PL/SQL, including its architecture, data types, and programming constructs such as blocks, variables, and control statements. It highlights the differences between PL/SQL and SQL, explains the structure of PL/SQL blocks, and details various data types like CHARACTER, NUMBER, BOOLEAN, and LOB. Additionally, it covers decision-making statements and examples of using conditional statements in PL/SQL.

Uploaded by

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

Updates - Lec 5

This document provides an overview of PL/SQL, including its architecture, data types, and programming constructs such as blocks, variables, and control statements. It highlights the differences between PL/SQL and SQL, explains the structure of PL/SQL blocks, and details various data types like CHARACTER, NUMBER, BOOLEAN, and LOB. Additionally, it covers decision-making statements and examples of using conditional statements in PL/SQL.

Uploaded by

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

1

IS 221 Database Management

Lec 5

PL/SQL AND TRIGGERS

Book: Fundamentals of Database Systems – Seventh Edition :


Chapter 5: The Relational Data Model and Relational Database Constraints
& Chapter 9: Relational Database Design by E R- and E E R R-to-Relational Mapping

1
Chapter Outline
 PL/SQL Architecture
 PL/SQL Data types
 Variables, Identifiers and Naming convention
 PL/SQL BLOCK
 PL/SQL-Conditional Statements
 PL/SQL-Loop statements
 PL/SQL- Varray
 PL/SQL –Stored procedures and Functions
 Triggers

2
Introduction

• The PL/SQL stands for Procedural Language extensions to Structured Query


Language

• Basically, SQL is used to perform basic operations of creating a database, storing


data in the database, updating data in the database, retrieving the stored data of
database, etc, whereas PL/SQL is a fully Structured Procedural language which
enables the developer to combine the powers of SQL with its procedural statements.

3
PL/SQL Architecture

 PL/SQL architecture consist of


following three components,
displayed in the diagram

4
PL/SQL Architecture(contd.)

 PL/SQL Block:

PL/SQL block creates the structured logical blocks of code that describes the
process to be executed. Such a block consists of SQL statements and PL/SQL
instructions that are then passed to the oracle engine for execution.
 PL/SQL Engine:

The PL/SQL block containing the procedural statements are executed by the
PL/SQL statement executor inside the PL/SQL engine. In simpler words, the
PL/SQL engine provides the environment in which the PL/SQL block is executed.
 Database Server:

This can be Oracle DB server or MySQL DB server. The DB server stores data in
tables.

5
PL/SQL Architecture(contd.)

6
Difference between PL/SQL and SQL
 SQL statement

• When is issued on the client computer, the request is made to the database on the
server, and the result set is sent back to the client
• As a result, a single SQL statement causes two trips on the network.

• If multiple SELECT statements are issued, the network traffic increase significantly
very fast. For example, four SELECT statements cause eight network trips.

 SQL statement as part of the PL/SQL block

• they are sent to the server as a single unit. The SQL statements in this PL/SQL
program are executed at the server and the result set is sent back as a single unit.
There is still only one network trip made as is in case of a single SELECT statement.

7
Comparison of SQL* PLUS and PL/SQL

8
PL/SQL DATA TYPES
• The PL/SQL variables, constants and parameters must have a valid data
type, which specifies a storage format, constraints, and a valid range of
values.

9
PL/SQL DATA TYPES(contd.)
The scalar types are types that store single values such
as number Boolean, character, and date time
The composite types are types that store multiple values, for
example, record and collection.
 The LOB Data Type is mainly used to store and manipulate
large blocks of unstructured data's like images, multimedia
files, etc
The Reference Data type is used to hold pointer values which
generally stores address of other program items.

10
PL/SQL DATA TYPES(contd.)
• Most commonly used Data Types are

• CHARACTER Data Type

• NUMBER Data Type

• BOOLEAN Data Type

• DATE Data Type

• LOB Data Type

11
CHARACTER Data Type
• This data type basically stores alphanumeric characters in string format.
• The literal values should always be enclosed in single quotes while
assigning them to CHARACTER data type.
• This character data type is further classified as follows:
 CHAR Data type (fixed string size)
 VARCHAR2 Data type (variable string size)
 VARCHAR Data type
 NCHAR (native fixed string size)
 NVARCHAR2 (native variable string size)
 LONG and LONG RAW

12
NUMBER Data Type
 This data type stores fixed or floating point numbers up to 38 digits of
precision. This data type is used to work with fields which will contain only
number data
 The variable can be declared either with precision and decimal digit details
or without any restrictions.
Syntax:
A NUMBER(8,2);
B NUMBER(8);
C NUMBER;
In the above, the first declaration declares the variable 'A' is of number data
type with total precision 8 and decimal digits 2.
13
NUMBER Data Type(contd.)
• The second declaration declares the variable 'B' is of number
data type with total precision 8 and no decimal digits
• The third declaration is the most generic, declares variable 'C'
is of number data type with no restriction in precision or
decimal places. It can take up to a maximum of 38 digits.

14
BOOLEAN Data Type
• This data type stores the logical values. It represents either TRUE or
FALSE and mainly used in conditional statements. Values need not enclose
within quotes while assigning for this data type.

Syntax:
Var1 BOOLEAN;

In the above Syntax, variable 'Var1' is declared as BOOLEAN data type. The
output of the code will be either true or false based on the condition set.

15
DATE Data Type
• This data type stores the values in date format, as date, month, and year. Whenever a
variable is defined with DATE data type along with the date it can hold time
information and by default time information is set to 12:00:00 if not specified. Values
need to enclose within quotes while assigning for this data type.

newyear DATE:='01-JAN-2020';

current_date DATE:=SYSDATE;

• In the above, variable 'newyear' is declared as DATE data type and assigned the value
of Jan 1st, 2020 date.
• The second declaration declares the variable current date as DATE data type and
assigned the value with current system date.
• Both these variable holds the time information.

16
LOB Data Type
• Oracle prefers LOB instead of the a LONG data type as it is more flexible
than the LONG data type

• They can store up to the size of 128 terabytes.

Following are the different LOB data types:


 BLOB
This data type stores the LOB data in the binary file format up to the maximum
size of 128 TB. This doesn't store data based on the character set details, so that
it can store the unstructured data such as multimedia objects, images, etc.
Syntax:
Binary_data BLOB;

17
LOB Data Type(Contd.)
• CLOB and NCLOB:

CLOB data type stores the LOB data into the character set, whereas NCLOB
stores the data in the native character set. Since these data types use character
set based storage, these cannot store the data like multimedia, images, etc. that
cannot be put into a character string. The maximum size of these data types is
128 TB.
Syntax:
Charac_data CLOB;
In the above, variable 'Charac_data' is declared as CLOB data type.

18
LOB Data Type(Contd.)
• BFILE

BFILE are the data types that stored the unstructured binary format data
outside the database as an operating-system file.

The size of BFILE is to a limited operating system, and they are read-only
files and can't be modified.

19
PL/SQL Delimiters

• A delimiter is a symbol with a special meaning. Following is the list of


some of delimiters in PL/SQL

Delimiter Description
+, -, *, / Addition, subtraction/negation,
multiplication, division
% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

20
Declare Variables, identifiers , Naming conventions in
PL/SQL

• Identifiers:

Identifiers is a name that is given to a PL/SQL object. The object could be constant,
variable, exception, cursors, procedures, function, package, trigger, object type,
reserve word or label.

• Properties of Identifiers:
 Must start with a letter
 Maximum size is limited to 30 letters
 Cannot contain whitespace characters
 Can contain dollar sign ('$'), underscore ('_') and hash sign ('#')
 Is case-insensitive

21
Declare Variables, identifiers , Naming conventions in
PL/SQL(contd.)

• Naming Conventions of Identifiers:

The commonly used naming conventions in PL/SQL


 The first letter should be used to specify the declared level of the variable.
 The below 'P‘, 'L‘, 'G‘ give the different first letters and their declarative
level
 'P‘– Variable is declared at the parameter level
'L' – Variable is declared at the local block
'G‘– Variable is declared at the global level

22
Declaration of Variables
Declaration of variables:
• Variables are mainly used to store data during the data manipulation or data
processing.
• They need to be declared before using them inside the program.
• This declaration needs to be done in the declarative section of the PL/SQL
blocks.
• Declaration of variables is a process of assigning the name to the placeholder
and associate the same with a valid data type.
Syntax :
<variable name> <data type>;
The above syntax shows how to declare the variable in the declarative section.
23
Data storing in Variables
• Once the variable is declared, they are ready to hold the data of defined type. The
values of these variables can be assigned either in execution section or at the time
of declaring itself.
Syntax: variable_name data type := default_value;
The above syntax shows how to declare the variable and assign value in the
declarative section.
Syntax:
variable_name data type;
variable name := value;

The above syntax shows how to assign the value to an already declared variable.

24
Example
Explanation of example:
 Code line 2: Declaring the variable
'lv_name' of VARCHAR2 with size 50.
 Code line 3: Declaring the variable
DECLARE
'lv_name_2' of VARCHAR2 with size 50 and lv_name VARCHAR2(50);
assigned the default value using literal lv_name_2 VARCHAR2(50) := ‘WAFA';
‘WAFA'. BEGIN
 Code line 5: Value for variable 'lv_name' has lv_name := lv_name_2;
dbms_output .put_line(lv_name);
been assigned from the variable 'lv_name_2'. END ;
 Code line 6: Printing the stored value of /
variable 'lv_name'.
When the above code is executed, you will get
the following output.
Output: WAFA

25
PL/SQL BLOCK
 In a PL/SQL program, code is written in blocks. Each PL/SQL block has 3
sections, which are:
 Declare section
 Begin section
 Exception section

Followed by END / statement at the end.


 PL/SQL block creates the structured logical blocks of code that describes the
process to be executed. Such a block consists of SQL statements and PL/SQL
instructions that are then passed to the oracle engine for execution.

26
PL/SQL Block STRUCTURE

 PL/SQL block has the following structure:


DECLARE
Declaration statements
BEGIN
Executable statements
EXCEPTION
Exception-handling statements
END;
/
27
DECLARATION SECTION

 The declaration section is the first section of the PL/SQL block


 This section starts with the keyword DECLARE. It is an optional section
and defines all variables, cursors, subprograms, and other elements to be
used in the program.

Example:

DECLARE
v_first_name VARCHAR2(35) ;
v_last_name VARCHAR2(35) ;
v_counter NUMBER := 0 ;

28
EXECUTABLE SECTION

 This section is enclosed between the keywords BEGIN and END and it is a
mandatory section.
 This section contains executable statements that allow you to manipulate
the variables that have been declared in the declaration section

BEGIN
SELECT first_name, last_name
INTO v_first_name, v_last_name
FROM student
WHERE student_id = 123 ;
DBMS_OUTPUT.PUT_LINE
(‘Student name :’ || v_first_name ||‘ ’|| v_last_name);
END;
/
29
EXCEPTION HANDLING SECTION

 This section starts with the keyword EXCEPTION.


 This optional section contains exception(s) that handle errors in the
program.

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE
(‘ There is no student with student id 123 ’);
END;

30
Anonymous PL/SQL Blocks

 PL/SQL blocks are a part of large programs and are either sub-programs, or
functions, or procedures, or triggers etc., but they can be defined independently
and can be executed as well.
When PL/SQL block is defined with no header , it is known as Anonymous Block

Example:
DECLARE
-- declare variable a and b Output:
-- and these variables have integer datatype 84
a number;
b number;
BEGIN
a:= 7;
b:= 77;
dbms_output.put_line('Sum of the number is: ' || a + b);
END;
/ 31
The PL/SQL Comments

 The PL/SQL supports single-line and multi-line comments. All characters


available inside any comment are ignored by the PL/SQL compiler.
 The PL/SQL single-line comments start with the delimiter -- (double
hyphen) and multi-line comments are enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/

32
Example

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be
nested within other PL/SQL blocks using BEGIN and END. Following is the
basic structure of a PL/SQL block −

DECLARE
message varchar2(20):= 'Hello World!';
BEGIN
dbms_output.put_line(message);
END;
/

33
Example

 The end; line signals the end of the PL/SQL block


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

Hello World
PL/SQL procedure successfully completed.

34
Oracle PL/SQL IF THEN ELSE Statement: ELSIF,
NESTED-IF
 Decision making statements are those who will decide the
flow-control of SQL statements based on the conditions.
 PL/SQL programming language provides following types of
decision-making statements
 If Statement
 If...then...else statement
 If...then...elsif...else statement
 Case Statement
 Searched Case Statement

35
PL/SQL: if Statement

36

 The if statement, or the if...then statement can be used when


there is only a single condition to be tested
Syntax:
if <test_condition> then
body of action
end if;

36
Example : if Statement

set serveroutput on;


DECLARE
x int:=10;
y int:=80;
BEGIN
if(y>x) then
dbms_output.put_line('Result: ' ||y|| ' is greater than ' ||x);
end if;
END;
/
Output: Result: 80 is greater than 10
PL/SQL procedure successfully completed.

37
PL/SQL: if...then...else statement

 The IF-THEN-ELSE statement is mainly used to select


between two alternatives based on the condition.
Syntax:
if <test_condition> then
statement 1/set of statements 1
else
statement 2/set of statements 2
end if;

38
Example if...then...else

set serveroutput on;


DECLARE
x int;
BEGIN x := &x;
if mod(x,2) = 0 then
dbms_output.put_line('Even Number');
else
dbms_output.put_line('Odd Number');
end if;
END;
/ Output:
Enter value for x:6
Even Number
PL/SQL procedure successfully completed.

39
PL/SQL: if...then...elsif...else statement

 The IF-THEN-ELSIF statement is mainly used where one alternative should be chosen from a set
of alternatives, where each alternative has its own conditions to be satisfied.
 The IF-THEN-ELSIF statement may contain 'ELSE' block in it. This 'ELSE' block will be executed if
none of the conditions is satisfied.
Syntax for IF-THEN-ELSIF Statements:
if <test_condition1> then
body of action
elsif <test_condition2>then
body of action
elsif<test_condition3>then
body of action
...
....
else body of action
end if;
.
40
Example: if...then...elsif...else statement

set serveroutput on;


DECLARE
a int;
Output:
b int; Enter value for a: 8
BEGIN Enter value for b: 5
a := &a; a is greater than b
PL/SQL procedure successfully completed.
b := &b;
if(a>b) then
dbms_output.put_line(‘a is greater than b’);
elsif(b>a) then
dbms_output.put_line(‘b is greater than a’);
else
dbms_output.put_line(‘Both a and b are equal’);
end if;
END;
/

41
PL/SQL: Case Statement

 The CASE statement selects one sequence of statements to


execute.
Syntax:
CASE selector
when value1 then Statement1;
when value2 then Statement2;
...
...
else statement;
end CASE;

42
Example: Case Statement

set serveroutput on;


DECLARE
a int;
b int; Output:
Enter the value for a:7
BEGIN Odd number
a := &a; PL/SQL procedure successfully completed.
b := mod(a,2);
CASE b
when 0 then dbms_output.put_line('Even Number');
when 1 then dbms_output.put_line('Odd Number');
else dbms_output.put_line('User has not given any input value to check');
END CASE;
END;
/

43
PL/SQL: Searched Case Statement

 The searched CASE statement has no selector, and it's WHEN clauses
contain search conditions that yield Boolean values.
Syntax:
CASE
when <test_condition1> then statement1;
when <test_condition2> then statement2;
...
...
else default statement;
end case;

44
Example: Searched Case Statement

set serveroutput on;


DECLARE
dt Date; Output:
Enter the value for dt:28-APR-2019
str varchar2(10); Weekend date
BEGIN PL/SQL procedure successfully completed.

dt := '&dt';
str := to_char(dt,'DY');
CASE
when str in ('SAT','SUN') then dbms_output.put_line('Its the Weekend');
else dbms_output.put_line('Not a Weekend');
END CASE;
END;
/ 45
PL/SQL Loops

Loops in PL/SQL provides a way of repeating a particular part of any program


or any code statement as many times as required.
 In PL/SQL we have three different loop options

 Basic Loop
 While Loop

 For Loop

46
Slide
8- 47
PL/SQL Loops
 Basic Loop:
 Basic loop or simple loop is preferred in PL/SQL code when there
is no surety about how many times the block of code is to be
repeated
 Simple loop always begins with the keyword LOOP and ends with
a keyword END LOOP.
 A basic/simple loop can be terminated at any given point by using
the exit statement or by specifying certain condition by using the
statement exit when.

47
PL/SQL: Basic Loop(Example)
Syntax:
LOOP
sequence of statements
END LOOP;
Example:
set serveroutput on; Output:
1
DECLARE 2
i int; 3
BEGIN 4
5
i := 1; 6
LOOP 7
if i>10 then 8
9
exit; 10
end if; PL/SQL procedure successfully completed
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
/
48
PL/SQL : While Loop

 It is an entry controlled loop which means that before


entering in a while loop first the condition is tested, if the
condition is TRUE the statement or a group of statements get
executed and if the condition is FALSE the control will move
out of the while loop.
Syntax:
WHILE <test_condition> LOOP
<action>
END LOOP;

49
Example: While Loop

Example:
Output:
set serveroutput on; 1
DECLARE 3
5
num int:=1; 7
9
BEGIN
PL/SQL procedure successfully completed.
while(num <= 10) LOOP
dbms_output.put_line(''|| num);
num := num+2;
END LOOP;
END;/

50
PL/SQL : For Loop

 This loop is used when some statements in PL/SQL


code block are to be repeated for a fixed number of
times.
Syntax:
FOR counter variable IN start_value..end value LOOP
statement to be executed
END LOOP;

51
Example: For Loop

set serveroutput on;


BEGIN Output:
1
FOR l_counter IN 1..10 2
3
LOOP 4
DBMS_OUTPUT.PUT_LINE( l_counter ); 5
6
END LOOP; 7
8
END; 9
/ 10
PL/SQL procedure
successfully completed.

52
PL/SQL : Array- VARRAY

 In PL/SQL we have a varray named data structure which is a variable size


array which can be used to store a fixed size of data elements of same
type.

 A varray stores data in contiguous memory locations where the first


element is stored at the lowest address location and the last element is
stored at the highest address location.

53
PL/SQL : Array- VARRAY

 To access the data elements stored in a varray type variable, we use the
syntax variable_name(index) where index starts from 1 for the first element and
goes up to the current upper bound of elements which means the number of
elements that exists at that given point(not the maximum size of the array).
 The upper bound keeps on changing as you add or remove elements from an array,
but it cannot exceed the maximum size of the array.
Example:
In the Below diagram below we have a varray Marks of size 8 and 5 data elements
are stored in it.

54
Varray

 In the above varray Marks if you want to access the second


element, all you need to do it Marks(2)
 The database stores a varray variable as a single object. If a

varray variable is less than 4 KB, it resides inside the table of


which it is a column; otherwise, it resides outside the table
but in the same tablespace.
Declaring a Varray Type:
 A new varray type can be declared using the TYPE statement

inside the PL/SQL block.


TYPE varr_type_name IS VARRAY(number of elements ) of <element_data_type>

55
Example : Varray

56
Example: Varray

 In the above example, we have declared two varray types one for storing student
names and another on for storing student's marks
 And then we have used them in our PL/SQL block for storing student names and
student marks.

57
PL/SQL: Stored Procedure

 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
Syntax:
CREATE OR REPLACE PROCEDURE
<procedure_name>
(
<parameterl IN/OUT <datatype>
..
.)
[ IS | AS ] <declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
/
58
Example: Stored procedure

set serveroutput on;


CREATE OR REPLACE PROCEDURE Sum(a IN number, b IN
number) IS c number;
BEGIN
c := a+b;
dbms_output.put_line('Sum of two nos= '|| c);
END Sum;
/

Output:
Procedure created

59
Example: Stored Procedure

For calling the procedure created following code will be executed:

set serveroutput on;


DECLARE
x number;
y number;
BEGIN OUTPUT:

x := &x; Enter value for x: 10


Enter value for y: 20
y := &y; Sum of two nos= 30
Sum(x,y); PL/SQL procedure successfully created.

END;
/

60
PL/SQL : Function

 Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions


have a unique name by which it can be referred.
Characteristics of Functions:
 Functions are a standalone block that is mainly used for calculation purpose.
 Function use RETURN keyword to return the value, and the data type 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 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.

61
PL/SQL : Function

 These parameters should be included in the calling statement.


 Function can also return the value through OUT parameters other than
using RETURN.

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

62
Example: Function

set serveroutput on;


CREATE OR REPLACE FUNCTION Sum(a IN number, b IN number) RETURN
Number IS c number;
BEGIN
c := a+b;
RETURN c;
END;
/
Output: Function Created

63
Example : Function

For calling the function Sum following code will be executed:


set serveroutput on;
DECLARE
no1 number;
no2 number; Output:
result number; Enter value for no1 :5
Enter value for no2 :5
BEGIN Sum of two nos=10
no1 := &no1; PL/SQL procedure successfully created.
no2 := &no2;
result := Sum(no1,no2);
dbms_output.put_line(‘Sum of two nos=’||result);
END;
/

64
Triggers

 Triggers in oracle are blocks of PL/SQL code which oracle


engine can execute automatically based on some action or
event.
 Triggers are automatically and repeatedly called upon by
oracle engine on satisfying certain condition.
 Triggers can be activated or deactivated depending on the
requirements.
 If triggers are activated then they are executed implicitly by
oracle engine and if triggers are deactivated then they are
executed explicitly by oracle engine

65
PL/SQL: Parts of Trigger

66

 Whenever a trigger is created, it contains the following three sequential parts:


Triggering Event or Statement:
 The statements due to which a trigger occurs is called triggering event or
statement. Such statements can be DDL statements, DML statements or any
database operation, executing which gives rise to a trigger.
Trigger Restriction:
 The condition or any limitation applied on the trigger is called trigger restriction.
Thus, if such a condition is TRUE then trigger occurs otherwise it does not occur.
Trigger Action:
 The body containing the executable statements that is to be executed when
trigger occurs that is with the execution of Triggering statement and upon
evaluation of Trigger restriction as True is called Trigger Action.

66
PL/SQL: Types of Trigger

 The Triggers can be classified into three categories:


• Level Triggers
• Event Triggers
• Timing Triggers
 Level Triggers:

There are 2 different types of level triggers, they are:


 ROW LEVEL TRIGGERS: It fires for every record that got affected with the
execution of DML statements like INSERT, UPDATE, DELETE etc. It always
use a FOR EACH ROW clause in a triggering statement.
 STATEMENT LEVEL TRIGGERS: It fires once for each statement that is
executed.

67
PL/SQL: Types of Triggers

 Event Triggers:
There are 3 different types of event triggers, they are:
• DDL EVENT TRIGGER: It fires with the execution of every DDL
statement(CREATE, ALTER, DROP, TRUNCATE).
• DML EVENT TRIGGER: It fires with the execution of every DML
statement(INSERT, UPDATE, DELETE).
• DATABASE EVENT TRIGGER: It fires with the execution of every
database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.

68
PL/SQL: Types of Triggers

 Event Triggers:
There are 3 different types of event triggers, they are:
• DDL EVENT TRIGGER: It fires with the execution of every DDL
statement(CREATE, ALTER, DROP, TRUNCATE).
• DML EVENT TRIGGER: It fires with the execution of every DML
statement(INSERT, UPDATE, DELETE).
• DATABASE EVENT TRIGGER: It fires with the execution of every
database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.

69
PL/SQL: Types of Triggers

 Timing Triggers:
There are 2 different types of timing triggers, they are:
 BEFORE TRIGGER: It fires before executing DML

statement. Triggering statement may or may not


executed depending upon the before condition block.
 AFTER TRIGGER: It fires after executing DML

statement.

70
Trigger: Syntax and Example

Syntax for creating Triggers:


CREATE OR REPLACE TRIGGER <trigger_name>
BEFORE/AFTER/INSTEAD OF
INSERT/DELETE/UPDATE ON <table_name>
REFERENCING (OLD AS O, NEW AS N)
FOR EACH ROW WHEN (test_condition)
DECLARE
-- Variable declaration;
BEGIN
-- Executable statements;
EXCEPTION
-- Error handling statements;
END <trigger_name>;
END;
/
71
PL/SQL: Syntax and Example

Where
CREATE OR REPLACE TRIGGER is a keyword used to create a trigger and <trigger_name> is user-
defined where a trigger can be given a name.
BEFORE/AFTER/INSTEAD OF specify the timing of the trigger's occurrence.
INSTEAD OF is used when a view is created.
INSERT/UPDATE/DELETE specify the DML statement.
<table_name> specify the name of the table on which DML statement is to be applied.
REFERENCING is a keyword used to provide reference to old and new values for DML statements.
FOR EACH ROW is the clause used to specify row level trigger.
WHEN is a clause used to specify condition to be applied and is only applicable for row-level
trigger.
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.

72
Example: Trigger

CREATE OR REPLACE TRIGGER CheckAge


BEFORE
INSERT OR UPDATE ON student
FOR EACH ROW
BEGIN
IF :new.Age>30 THEN
raise_application_error(-20001, 'Age should not be greater than 30');
END IF;
END;
/

Output:
Trigger created

73
Example: Trigger

Following is the STUDENT table,


ROLL NO SNAM AGE COURSE
E

11 ALIYA 20 B.SC

12 Hanan 21 B.SC

13 Fatima 18 B.C.A

14 Hana 20 B.D.S

15 Nihal 19 M.D.S

74
Example: Trigger

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.
 Example 1:
INSERT into STUDENT values(16, 'Saina', 32, 'BCOM');

Output: Age should not be greater than 30


 Example 2:
INSERT into STUDENT values(17, 'Anna', 22, 'BCOM');

Output: 1 row created

75
Example: Trigger

76

 Example 3:
UPDATE STUDENT set age=31 where ROLLNO=12;

Output: Age should not be greater than 30

 Example 4:
UPDATE STUDENT set age=23 where ROLLNO=12;

Output: 1 row updated.

76
Reference

 Oracle-PL/SQL User’s Guide and References-


TomPortfolio,John Russell
 Oracle PL/SQL by Example-Fourth Edition

77

You might also like