What Is PL
What Is PL
Basics
Anbarasu Dhanapal
AAA PRIVATE LTD.
Table of Contents
1. What is PL/SQL? .................................................................................................................................. 4
2. What do you mean by PL/SQL Architecture? ......................................................................................4
3.Blocks in PL/SQL ................................................................................................................................... 5
4.PL/SQL | User Input ..............................................................................................................................8
5.PL/SQL Control Flow ...........................................................................................................................10
5.1 IF THEN in PL/SQL - Decision Making in PL/SQL .................................................................10
5.2 CASE Statement in PL/SQL ................................................................................................. 18
5.3 PL/SQL GOTO Statement ....................................................................................................23
5.4 PL/SQL NULL Statement ..................................................................................................... 26
6. PL/SQL LOOPS and EXIT Statement ...................................................................................................28
6.1 FOR LOOP in PL/SQL ........................................................................................................... 33
6.2 PL/SQL NESTED FOR LOOP ................................................................................................. 35
6.3 Using the REVERSE Keyword in a PL/SQL FOR Loop .......................................................... 37
6.4 PL/SQL While Loop ............................................................................................................. 39
6.5 PL/SQL CONTINUE Statement ............................................................................................ 41
7. PL/SQL Query .....................................................................................................................................42
8. PL/SQL Clauses .................................................................................................................................. 43
9. PL/SQL Operators .............................................................................................................................. 43
10. PL/SQL Aggregate Functions ........................................................................................................... 43
11. PL/SQL Data Constraints ..................................................................................................................43
12. PL/SQL Joining Data .........................................................................................................................44
13. PL/SQL Functions & PROCEDURES .................................................................................................. 44
13.1 Basic Query in PL/SQL procedure .....................................................................................44
13.2 PL/SQL Functions ..............................................................................................................46
13.3 Procedures in PL/SQL ....................................................................................................... 52
Advantages of Procedures .................................................................................................. 53
Disadvantages of Procedures ..............................................................................................53
Important Points About Procedures in SQL ........................................................................54
14. PL/SQL Views ................................................................................................................................... 54
15. PL/SQL Indexes ................................................................................................................................ 54
16. PL/SQL EXCEPTION HANDLERS ........................................................................................................54
16.1 Exception Handling in PL/SQL .......................................................................................... 54
16.2 RAISE_APPLICATION_ERROR: ...........................................................................................61
16.3 PL/SQL RAISE Exceptions ..................................................................................................65
16.3.1 User-Defined Exception ................................................................................................ 66
16.3.2 Internally Defined Exception .........................................................................................67
16.3.3 Current Exception ......................................................................................................... 67
16.4 Example: Using Exceptions in PL/SQL .............................................................................. 68
17. PL/SQL RECORDS & CURSORS ......................................................................................................... 71
17.1 Cursors in PL/SQL .............................................................................................................. 71
Types of Cursors in PL/SQL ...................................................................................................72
17.1.1 Explicit cursor ................................................................................................................. 72
17.2 PL/SQL Cursor Update .......................................................................................................73
Advantages ....................................................................................................................... 77
Disadvantages .................................................................................................................. 77
17.3 PL/SQL Parameterized Cursors ..........................................................................................77
17.4 PL/SQL Parameterized Cursor with Default Value ............................................................ 80
18. PL/SQL PACKAGES ........................................................................................................................... 83
18.1 PL/SQL packages ...............................................................................................................83
18.2 Package Specification .......................................................................................................83
18.3 Package Body ................................................................................................................... 84
19. PL/SQL TRIGGERS ............................................................................................................................ 90
Common Use Cases of PL/SQL Triggers ........................................................................................... 96
20. PL/SQL COLLECTIONS ...................................................................................................................... 96
Document Revision History
Reviewed
Version Date Revision Author(s) Updates
By
1.0 21-OCT-2024 1 Anbarasu Dhanapal
1. What is PL/SQL?
PL/SQL, in simple terms, is a programming language used for managing data in databases. It combines SQL
for data manipulation and procedural features for building applications. It’s like a toolkit that lets you
efficiently interact with and control your Oracle database.
PL/SQL was developed by Oracle Corporation within the early ’90s to reinforce the capabilities of
SQL. It integrates well with SQL* PLUS and other application development products of Oracle.
PL/SQL is the superset of SQL. It provides SQL data manipulation commands and SQL data types.
In PL/SQL, a block without any name is called Anonymous Block
PL/ SQL block consists of various functions, library, procedures, trigger, packages etc.
The following points should be remembered while writing a PL/SQL program
In PL/SQL the semicolon (;) is placed at the end of an SQL statement or PL/SQL control statement.
Section keyword DECLARE, BEGIN and EXCEPTION are not followed by semicolons.
END keyword and all other PL/SQL statements require a semicolon to terminate the statements.
Use the COMMIT and ROLLBACK instructions to provide proper transaction management.
The PL/SQL runtime system is a technology and not an independent product. This technology is
actually like an engine that exhibits PL/SQL blocks, subprograms like functions and procedures. This engine
can be installed in an Oracle Server or in application development tools such as Oracle Form Builder, Oracle
Reports Builder etc.
PL/SQL Architecture
Features of PL/SQL :
These two environments are independent of each other. In either environment, the PL/SQL engine
accepts any valid PL/SQL block as input. The PL/SQL engine executes the procedural part of the statements
and sends the SQL statement executer in the Oracle Server. A single transfer is required to send the block
from the application to the Oracle Server, thus improving performance, especially in a Client-Server network.
PL/SQL code can also be stored in the Oracle server as subprograms that can be referenced by any number
of applications connected to the database.
Advantages of PL/SQL :
PL/SQL provides better performance.
PL/SQL has high Productivity.
It supports Object-Oriented Programming concepts.
It has Scalability and Manageability.
PL/SQL supports various Web Application Development tools.
Disadvantages of PL/SQL :
PL/SQL requires high memory.
Lacks of functionality debugging in stored procedures.
3.Blocks in PL/SQL
In PL/SQL, All statements are classified into units that is called Blocks. PL/SQL blocks can include
variables, SQL statements, loops, constants, conditional statements and exception handling. Blocks can also
build a function or a procedure or a Package.
The Declaration section: Code block start with a declaration section, in which memory variables,
constants, cursors and other oracle objects can be declared and if required initialized.
The Begin section: Consist of set of SQL and PL/SQL statements, which describe processes that have
to be applied to table data. Actual data manipulation, retrieval, looping and branching constructs
are specified in this section.
The Exception section: This section deals with handling errors that arise during execution data
manipulation statements, which make up PL/SQL code block. Errors can arise due to syntax, logic
and/or validation rule.
The End section: This marks the end of a PL/SQL block.
Broadly, PL/SQL blocks are two types: Anonymous blocks and Named blocks are as follows:
1. Anonymous blocks:
In PL/SQL, That’s blocks which is not have header are known as anonymous blocks. These blocks do
not form the body of a function or triggers or procedure. Example: Here a code example of find greatest
number with Anonymous blocks.
DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/
-- Program End
Output:
That’s PL/SQL blocks which having header or labels are known as Named blocks. These blocks can
either be subprograms like functions, procedures, packages or Triggers. Example: Here a code example of
find greatest number with Named blocks means using function.
DECLARE
DECLARE
a number;
b number;
c number;
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 10;
b:= 100;
c := findMax(a, b);
END;
-- Program End
Output:
Maximum number in 10 and 100: 100
In PL/SQL, user can be prompted to input a value using & character. & can be used to prompt input
for different data types. Consider, following table:
likes number(4))
Table created.
1 row created.
1 row created.
SQL> insert into GFG values(3, 'ria', 40);
1 row created.
id author likes
1 sam 10
2 maria 30
3 ria 40
2. Text value
1. Numeric value –
Syntax:
&value
id author likes
2 maria 30
2.Text Value –
& can also be used to input text values from the user.
Syntax:
'&value'
5.PL/SQL Control Flow
PL/SQL Control Flow refers to the logical order in which statements are executed in a PL/SQL program.
Mastering these statements ensures your PL/SQL code executes efficiently, follows a clear path, and
responds dynamically to various conditions.
IF THEN in PL/SQL
CASE in PL/SQL
GOTO Statement in PL/SQL
NULL Statement in PL/SQL
Decision-making statements in programming languages decide the direction of the flow of program
execution. Conditional Statements available in PL/SQL are defined below:
1. IF THEN
2. IF THEN ELSE
3. NESTED-IF-THEN
4. IF THEN ELSIF-THEN-ELSE Ladder
1. IF THEN
IF THEN the statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
if condition then
-- do something
end if;
Here, condition after evaluation will be either true or false. if statement accepts boolean values – if
the value is true then it will execute the block of statements below it otherwise not. if and endif consider as
a block here.
Example:
1.
declare
begin
if condition then
dbms_output.put_line('output');
end if;
dbms_output.put_line('output2');
end;
2.
-- pl/sql program to illustrate If statement
declare
begin
dbms_output.put_line('num1 small');
end if;
end;
As the condition present in the if statement is false. So, the block below the if statement is not executed.
Output:
I am Not in if
2. IF THEN ELSE
The if statement alone tells us that if a condition is true it will execute a block of statements and if
the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:-
if (condition) then
-- Executes this block if
-- condition is true
else
-- Executes this block if
-- condition is false
Example:-
SQL
declare
begin
dbms_output.put_line('i am in if block');
ELSE
end if;
end;
Output:-
i'm in if Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the if statement is
false after calling the statement which is not in block(without spaces).
3. NESTED-IF-THEN
A nested if-then is an if statement that is the target of another if statement. Nested if-then
statements mean an if statement inside another if statement. Yes, PL/SQL allows us to nest if statements
within if-then statements. i.e, we can place an if then statement inside another if then statement.
Syntax:-
if (condition1) then
-- Executes when condition1 is true
if (condition2) then
-- Executes when condition2 is true
end if;
end if;
Example:
SQL
declare
begin
end if;
end if;
end;
Output:-
Here, a user can decide among multiple options. The if then statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
endif
Flow Chart:-
Example
SQL
declare
begin
dbms_output.put_line('both equal');
ELSE
dbms_output.put_line('num2 greater');
end if;
end;
Output:-
num1 small
after end if
CASE statement gives you a clear way to handle conditional logic within PL/SQL blocks. It is
a conditional control statement that allows you to execute different blocks of code based on the specified
conditions. It is particularly useful when dealing with multiple conditions and provides a more readable and
maintainable alternative to nested IF-ELSE statements.
Syntax:
CASE
...
ELSE
-- default code block
END CASE;
The syntax starts with the keyword CASE, followed by multiple WHEN clauses that specify
conditions. If a condition evaluates as true, the corresponding code block is executed. If none of the
conditions are met, the ELSE clause (optional) provides a default action.
Example:
DECLARE
day_number NUMBER := 1;
day_name VARCHAR2(20);
BEGIN
CASE day_number
WHEN 1 THEN
day_name := 'Monday';
WHEN 2 THEN
day_name := 'Tuesday';
WHEN 3 THEN
day_name := 'Wednesday';
WHEN 4 THEN
day_name := 'Thursday';
WHEN 5 THEN
day_name := 'Friday';
WHEN 6 THEN
day_name := 'Saturday';
WHEN 7 THEN
day_name := 'Sunday';
ELSE
END CASE;
END;
In this example,
The variable day_number is set to 1 that representing Monday.
The Simple CASE statement then checks the value of day_number and assigns the corresponding day
name to the variable day_name.
The output will be The day is: Monday
Output:
Statement processed.
In a Searched CASE statement, each condition is evaluated independently. It allows for more
complex conditions such as comparisons, logical operators, and functions.
Example:
DECLARE
product_category VARCHAR2(20);
BEGIN
CASE
ELSE
END CASE ;
END;
In this example,
The variable product_price is set to 120.50.
The Searched CASE statement evaluates different conditions based on the value of product_price and
assigns the appropriate category to the variable product_category.
The output will be The product falls into the category: High Cost.
Output:
Statement processed.
The product falls into the category: High Cost
It is limited to PL/SQL blocks such as procedures, It is primarily used within SQL statements like
functions, and blocks. SELECT, WHERE, and ORDER BY clauses.
It supports both Simple CASE and Searched CASE. It only supports Searched CASE.
Both Simple and Searched CASE statements support an optional ELSE clause to handle situations where
no conditions are met.
CASE statement controls procedural logic within PL/SQL, while CASE expression is used within SQL
queries like SELECT, WHERE, and ORDER BY.
It is primarily used within PL/SQL procedural blocks but not in standalone SQL queries unless it is a CASE
expression.
CASE statements are used for decision-making within PL/SQL blocks, such as stored procedures,
functions, and triggers.
The GOTO statement within PL/SQL serves as a programming feature instructing a program to shift
control to a designated portion of code identified by a label. Usually, this label denotes a distinct line or
block of code within the program. Upon encountering the GOTO statement during program execution, the
control flow skips to the labelled position, enabling the code to resume execution from that particular
point
GOTO Statements Work.
Labelling: Programmers typically place labels at specific points in their code, marking particular
locations or sections for better understanding for jumping.
Execution Flow: Upon encountering a GOTO statement, the program immediately redirects its
execution to the line or block of code identified by the label. This non-sequential execution can make
the code harder to comprehend and follow for the programmer.
Control Flow Considerations: Excessive use of GOTO statements can result in what’s termed “spaghetti
code,” where the flow of execution becomes convoluted, making it challenging to trace. Debugging and
maintaining such code becomes more difficult as the program’s 23ehaviour becomes less predictable.
Modern Practices: Most contemporary programming languages discourage or completely avoid GOTO
statements due to their potential to generate intricate and error-prone code. Instead, structured
programming constructs like loops, conditional statements (if-else), and functions/methods are
preferred. These constructs offer improved readability, maintainability, and control flow without relying
on unconditional jumps.
Exceptions: Despite the overall discouragement of GOTO statements, specific scenarios, such as error
handling in certain languages or low-level programming, might still necessitate the judicious use of
GOTO-like constructs.
The GOTO statement in PL/SQL allows for an unconditional transfer of control within the same subprogram
to a labeled statement. Its syntax is as follows:
Syntax:
GOTO label;
…
…
<< label >>
statement;
Restrictions with the GOTO Statement
DECLARE
a NUMBER := 1;
BEGIN
<<my_label>>
-- Displaying values from 1 to 5
WHILE a <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Value of a: ' || a);
a := a + 1;
IF a = 4 THEN
GOTO my_label; -- Redirects control to the label 'my_label'
END IF;
END LOOP;
END;
Output
Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
Value of a: 5
Code Explanation
This PL/SQL block initializes The variable a with a value of 1.
It enters a loop that will display the value of a and increment it by 1 in each iteration.
Within the loop, there is an IF condition that checks if a equals 4. When a is 4, it triggers the GOTO
statement.
The GOTO statement redirects the program flow back to the labeled statement <<my_label>>,
effectively restarting the loop.
The loop continues until a reaches 5.
Example
DECLARE
num NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Welcome to the Program');
num := -2;
<<end_of_program>>
DBMS_OUTPUT.PUT_LINE('End of the Program');
END;
Output:
The NULL statement works like a stand-in within PL/SQL code. It’s needed by the syntax but doesn’t
do any particular job. It shows that no specific code has to run at that moment. This helps keep the
code in good shape when a statement is a must but the statement does not need to take actual
action.
In exception handling also this NULL statement tells us that we don’t have to do anything special
for certain problems. It’s like a little note saying, “No need to handle this one especially.”
Basic Syntax of PL/SQL Null Statement
The basic syntax of the NULL statement in PL/SQL is very simple. It’s just the keyword NULL followed by a
semicolon (;).
— Some PL/SQL code executing other statements
— The NULL statement used as a placeholder
NULL;
— More PL/SQL code
END;
Example :
DECLARE
x INT := 3;
BEGIN
IF x > 5 THEN
DBMS_OUTPUT.PUT_LINE('x is greater than 5');
ELSE
NULL; -- The NULL statement does nothing in the ELSE block
END IF;
END;
In PL/SQL, a NULL statement can act as a placeholder for the program , indicating that no particular
action is needed to perform. When incorporated into exception handling, this NULL statement within
the EXCEPTION block signifies that no specific action is required to address a certain error situation.
BEGIN
-- Some operations or code execution
Output:
PL/SQL LOOP
PL/SQL FOR LOOP
PL/SQL WHILE Loop
PL/SQL CONTINUE Statement
PL/SQL provides a robust environment for database programming, allowing developers to create powerful
and efficient code for Oracle databases.
Syntax
LOOP
END LOOP;
EXIT Statement
The EXIT statement is used to break the loop whether the loop condition has been satisfied or not.
This statement is particularly useful when you want to terminate the loop based on certain conditions
within the loop block.
Syntax
LOOP
-- Code block
IF condition THEN
EXIT;
END IF;
END LOOP;
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
IF counter = 3 THEN
EXIT;
END IF;
counter := counter + 1;
END LOOP;
END;
/
Output:
Statement processed.
Code Explanation:
Initially counter variable is set to 1.
The LOOP statement repeatedly executes the code block within it.
Inside the loop, DBMS_OUTPUT.PUT_LINE is used to print Iteration number (value of counter).
The counter is incremented by 1 in each iteration.
IF statement is executed when the value of counter will become 3 and The EXIT statement is
executed and loop stops.
LOOP
-- Code block
END LOOP;
DECLARE
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('GeeksForGeeks');
EXIT WHEN counter > 5; -- Exit the loop when counter exceeds 5
END LOOP;
END;
Output:
Statement processed.
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Code Explanation:
Initially counter variable is set to 1.
The LOOP statement repeatedly executes the code block within it.
Inside the loop, DBMS_OUTPUT.PUT_LINE is used to print “GeeksForGeeks”.
The counter is incremented by 1 in each iteration.
The EXIT WHEN statement is executed when the loop when the counter exceeds 5.
Nested Loops
Nested Loop is a Loop inside Loop and PL/SQL supports nested loops that allows you to have multiple levels
of iteration within a program. This is achieved by placing one or more LOOP statements inside another. Each
nested loop has its own set of loop control statements.
Syntax
-- Outer Loop
LOOP
-- Code block
-- Inner Loop
LOOP
END LOOP;
END LOOP;
DECLARE
outer_counter NUMBER := 1;
inner_counter NUMBER := 1;
BEGIN
END LOOP;
END LOOP;
END;
Output:
Statement processed.
Explanation:
There are two nested loops
The outer FOR loop (FOR outer_counter IN 1..3 LOOP) runs three times.
Inside the outer FOR loop, there is an inner FOR loop (FOR inner_counter IN 1..2 LOOP) that runs two
times for each iteration of the outer loop.
DBMS_OUTPUT.PUT_LINE statements is used to print output.
It has block structure programming features. With PL/SQL, you can fetch data from the table, add
data to the table, make decisions, perform repetitive tasks, and handle errors.PL/SQL supports SQL queries.
To fetch records, process data, or execute complex calculations, the FOR loop helps to efficiently iterate
over a range of values or collections.
Along with SQL queries PL/SQL supports looping. FOR loop is a type of control statement. It is used
to perform repetitive tasks. It is used to execute the set of statements for a specific number of times. To
execute for loop, start and end values are provided. During each iteration counter is incremented by 1.
Syntax:
DECLARE
loop_varaible datatype;
BEGIN
set of statements
END LOOP;
END;
The loop_variable automatically increments by 1 in each iteration, and the loop continues until it reaches
the end_value. There’s no need to declare the loop variable separately unless needed elsewhere in the
program
Example:
Query:
DECLARE
counter NUMBER;
BEGIN
END LOOP;
END;
Output:
Code Explanation:
SET SERVEROUTPUT ON is used to enable output in Oracle SQL*Plus or other tools.
The loop variable counter is automatically initialized and used within the loop to print numbers
from 1 to 5.
The FOR loop iterates over the range from 1 to 5 and displays the output
using DBMS_OUTPUT.PUT_LINE.
Syntax
BEGIN
--outer loop
FOR loop_variable1 IN start_value1 ..end_value1 LOOP
--inner loop
--set of statements
END LOOP;
END LOOP;
END;
Query:
BEGIN
DBMS_OUTPUT.PUT( counter1);
END LOOP;
DBMS_OUTPUT.NEW_LINE;
END LOOP;
END;
Output:
Code Explanation:
The outer loop runs three times, and for each iteration of the outer loop, the inner loop runs three
times, printing the values from 1 to 3.
DBMS_OUTPUT.NEW_LINE is used to move to a new line after the inner loop finishes.
Syntax
BEGIN
FOR loop_variable IN REVERSE start_value .. end_value LOOP
set_of_statements
END LOOP;
END;
/
DECLARE
counter NUMBER;
BEGIN
END LOOP;
END;
Output:
Explanation:
The REVERSE keyword is used to reverse the iteration, starting from 5 and decrementing to 1.
The loop prints the numbers in descending order.
The ‘WHILE LOOP’ is used when you are not sure about the number of times the code block needs
to execute. Only during the WHILE Loop execution, the specific condition set to end the execution is made
TRUE and the control moves out of the WHILE Loop statement.
Syntax:
WHILE condition
LOOP
— Statements to be executed as long as the condition is true
END LOOP;
Example 1:
DECLARE
counter NUMBER := 1; -- Initialize a counter variable
BEGIN
-- Start the WHILE loop
WHILE counter <= 5 -- Condition to check
LOOP
-- Statements to be executed as long as the condition is true
DBMS_OUTPUT.PUT_LINE('Counter value: ' || counter);
DECLARE: This section is used to declare variables. In this example, we declare a variable named
counter and initialize it to 1.
BEGIN: Marks the beginning of the executable section.
WHILE Loop: The WHILE loop is used to repeatedly execute the block of statements as long as the
specified condition (counter <= 5) is true.
LOOP: Marks the beginning of the loop block.
DBMS_OUTPUT.PUT_LINE: This statement is used to display output in the console. In this example, it
prints the current value of the counter variable.
Increment Counter: The counter variable is incremented by 1 in each iteration.
END LOOP: Marks the end of the loop block.
END; Marks the end of the executable section.
In the above example, the WHILE loop will iterate as long as the counter is less than or equal to 5.
Output:
Statement processed.
Counter value: 1
Counter value: 2
Counter value: 3
Counter value: 4
Counter value: 5
Example 2:
DECLARE
total_sum NUMBER := 0; -- Initialize a variable to store the sum
current_number NUMBER := 1; -- Initialize a variable for the loop
BEGIN
-- Start the WHILE loop with EXIT WHEN statement
WHILE total_sum < 10
LOOP
-- Add the current number to the total sum
total_sum := total_sum + current_number;
In the above example, the loop continues as long as the total_sum is less than 10. The loop adds the
current_number to the total_sum in each iteration and increments the current_number. The loop will exit
when the total_sum becomes greater than or equal to 10.
Output:
Statement processed.
Current Number: 1
Total Sum: 1
Current Number: 2
Total Sum: 3
Current Number: 3
Total Sum: 6
Current Number: 4
Total Sum: 10
Syntax:
CONTINUE;
Example:
DECLARE
i NUMBER := 1;
BEGIN
LOOP
IF i = 3 THEN
i := i + 1;
CONTINUE;
END IF;
i := i + 1;
END LOOP;
END;
When the above code is executed in SQL prompt, it produces the following output.
Output:
Current Value of i: 1
Current Value of i: 2
Current Value of i: 4
Current Value of i: 5 .
7. PL/SQL Query
PL/SQL query is like asking a database a question. You use it to retrieve or manipulate data. It’s similar
to asking, “Give me all the information about X from the database,” and the query provides the answer in a
structured format.
8. PL/SQL Clauses
PL/SQL clauses are like specific instructions you give when asking questions to a database. With clauses,
you can write powerful procedures and functions that automate tasks, manipulate data, and build robust
database applications.
PL/SQL WHERE Clause
PL/SQL WITH Clause
PL/SQL HAVING Clause
PL/SQL ORDER By Clause
PL/SQL Group By Clause
PL/SQL LIMIT Clause
9. PL/SQL Operators
PL/SQL operators are the building blocks of your code. These symbols perform calculations (arithmetic,
comparisons), manipulate data (concatenation, negation), and control logic (AND, OR, NOT). Understanding
operators is fundamental for writing effective PL/SQL procedures, functions, and database triggers.
PLSQL : || Operator
PL/SQL AND Operator
PL/SQL OR Operator
PL/SQL LIKE Operator
PL/SQL IN Operator
PL/SQL NOT Operator
PL/SQL NOT EQUAL Operator
PL/SQL IS NULL Operator
PL/SQL UNION Operator
PL/SQL UNION ALL Operator
PL/SQL EXCEPT Operator
PL/SQL BETWEEN Operator
PL/SQL ALL, ANY Operator
PL/SQL INTERSECT Operator
PL/SQL EXISTS Operator
PL/SQL CASE Operator
What is PL/SQL?
PL/SQL Stands for procedural language extension to SQL. In a procedure, the role of the
subprogram is to perform a particular task and it is a unit module of a program. It combined to form larger
programs. A subprogram can be involved by another program which is called the calling program. PL/SQL
provides a block structure of executable unit code. It provides procedural constructs, for example, in control
structure includes loops, conditional statements, and variable, constant, and data type.
Syntax:
[( Parameter [ parameter ] ) ]
IS
[ declaration_section ]
BEGIN
executable_section
[ EXCEPTION
exception_section]
END [ procedure_name];
Removing procedure in PL/SQL
Once created, a procedure can be removed from the database using the DROP PROCEDURE statement.
Syntax:
Example:
1. IN Mode:
It is read read-only a parameter. IN parameter act like a constant. And within called program or
function, It can be referenced. The program cannot assign a new value to the IN parameter. Their value
cannot be changed inside the subprogram.
2. OUT Mode:
It is used for getting output from the subprograms. It is a read-write variable inside the
subprograms. Their value can be changed inside the subprogram.
3. IN OUT Mode:
To get the input and output from the subprogram then this IN-OUT can be used for getting the
results. Their values can be changed inside the subprograms.
Syntax
The syntax to create a function in PL/SQL is given below:
CREATE [OR REPLACE] FUNCTION function_name
(parameter_name type [, …])
{IS | AS}
BEGIN
— program code
[EXCEPTION
exception_section;
END [function_name];
Example
In this example, we create a PL/SQL function to calculate factorial of a number
PL/SQL
RETURN NUMBER
IS
f NUMBER;
BEGIN
IF x = 0 THEN
f := 1;
ELSE
f := x * factorial(x - 1);
END IF;
RETURN f;
END;
Example
Here, we call the factorial function which we created earlier.
PL/SQL
DECLARE
num NUMBER;
result NUMBER;
BEGIN
num := 5;
result := factorial(num);
END;
Output:
A PL/SQL recursive function is a function that calls itself to perform a specific task. The function
continues to call itself until a certain condition is met, at which point it returns a value.
Recursive Function.
Example
Lets implement a recursive function to calculate the factorial of a number Recursive functions example:
PL/SQL
DECLARE
num INT;
answer INT;
RETURN INT
IS
f INT;
BEGIN
IF x = 0 THEN
f := 1;
ELSE
f := x * factorial(x - 1);
END IF;
RETURN f;
END;
BEGIN
num := 5;
answer := factorial(num);
END;
Output:
Factorial of 5 is 120
Example: PL/SQL
DECLARE
a INT;
b FLOAT;
myexp EXCEPTION;
AS
answer FLOAT;
BEGIN
IF x < 0 THEN
RAISE myexp;
ELSE
answer := SQRT(x);
END IF;
RETURN answer;
EXCEPTION
RETURN x;
END;
BEGIN
b := sqroot(-2);
END;
Output:
Syntax
DROP Function <function_name>;
Example
Table of Content
Procedures in PL/SQL
o Procedure Header
o Procedure Body
Create Procedures in PL/SQL
o Example
Parameters in Procedures
o 1. IN parameters
o 2. OUT parameters
o 3. IN OUT parameters
Modify Procedures in PL/SQL
o Example
Drop Procedure in PL/SQL
o PL/SQL DROP PROCEDURE Example
Advantages of Procedures
Disadvantages of Procedures
Important Points About Procedures in SQL
Procedures in PL/SQL
A PL/SQL procedure is a reusable block of code that contains a specific set of actions or logic.
The procedure contains two parts:
1. Procedure Header
The procedure header includes the procedure name and optional parameter list.
It is the first part of the procedure and specifies the name and parameters
2. Procedure Body
The procedure body contains the executable statements that implement the specific business
logic.
It can include declarative statements, executable statements, and exception-handling
statements
Parameters in Procedures
In PL/SQL, parameters are used to pass values into procedures. There are three types of parameters used in
procedures:
1. IN parameters
Used to pass values into the procedure
Read-only inside the procedure
Can be a variable, literal value, or expression in the calling statement.
2. OUT parameters
Used to return values from the procedure to the calling program
Read-write inside the procedure
Must be a variable in the calling statement to hold the returned value
3. IN OUT parameters
Used for both passing values into and returning values from the procedure
Read-write inside the procedure
Must be a variable in the calling statement
Syntax
DROP PROCEDURE syntax is:
DROP PROCEDURE procedure_name
Advantages of Procedures
They result in performance improvement of the application. If a procedure is being called frequently in
an application in a single connection, then the compiled version of the procedure is delivered.
They reduce the traffic between the database and the application since the lengthy statements are
already fed into the database and need not be sent again and again via the application.
They add to code reusability, similar to how functions and methods work in other languages such
as C/C++ and Java.
Disadvantages of Procedures
Stored procedures can cause a lot of memory usage. The database administrator should decide an
upper bound as to how many stored procedures are feasible for a particular application.
MySQL does not provide the functionality of debugging the stored procedures.
Important Points About Procedures in SQL
A procedure in PL/SQL is a subprogram that can take parameters and be called to perform a specific
action.
Procedures are executed just like SQL statements.
Procedures have two parts the specification (spec) and the body. The spec begins with
the PROCEDURE keyword and ends with the procedure name and optional parameter list. The body
begins with IS (or AS) and ends with END followed by an optional procedure name
They enhance performance by reducing network traffic between the application and database.
Note: When other keyword should be used only at the end of the exception handling block as no exception
handling part present later will get executed as the control will exit from the block after executing the
WHEN OTHERS.
1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows. For eg:
DECLARE
temp varchar(20);
BEGIN
exception
dbms_output.put_line('ERROR');
end;
Output:
ERROR
There is no name as GeeksforGeeks in geeks table
2. TOO_MANY_ROWS:It is raised WHEN a SELECT INTO statement returns more than one row.
DECLARE
temp varchar(20);
BEGIN
dbms_output.put_line(temp);
EXCEPTION
end;
Output:
error trying to SELECT too many rows
3. VALUE_ERROR:This error is raised WHEN a statement is executed that resulted in an arithmetic,
numeric, string, conversion, or constraint error. This error mainly results from programmer
error or invalid data input.
DECLARE
temp number;
BEGIN
EXCEPTION
dbms_output.put_line('Error');
END;
Output:
Error
Change data type of temp to varchar(20)
4. ZERO_DIVIDE = raises exception WHEN dividing with zero.
DECLARE
a int:=10;
b int:=0;
answer int;
BEGIN
answer:=a/b;
exception
END;
Output:
dividing by zero please check the values again
the value of a is 10
the value of b is 0
Syntax:
PRAGMA EXCEPTION_INIT(exception_name, -error_number);
error_number are pre-defined and have negative integer range from -20000 to -20999.
Example:
DECLARE
exp exception;
n int:=10;
BEGIN
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE exp;
END IF;
END LOOP;
EXCEPTION
dbms_output.put_line('Welcome to GeeksforGeeks');
END;
Output:
1
4
9
16
25
36
Welcome to GeeksforGeeks
16.1.2 User defined exceptions:
This type of users can create their own exceptions according to the need and to raise these exceptions
explicitly raise command is used.
Example:
Divide non-negative integer x by y such that the result is greater than or equal to 1.
From the given question we can conclude that there exist two exceptions
o Division be zero.
o If result is greater than or equal to 1 means y is less than or equal to x.
DECLARE
y int:=&y;
div_r float;
exp1 EXCEPTION;
exp2 EXCEPTION;
BEGIN
IF y=0 then
raise exp1;
raise exp2;
ELSE
div_r:= x / y;
END IF;
EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('Error');
END;
Input 1: x = 20
y = 10
Output:
Error
division by zero not allowed
Input 3: x=20
y = 30
Output:<.em>
Error
y is greater than x please check the input
16.2 RAISE_APPLICATION_ERROR:
It is used to display user-defined error messages with error number whose range is in between
20000 and -20999. When RAISE_APPLICATION_ERROR executes it returns error message and error
code which looks same as Oracle built-in error.
Example:
DECLARE
myex EXCEPTION;
n NUMBER :=10;
BEGIN
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
Output:
Error report:
ORA-20015: Welcome to GeeksForGeeks
ORA-06512: at line 13
1
4
9
16
25
36
Note: The output is based on Oracle Sql developer, the output order might change IF you’re running this
code somewhere else.
DECLARE
GeeksforGeeks EXCEPTION;
age NUMBER:=16;
BEGIN
-- sub-block BEGINs
DECLARE
GeeksforGeeks EXCEPTION;
age NUMBER:=22;
BEGIN
END IF;
END;
-- sub-block ends
EXCEPTION
DBMS_OUTPUT.PUT_LINE
('Handling GeeksforGeeks exception.');
DBMS_OUTPUT.PUT_LINE
END;
Output:
Could not recognize exception GeeksforGeeks in this scope.
Advantages:
Exception handling is very useful for error handling, without it we have to issue the command at every
point to check for execution errors:
Example:
Select ..
Select ..
Select ..
With exception handling we handle errors without writing statements multiple times and we can even
handle dIFferent types of errors in one exception block:
BEGIN
SELECT ...
SELECT ...
SELECT ...
exception
...
...
From above code we can conclude that exception handling
1. Improves readability by letting us isolate error-handling routines and thus providing robustness.
2. Provides reliability, instead of checking for dIFferent types of errors at every point we can simply write
them in exception block and IF error exists exception will be raised thus helping the programmer to find
out the type of error and eventually resolve it.
Syntax:
DECLARE
custom_exception EXCEPTION;
BEGIN
IF some_condition THEN
RAISE custom_exception;
END IF;
EXCEPTION
END;
Explanation:
if some_condition is true then the RAISE custom_exception statement will be executed and make
happen the user-defined exception custom_exception to be raised.
The WHEN custom_exception THEN block in the EXCEPTION section will catch and handle this exception.
DECLARE
custom_exception EXCEPTION;
BEGIN
IF true THEN
RAISE custom_exception;
END IF;
EXCEPTION
END;
Output:
Statement processed.
Explanation: In the above query we have declares a custom exception custom_exception. If a condition (in
this case, always true for demonstration purposes) is met then it raises the custom_exception.
The EXCEPTION block catches and handles the custom_exception, printing ‘Custom exception
handled!‘ using DBMS_OUTPUT.PUT_LINE.
16.3.2 Internally Defined Exception
Internally defined exceptions are pre-built into PL/SQL to handle common error conditions such as
division by zero, no data found, or too many rows fetched. Some of the commonly used internal exceptions
include:
NO_DATA_FOUND
TOO_MANY_ROWS
ZERO_DIVIDE
DUP_VAL_ON_INDEX
STORAGE_ERROR
Example:
DECLARE
result NUMBER;
BEGIN
EXCEPTION
END;
Output:
Statement processed.
Explanation: In the above query we computes a division operation (10 / 0) which causes a division by zero
error and leading to the ZERO_DIVIDE exception being raised. The EXCEPTION block catches and handles
this exception by printing ‘Cannot divide by zero!‘ using DBMS_OUTPUT.PUT_LINE.
Example:
DECLARE
custom_exception EXCEPTION;
BEGIN
BEGIN
RAISE custom_exception;
EXCEPTION
END;
END;
Output:
Statement processed.
Explanation: In the above query we demonstrates nested exception handling. It raises a user-defined
exception (custom_exception) within an inner block. The EXCEPTION block in the outer block catches any
exceptions (including the custom_exception) using WHEN OTHERS and prints the error message (SQLERRM)
to the console.
emp_name VARCHAR2(50),
emp_salary NUMBER
);
Step 2: Create a Procedure with an Exception
p_emp_id NUMBER,
p_emp_name VARCHAR2,
p_emp_salary NUMBER
IS
emp_salary_limit EXCEPTION;
BEGIN
RAISE emp_salary_limit;
ELSE
END IF;
EXCEPTION
END;
This procedure will check if the p_emp_salary is greater then 100000 then it will raise a user-defined
exception(emp_salary_limit) else it will insert a new record into a employee table.
Step 3: Execute the Procedure
DECLARE
BEGIN
END;
Output:
DECLARE
BEGIN
END;
Output:
Statement processed.
PL/SQL Record
PL/SQL Cursors
PL/SQL Cursor Update
PL/SQL Cursor FOR LOOP
PL/SQL Cursors with Parameters
PL/SQL REF CURSOR
The Data that is stored in the Cursor is called the Active Data Set. Oracle DBMS has another
predefined area in the main memory Set, within which the cursors are opened. Hence the size of
the cursor is limited by the size of this pre-defined area.
Cursor Actions
Key actions involved in working with cursors in PL/SQL are:
1. Declare Cursor: A cursor is declared by defining the SQL statement that returns a result set.
2. Open: A Cursor is opened and populated by executing the SQL statement defined by the cursor.
3. Fetch: When the cursor is opened, rows can be fetched from the cursor one by one or in a block to
perform data manipulation.
4. Close: After data manipulation, close the cursor explicitly.
5. Deallocate: Finally, delete the cursor definition and release all the system resources associated with the
cursor.
Types of Cursors in PL/SQL
Cursors are classified depending on the circumstances in which they are opened.
Implicit Cursor: If the Oracle engine opened a cursor for its internal processing it is known as an Implicit
Cursor. It is created “automatically” for the user by Oracle when a query is executed and is simpler to
code.
Explicit Cursor: A Cursor can also be opened for processing data through a PL/SQL block, on demand.
Such a user-defined cursor is known as an Explicit Cursor.
Where,
Syntax
General Syntax of using an explicit cursor in PL/SQL is:
DECLARE
variables;
records;
CURSOR cursor_name IS select_statement;
BEGIN
OPEN cursor_name;
LOOP
FETCH cursor_name INTO variables OR records;
EXIT WHEN cursor_name%NOTFOUND;
Syntax:
SET SERVEROUTPUT ON;
DECLARE
–declare variables and cursor;
CURSOR cursor_name IS SELECT statement FROM FOR UPDATE;
BEGIN
OPEN cursor_name;
FETCH cursor_name ;
— to update
UPDATE table_name
CLOSE cursor_name;
–to commit the changes
COMMIT;
END;
/
Examples of PL/SQL Updatable Cursors
Explanation:
The Cursor with FOR UPDATE keyword is declared in the declaration section. It is opened and
fetched in the execution section. The Fetch operation is performed in loop to update each row UPDATE
keyword is used to update the table.” WHERE CURRENT OF cursor_geek” is used to point to the current row.
“cursor_geek%NOTFOUND” is used as can condition till there are rows in the table. The cursor is closed
after the updation.
Output:
The output contains the table before the update and the table after updation.
PL/SQL UPDATABLE
Syntax:
SET SERVEROUTPUT ON;
DECLARE
–declare variables and cursor;
CURSOR cursor_name IS SELECT statement FROM FOR UPDATE OF column_name; — column to be
updated.
BEGIN
OPEN cursor_name;
FETCH cursor_name ;
— to update
UPDATE table_name
CLOSE cursor_name;
–to commit the changes
COMMIT;
END;
/
Query:
DECLARE
CURSOR geek_cursor IS
SELECT Id, Name, Score
FROM Geeks
FOR UPDATE OF Score; -- column to be updated
variable_id NUMBER;
variable_name VARCHAR2(20);
variable_score NUMBER;
BEGIN
-- Table before Updates
DBMS_OUTPUT.PUT_LINE('TABLE BEFORE UPDATES');
FOR element IN (SELECT * FROM Geeks) LOOP
DBMS_OUTPUT.PUT_LINE(element.Id || ' ' || element.Name || ' ' || element.Score);
END LOOP;
DBMS_OUTPUT.NEW_LINE;
OPEN geek_cursor;
LOOP
FETCH geek_cursor INTO variable_id, variable_name, variable_score;
EXIT WHEN geek_cursor%NOTFOUND;
-- Update
UPDATE Geeks
SET Score = variable_score+ 100
WHERE CURRENT OF geek_cursor;
END LOOP;
CLOSE geek_cursor;
-- Committing changes
COMMIT;
Explanation: FOR UPDATE OF keyword is used to lock the score column from the geeks table.
Syntax:
DECLARE
declare variables;
FETCH cursor;
CLOSE cursor;
END;
DECLARE
FROM Geeks
-- Declare variables
cur_id Geeks.Id%TYPE;
cur_name Geeks.name%TYPE;
cur_rank Geeks.rank%TYPE;
BEGIN
-- Open and fetch data using the cursor
OPEN GFG(951);
LOOP
DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name || ', Rank: ' ||
cur_rank);
END LOOP;
CLOSE GFG;
END;
Output:
Table
Output:
Output
Explanation:
SET SERVEROUTPUT ON is used to display output from DBMS_OPTPUT.PUT_LINE. GFG cursor and
variables are declared in the declaration block. The parameter indicates the minimum required
rank.
The BEGIN keyword is used to start the execution of code. The cursor is opened using
The OPEN keyword and data is fetched repeatedly from the table using the LOOP keyword.
Data from the table is checked against the condition mentioned in the
cursor. DBMS_OUTPUT.PUT_LINE to display the data that satisfies the condition. END LOOP breaks
the loop and the cursor is closed using the CLOSE keyword. The END keyword is used to end the
execution.
DECLARE
declare variables;
FETCH cursor;
CLOSE cursor;
END;
DECLARE
FROM Geeks
-- Declare variables
cur_id Geeks.Id%TYPE;
cur_name Geeks.name%TYPE;
cur_rank Geeks.rank%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE('PL/SQL parameterized cursor with default value');
OPEN GFG;
LOOP
DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name || ', Rank: ' ||
cur_rank);
END LOOP;
CLOSE GFG;
END;
Explanation:
The example mentioned is the same as the one used earlier. In this example, default values are
used in the parameterized cursor. In DECLARE block cursor is defined with default value for the parameter .
The cursor is called without argument in the BEGIN section.
Important Points About PL/SQL Parameterized Cursors
Explicitly close cursors to free up memory resources.
Use the %NOTFOUND attribute to exit loops when no more rows are available.
PL/SQL Cursors with Parameters allows for specific actions to be taken based on parameterized
cursor outcomes.
You can adapt the cursor’s behavior based on different input values.
-- Other declarations...
END my_package;
BEGIN
-- Implementation code...
END my_procedure;
BEGIN
-- Implementation code...
END calculate_sum;
END my_package;
Once your create your package in above two steps, you can use it in PL/SQL codes. This allows for modular
programming, code reuse, and better maintenance of the the code base.
DECLARE
result NUMBER;
BEGIN
my_package.my_procedure(42);
-- Other code...
END;
Here, my_procedure is called with the value 42, and the result of calculate_sum(10, 20) is displayed.
END math_operations;
/
-- Create the body of the math_operations package
BEGIN
result := x + y;
END add_numbers;
BEGIN
RETURN x * y;
END multiply_numbers;
END math_operations;
DECLARE
sum_result NUMBER;
product_result NUMBER;
BEGIN
END;
Output:
Explanation:
The PL/SQL code defines a package named math_operations with a procedure (add_numbers) and a
function (multiply_numbers). The package is then implemented in a package body, with the procedure
adding two numbers and the function multiplying them.
END employee_operations;
BEGIN
END calculate_annual_salary;
BEGIN
END employee_operations;
DECLARE
-- Declare variables
annual_salary_result NUMBER;
full_name_result VARCHAR2(100);
BEGIN
employee_operations.calculate_annual_salary(5000, annual_salary_result);
END;
Ouput:
Explanation:
The above PL/SQL code create a package named employee_operations with a procedure
(calculate_annual_salary) and function (get_full_name). The created package calculate the annual salary
based on monthly salary and concatnates employee names. A PL/SQL block then tests the package by calling
these routines and finally displays the result.
Important Points About PL/SQL Packages
Here are 4 important points for working with PL/SQL packages:
1. Encapsulation: Packages group related procedures, functions, and variables together, making code
easier to manage and maintain.
2. Reusability: Code in packages can be reused across multiple applications, reducing duplication and
simplifying future maintenance.
3. Performance: Packages are loaded into memory once per session, improving execution speed for
repeated use during the session.
4. Overloading: Packages allow overloading, meaning multiple procedures or functions with the same
name can exist, as long as they have different parameters
PL/SQL triggers are block structures and predefined programs invoked automatically when some event
occurs. They are stored in the database and invoked repeatedly in a particular scenario. There are two
states of the triggers, they are enabled and disabled. When the trigger is created it is enabled. CREATE
TRIGGER statement creates a trigger. A triggering event is specified on a table, a view, a schema, or a
database. BEFORE and AFTER are the trigger Timing points.DML triggers are created on a table or view,
and triggers. Crossedition triggers are created on Edition-based redefinition. System Triggers are created on
schema or database using DDL or database operation statements.It is applied on new data only ,it don’t
affect existing data.
They are associated with response-based events such as a
Database Definition Language statements such as CREATE, DROP or ALTER.
Database Manipulation Language statements such as UPDATE, INSERT or DELETE.
Database operations such as LOGON, LOGOFF, STARTUP, and SHUTDOWN .
Why are Triggers important?
The importance of Triggers are:
Automated Action: It helps to automate actions in response to events on table or views.
Data integrity: Constraint can be applied to the data with the help of trigger.It is used to
ensure referential integrity.
Consistency: It helps to maintain the consistency of the database by performing immediate responses
to specific events.
Error handling: It helps in error handling by responding to the errors. For example, If specific condition
is not met it will provide an error message.
Syntax:
CREATE OR REPLACE TRIGGER trigger_name
BEFORE or AFTER or INSTEAD OF //trigger timings
INSERT or UPDATE or DELETE // Operation to be performed
of column_name
on Table_name
FOR EACH ROW
DECLARE
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
/
Query operation to be performed i.e INSERT,DELETE,UPDATE.
CREATE [ OR REPLACE ] TRIGGER trigger_name is used to create a trigger or replace the existing
trigger.|
BEFORE | AFTER | INSTEAD OF specifies trigger timing.
INSERT | UPDATE | DELETE are the DML operations performed on table or views.
OF column_name specifies the column that would be updated.
ON table_name species the table for the operation.
FOR EACH ROW specify that trigger is executed on each row .
Query:
-- Create Geeks table
CREATE TABLE Geeks (
Id INT,
Name VARCHAR2(20),
Score INT
);
Output:
Output:
6.Conditional Trigger After
Explanation: After the deletion of the row from the Geek table trigger is fired and the row which is deleted
is added to the Affect Table.In second trigger i.e After_update trigger is fired after performing update on
Geeks table and the row is added to Affect Table.Output contains the Affect table and the Geek table after
the trigger events.
Common Use Cases of PL/SQL Triggers
To automate the actions in response to the events and reducing manual task.
To apply constraint to ensure referential integrity and to prevent invalid data in table or database.
In error handling to response to errors.
Syntax:
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;