0% found this document useful (0 votes)
3 views97 pages

What Is PL

The document provides a comprehensive overview of Oracle PL/SQL, covering its architecture, features, and various programming constructs such as blocks, control flow statements, loops, and exception handling. It explains the advantages and disadvantages of PL/SQL, as well as detailed examples of user input and decision-making structures. The content is structured into sections that guide the reader through the fundamentals and advanced topics of PL/SQL programming.

Uploaded by

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

What Is PL

The document provides a comprehensive overview of Oracle PL/SQL, covering its architecture, features, and various programming constructs such as blocks, control flow statements, loops, and exception handling. It explains the advantages and disadvantages of PL/SQL, as well as detailed examples of user input and decision-making structures. The content is structured into sections that guide the reader through the fundamentals and advanced topics of PL/SQL programming.

Uploaded by

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

10/21/2024 ORACLE PL/SQL

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.

2. What do you mean by PL/SQL Architecture?

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 :

The various features of PL/SQL are given below –


 PL/SQL runs on various operating systems such as windows, Linux etc.
 PL/SQL have an error-checking facility and displays user-friendly messages when an error occurs in
a program.
 It offers logging and debugging capabilities, including the capacity to use exception messages.
 SQL can be executed dynamically.
 When certain data events, such as INSERT, UPDATE, or DELETE actions on a table, occur, triggers
are specialized forms of stored processes that are automatically invoked.
 Multi-row queries are handled using cursors.
 The declaration of variables and constants to store data values is supported.

PL/SQL can reside in two environments –


1. The Oracle Server
2. The Oracle tools

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:

Maximum number in 10 and 100: 100


2.Named blocks:

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 variable a, b and c

-- and these three variables datatype are integer

DECLARE

a number;

b number;

c number;

--Function return largest number of

-- two given number

FUNCTION findMax(x IN number, y IN 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);

dbms_output.put_line(' Maximum number in 10 and 100 is: ' || c);

END;

-- Program End

Output:
Maximum number in 10 and 100: 100

4.PL/SQL | User Input

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:

SQL> create table GFG (id number(4), author varchar2(50),

likes number(4))

Table created.

SQL> insert into GFG values(1, 'sam', 10);

1 row created.

SQL> insert into GFG values(2, 'maria', 30);

1 row created.
SQL> insert into GFG values(3, 'ria', 40);

1 row created.

SQL> select * from GFG;

id author likes

1 sam 10

2 maria 30

3 ria 40

User Input has two


1. Numeric value

2. Text value

1. Numeric value –

& is used to input numeric values from the user.

Syntax:

&value

SQL> select * from GFG where id=&id;


Enter value for id: 2
old 1: select * from GFG where id=&id
new 1: select * from GFG where id=2

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

5.1 IF THEN in PL/SQL - Decision Making 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

-- declare the values here

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

num1 number:= 10;

num2 number:= 20;

begin

if num1 > num2 then

dbms_output.put_line('num1 small');

end if;

dbms_output.put_line('I am Not in 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

-- pl/sql program to illustrate If else statement

declare

num1 number:= 10;

num2 number:= 20;

begin

if num1 < num2 then

dbms_output.put_line('i am in if block');
ELSE

dbms_output.put_line('i am in else Block');

end if;

dbms_output.put_line('i am not in if or else Block');

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

-- pl/sql program to illustrate nested If statement

declare

num1 number:= 10;

num2 number:= 20;

num3 number:= 20;

begin

if num1 < num2 then

dbms_output.put_line('num1 small num2');

if num1 < num3 then


dbms_output.put_line('num1 small num3 also');

end if;

end if;

dbms_output.put_line('after end if');

end;

Output:-

num1 small num2


num1 small num3 also
after end if

4. IF THEN ELSIF-THEN-ELSE Ladder

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

-- pl/sql program to illustrate if-then-elif-then-else ladder

declare

num1 number:= 10;

num2 number:= 20;

begin

if num1 < num2 then


dbms_output.put_line('num1 small');

ELSEIF num1 = num2 then

dbms_output.put_line('both equal');

ELSE

dbms_output.put_line('num2 greater');

end if;

dbms_output.put_line('after end if');

end;

Output:-

num1 small
after end if

5.2 CASE Statement in PL/SQL


The PL/SQL CASE statement is a powerful conditional control structure in Oracle databases that
allows you to execute different blocks of code based on specified conditions. Here, we explore the syntax,
types, and practical use cases of the PL/SQL CASE statement to make better decisions and improve your
ability to use conditional logic in Oracle PL/SQL.

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

WHEN condition_1 THEN

-- code block for condition_1

WHEN condition_2 THEN

-- code block for condition_2

...

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.

Types of CASE Statement


There are two primary types of CASE statements in PL/SQL:
 Simple CASE Statement
 Searched CASE Statement

1. Simple CASE Statement :


In a Simple CASE statement, the value of an expression is compared to constant values (predefined).
It is useful when you want to match a single expression with different constant values.

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

day_name := 'Invalid day';

END CASE;

DBMS_OUTPUT.PUT_LINE('The day is: ' || day_name);

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.

The day is: Monday


2. Searched CASE Statement:

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_price NUMBER := 120.50;

product_category VARCHAR2(20);

BEGIN

CASE

WHEN product_price < 50 THEN

product_category := 'Low Cost';

WHEN product_price >= 50 AND product_price <= 100 THEN

product_category := 'Medium Cost';

WHEN product_price > 100 THEN

product_category := 'High Cost';

ELSE

product_category := 'Invalid Price';

END CASE ;

DBMS_OUTPUT.PUT_LINE('The product falls into the category: ' || product_category);

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

CASE Statement vs CASE Expression


CASE Statement CASE Expression

CASE Statement is used to handle flow control


CASE Expression in SQL is used for transforming or
within procedural code and it determines which
selecting values within a query and returning
code block to execute based on specified
different results based on conditions.
conditions.

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.

It also supports ELSE clause for defining a default


It supports ELSE clause for defining a default action.
action.

Important Points About PL/SQL CASE Statement

 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.

5.3 PL/SQL GOTO Statement


GOTO statement, which helps control how a program flows by allowing it to jump to specific
statements within the same part of the program. Its excessive usage of the GOTO statement can result in
various drawbacks that impact code quality and readability.

How Does the GOTO Statement Work?

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.

GOTO Statement in PL/SQL

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

Understanding the limitations of the GOTO statement is crucial:


 Control Flow Limitations: GOTO cannot jump into IF, CASE, LOOP, or sub-blocks.
 Branching Limitations: It cannot jump between different clauses within IF or CASE statements.
 Block and Exception Handling Restrictions: GOTO cannot move from an outer block to a sub-block or
out of a subprogram. Additionally, it cannot branch back from an exception handler into the current
block.
 Debugging Challenges: Programs with GOTO statements are often harder to debug, as the flow of
control becomes less predictable.
 Exception Handling Issues: In structured languages with exception handling mechanisms, GOTO
statements often cannot branch back from an exception handler into the current block. This restriction
prevents unstructured or unexpected control flow, ensuring that exception handling maintains its
predictability.

PL/SQL Code Using the GOTO Statement Along with an Explanation

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;

IF num > 0 THEN


DBMS_OUTPUT.PUT_LINE('You entered a positive number.');
GOTO end_of_program;
ELSE
DBMS_OUTPUT.PUT_LINE('You entered either zero or a negative number.');
END IF;

<<end_of_program>>
DBMS_OUTPUT.PUT_LINE('End of the Program');
END;
Output:

Explanation of the Code

 Displays a welcome message to the user when the program starts.


 Input a number.
 The program checks if the input number is less than or equal to zero. If it is, the program jumps using
the GOTO statement.
 If the number is positive (not zero or negative), this line gets executed, indicating the input is a positive
number.
 If the input number by user is zero or negative, this line gets executed, indicating that the input is either
zero or a negative number.
 Marks the end of the program and displays a concluding message.

5.4 PL/SQL NULL Statement


 Null statement plays a crucial role in enhancing code readability and functionality.

 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;

NULL and Exception Handling

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

-- Exception handling block


BEGIN
-- Code that might raise an exception
DECLARE
numerator INT := 10;
denominator INT := 0;
result INT;
BEGIN
result := numerator / denominator; -- This line may raise a division by zero
exception
EXCEPTION
WHEN ZERO_DIVIDE THEN
-- NULL statement used as a placeholder for no specific action needed
NULL; -- Placeholder: No action required for this specific condition
END;
END;
END;

Output:

6. PL/SQL LOOPS and EXIT Statement


PL/SQL loops
PL/SQL loops are like repeating tasks in a to-do list. They repeat a code block until a condition is met,
ideal for processing data in bulk, running calculations iteratively, or automating database tasks. Mastering
loops is key to writing efficient, dynamic PL/SQL programs.

 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

-- Code block to be executed repeatedly

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;

Example of PL/SQL LOOP with Conditional EXIT


In this example, we showcase the application of a PL/SQL LOOP construct with a conditional EXIT
statement. The code demonstrates a scenario where a loop iterates a specific block of code, printing
iteration numbers, and breaks out of the loop when a predefined condition is met.

DECLARE

counter NUMBER := 1;

BEGIN

LOOP

DBMS_OUTPUT.PUT_LINE('This is iteration number ' || counter);

IF counter = 3 THEN

EXIT;

END IF;

counter := counter + 1;

END LOOP;

END;

/
Output:

Statement processed.

This is iteration number 1

This is iteration number 2

This is iteration number 3

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.

EXIT WHEN Statement


The EXIT WHEN statement allows for a more concise way to specify the condition under which a
loop should exit. It checks the condition directly within the loop’s syntax.
Syntax

LOOP

-- Code block

EXIT WHEN condition;

END LOOP;

Example of PL/SQL LOOP with EXIT WHEN


The purpose of this example is to show how to print “GeeksForGeeks” repeatedly using a PL/SQL
LOOP construct. With the help of the EXIT WHEN statement, the loop can be controlled to end when a
counter variable reaches a predetermined threshold.

DECLARE

counter NUMBER := 1; -- Initialization of the counter variable

BEGIN

-- Loop that prints "GeeksForGeeks" five times

LOOP
DBMS_OUTPUT.PUT_LINE('GeeksForGeeks');

counter := counter + 1; -- Increment the counter

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

-- Inner loop code block

EXIT WHEN inner_condition;

END LOOP;

EXIT WHEN outer_condition;

END LOOP;

Example of PL/SQL Nested FOR Loop Simultaneous Iteration


In this example, we will create nested FOR loops that iterate over two ranges, demonstrating simultaneous
iteration.

DECLARE

outer_counter NUMBER := 1;

inner_counter NUMBER := 1;

BEGIN

FOR outer_counter IN 1..3 LOOP

DBMS_OUTPUT.PUT_LINE('Outer Loop - Iteration ' || outer_counter);

FOR inner_counter IN 1..2 LOOP

DBMS_OUTPUT.PUT_LINE('Inner Loop - Iteration ' || inner_counter);

END LOOP;

END LOOP;

END;

Output:

Statement processed.

Outer Loop - Iteration 1

Inner Loop - Iteration 1


Inner Loop - Iteration 2

Outer Loop - Iteration 2

Inner Loop - Iteration 1

Inner Loop - Iteration 2

Outer Loop - Iteration 3

Inner Loop - Iteration 1

Inner Loop - Iteration 2

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.

6.1 FOR LOOP in PL/SQL

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

--declare loop variable and provide its datatype

loop_varaible datatype;

BEGIN

--for loop with start and end value

FOR loop_variable in start_value .. end_value LOOP

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:

Print Number From 1 to 5 Using FOR Loop in PL/SQL


Here’s a simple example to demonstrate the PL/SQL FOR loop:

Query:

SET SERVEROUTPUT ON;

DECLARE

counter NUMBER;

BEGIN

DBMS_OUTPUT.PUT_LINE('PL/SQL FOR LOOP EXECUTION');

FOR counter IN 1..5 LOOP

DBMS_OUTPUT.PUT_LINE('COUNTER VALUE: '|| counter);

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.

6.2 PL/SQL NESTED FOR LOOP


PL/SQL supports nested for loop. The nested for loop contains an outer loop and one or more inner
loop. For each increment of the loop variable , of the outer loop, the inner loops executes the set of
statements within it for a specific number of times.This process repeats until loop variable of outer loop
reaches its end value. Nested for loops are used for executing complex operations, designing patterns, and
many more operations.

Syntax

BEGIN

--outer loop
FOR loop_variable1 IN start_value1 ..end_value1 LOOP

--inner loop

FOR loop_variable2 IN start_value2 ..end_value2 LOOP

--set of statements

END LOOP;

--inner loop end

END LOOP;

--outer loop end

END;

Example: Using Nested FOR Loops to Print a Pattern


In this example, we will print the numbers 1, 2, and 3 in a pattern using nested loops.

Query:

SET SERVEROUTPUT ON;

BEGIN

DBMS_OUTPUT.PUT_LINE('PL/SQL NESTED FOR LOOP EXECUTION');

FOR counter IN 1..3 LOOP

FOR counter1 IN 1..3 LOOP

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.

6.3 Using the REVERSE Keyword in a PL/SQL FOR Loop


Reverse keyword is used in FOR loop to iterate from end value to start value.REVERSE keyword is
mentioned before the start value.

Syntax

BEGIN
FOR loop_variable IN REVERSE start_value .. end_value LOOP
set_of_statements
END LOOP;
END;
/

Example: Print Number From 5 to 1 Using the REVERSE Keyword


Here’s how you can print numbers in reverse order using a FOR loop:
Query:

SET SERVEROUTPUT ON;

DECLARE

counter NUMBER;

BEGIN

DBMS_OUTPUT.PUT_LINE('FOR LOOP WITH REVERSE KEYWORD');


FOR counter IN REVERSE 1..5 LOOP

DBMS_OUTPUT.PUT_LINE('REVERSE VALUE: '|| counter);

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.

Important Points About PL/SQL For Loop


 The loop variable is automatically declared and incremented within the FOR loop, so there’s no need
for explicit initialization or incrementation.
 The loop iterates from a specified start_value to end_value. The loop variable increases by 1 after
each iteration.
 The loop variable is scoped to the loop itself. It cannot be accessed outside the loop unless explicitly
declared in the declaration section.
 The REVERSE keyword can be used to iterate in reverse order, starting from the higher value and
decrementing to the lower value.
6.4 PL/SQL While Loop
In Oracle PL/SQL there are different loop statements to repeat a block of code until a certain
condition is met to exit the loop. Loop…End Loop, While Loop…End Loop and For Loop … End Loop.
In this article, we will discuss PL/SQL WHILE loop syntax, which involves variable declarations, loop initiation,
condition definition, and an optional EXIT WHEN statement for controlled termination. This structure allows
developers to create flexible and dynamic iterations tailored to specific programming needs.

WHILE Loop Statement


In PL/SQL, the WHILE loop statement is a control structure statement that repeatedly executes a
code block that is inside the ‘While Loop’ as long as the specific condition set in the ‘While Loop’ is TRUE.
The condition set in the ‘WHILE’ statement is a boolean expression that evaluates to TRUE, FALSE, or NULL.
To terminate the loop prematurely or based on some specific scenario then the EXIT or EXIT
WHEN statement is used.

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;

Examples of PL/SQL WHILE Loop

Example 1:

Using PL/SQL WHILE Loop for Iterative Execution


In this example, we delve into the usage of the PL/SQL WHILE loop for iterative execution. The code
demonstrates a basic scenario where a counter variable is initialized and incremented within the loop, with
the loop executing until a specified condition is met.

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);

-- Increment the counter


counter := counter + 1;
END LOOP; -- End of the loop
END;
/
Explanation:

 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:

WHILE Loop Example Terminated by EXIT WHEN Statement


This example illustrates the use of a PL/SQL WHILE loop with the EXIT WHEN statement, showcasing a
scenario where the loop iterates until a certain condition is met. The code calculates the sum of numbers
until the total sum reaches or exceeds 10.

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;

-- Display the current state


DBMS_OUTPUT.PUT_LINE('Current Number: ' || current_number);
DBMS_OUTPUT.PUT_LINE('Total Sum: ' || total_sum);

-- Increment the current number


current_number := current_number + 1;

-- Exit the loop when the total sum exceeds or equals 10


EXIT WHEN total_sum >= 10;
END LOOP; -- End of the loop
END;
/

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

6.5 PL/SQL CONTINUE Statement


In PL/SQL (Procedural Language/Structured Query Language), the CONTINUE statement is used
within loops to skip the remaining statements within the loop for the current iteration and move on to the
next iteration. The CONTINUE statement is commonly used in combination with conditional statements to
control the flow of execution in loops.

Syntax:

CONTINUE;

Example:

DECLARE

i NUMBER := 1;

BEGIN

LOOP

IF i = 3 THEN

-- Skip the rest of the loop for i = 3

i := i + 1;
CONTINUE;

END IF;

-- Process other statements inside the loop

DBMS_OUTPUT.PUT_LINE('Current Value of i: ' || i);

i := i + 1;

EXIT WHEN i > 5; -- Exit the loop when i exceeds 5

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.

 PL/SQL SELECT Statement


 PL/SQL SELECT FROM
 PL/SQL SELECT DISTINCT
 PL/SQL INSERT Statement
 PL/SQL Derived Tables
 PL/SQL Insert Into
 PL/SQL Insert Multiple Rows
 PL/SQL INSERT INTO SELECT
 PL/SQL UPDATE Statement
 PL/SQL DELETE Statement
 PL/SQL TRUNCATE TABLE

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

10. PL/SQL Aggregate Functions


PL/SQL aggregate functions are like summarizing tools for data.
 PL/SQL Aggregate Function
 PL/SQLCount() Function
 PL/SQL SUM() Function
 PL/SQL MIN() Function
 PL/SQL MAX() Function
 PL/SQL AVG() Function
11. PL/SQL Data Constraints
PL/SQL data constraints ensure data integrity and accuracy by setting conditions on what kind of
information can be stored in a table.
 PL/SQL NOT NULL Statement
 PL/SQL UNIQUE Constraint
 PL/SQL Primary Key
 PL/SQL Foreign Key
 PL/SQL Composite Key
 PL/SQL Unique Key
 PL/SQL Alternate Key
 PL/SQL CHECK Constraint
 PL/SQL DEFAULT Constraint

12. PL/SQL Joining Data


PL/SQL lets you weave magic with data from multiple tables. Using JOINs, you can combine related
information across tables. In this section we have discussed PL/SQL Joining Data, explore this section to get
upscale your PL/SQL understanding.
 PL/SQL JOIN
 PL/SQL Outer Join
 PL/SQL Left Join
 PL/SQL Right Join
 PL/SQL Full Join
 PL/SQL Cross Join
 PL/SQL UPDATE JOIN
 PL/SQL DELETE JOIN
 PL/SQL Recursive Join

13. PL/SQL Functions & PROCEDURES


PL/SQL’s secret weapons? Procedures and functions! Procedures act like mini-programs, automating
tasks and keeping your code clean. Functions are value-driven workhorses, performing calculations and
returning results.
 Basic Query in PL/SQL Procedure
 PL/SQL Procedure
 Functions in PL/SQL

13.1 Basic Query in PL/SQL procedure


PL/SQL is a powerful extension to SQL, designed to combine the robustness of SQL with procedural
constructs like loops, conditions, and more. It plays a crucial role in writing complex database interactions in
Oracle databases. This article will cover an overview of PL/SQL, basic query operations, and an in-depth look
at parameter modes in PL/SQL subprograms.

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.

Key Features of PL/SQL


1. It can be created at the schema level, inside a package, and inside a PL /SQL block.
2. The schema-level subprogram is a standalone subprogram. It is created with the CREATE PROCEDURE
statement. In the subprogram, it is stored in the database and can be deleted with the DROP
PROCEDURE statement.
3. It is stored in the database and the package is deleted with the DROP PACKAGE statement.
4. PL/SQL provides to kind of subprogram function and procedure.

Function and procedure in PL /SQL


Let’s understand the meaning of function and procedure in PL/SQL:
1. Function:
 A function is designed to return a single value.
 They are often used when you need to compute a value and use it elsewhere in your application.
 Functions must return a value using the ‘RETURN’ statement.
2. Procedure:
 Procedures perform a specific action but are not required to return a value.
 They are versatile and can include multiple operations such as inserting, updating, or deleting
records in a database.

Creating Procedure in PL/SQL


The ‘CREATE PROCEDURE’ statement is used to define a procedure. You can also use ‘OR
REPLACE’ to modify an existing procedure.
Here, we will discuss, how you can create the procedure using PL/SQL query as follows.

Syntax:

CREATE [ OR REPLACE ] PROCEDURE procedure_name

[( 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:

DROP PROCEDURE procedure_name;

Example:

DROP PROCEDURE Update course;

Parameter modes in PL/ SQL subprograms


Parameter modes define how values are passed to and from the subprogram. There are three
parameter modes in PL/SQL:

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.

13.2 PL/SQL Functions


PL/SQL functions are reusable blocks of code that can be used to perform specific tasks. They are
similar to procedures but must always return a value.

A function in PL/SQL contains:


 Function Header: The function header includes the function name and an optional parameter list. It is
the first part of the function and specifies the name and parameters.
 Function Body: The function body contains the executable statements that implement the specific logic.
It can include declarative statements, executable statements, and exception-handling statements.

Create Function in PL/SQL


To create a procedure in PL/SQL, use the CREATE FUNCTION statement.

Syntax
The syntax to create a function in PL/SQL is given below:
CREATE [OR REPLACE] FUNCTION function_name
(parameter_name type [, …])

— This statement is must for functions


RETURN return_datatype

{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

CREATE OR REPLACE FUNCTION factorial(x NUMBER)

RETURN NUMBER

IS

f NUMBER;

BEGIN

IF x = 0 THEN

f := 1;

ELSE

f := x * factorial(x - 1);

END IF;

RETURN f;

END;

How to Call Function in PL/SQL


To call a function, specify the function name and any required parameters. The function will
execute and return a value.

Example
Here, we call the factorial function which we created earlier.
PL/SQL

DECLARE

num NUMBER;

result NUMBER;
BEGIN

num := 5;

result := factorial(num);

DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || result);

END;

Output:

the reverse of number is 987654321

PL/SQL Recursive Function

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;

-- Defining the function

FUNCTION factorial(x NUMBER)

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);

DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || answer);

END;

Output:

Factorial of 5 is 120

Exception handling in PL/SQL Functions


Exception handling can be done using an exception block in functions but exception handling using
a try-catch block cannot be done.

Example: PL/SQL

SET SERVEROUTPUT ON;

DECLARE

a INT;

b FLOAT;

myexp EXCEPTION;

FUNCTION sqroot(x INT)


RETURN FLOAT

AS

answer FLOAT;

BEGIN

IF x < 0 THEN

RAISE myexp;

ELSE

answer := SQRT(x);

END IF;

RETURN answer;

EXCEPTION

WHEN myexp THEN

DBMS_OUTPUT.PUT_LINE('Square root of a negative number is not allowed, so returning


the same number');

RETURN x;

END;

BEGIN

b := sqroot(-2);

DBMS_OUTPUT.PUT_LINE('The value is ' || b);

END;

Output:

square of negative number is not allowed so returning the same number


the value is -2
Advantages of PL/SQL Functions
1. We can make a single call to the database to run a block of statements thus it improves the
performance against running SQL multiple times. This will reduce the number of calls between the
database and the application.
2. We can divide the overall work into small modules which becomes quite manageable also
enhancing the readability of the code.
3. It promotes reusability.
4. It is secure since the code stays inside the database thus hiding internal database details from the
application(user). The user only makes a call to the PL/SQL functions. Hence security and data
hiding is ensured.

DROP Function in PL/SQL

To drop a function in PL/SQL, DROP function statement is used.

Syntax
DROP Function <function_name>;

Example

DROP Function func1;

Important Points About Function in PL/SQL


 Functions in PL/SQL must return a value, which can be a scalar, table, or collection.
 They can improve performance by executing logic on the database server.
 They can enhance security by enforcing strict access controls.
 They can simplify complex logic by breaking it down into smaller, manageable parts.
 They can handle exceptions and errors by including exception handling blocks.
 They can simplify data retrieval by encapsulating complex join operations and filtering conditions.
13.3 Procedures in PL/SQL
PL/SQL procedures are reusable code blocks that perform specific actions or logic within
a database environment. They consist of two main components such as the procedure header which defines
the procedure name and optional parameters and the procedure body which contains the executable
statements implementing the desired business logic.We will learn about PL/SQL Procedures in detail by
understanding various examples and so on.

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

Create Procedures in PL/SQL


To create a procedure in PL/SQL, use the CREATE PROCEDURE command:
Syntax

CREATE PROCEDURE syntax is:

CREATE PROCEDURE procedure_name


@Parameter1 INT,
@Parameter2 VARCHAR(50) = NULL,
@ReturnValue INT OUTPUT
AS
BEGIN
END
Note: Procedures in PL/SQL without parameters are written without parentheses after the procedure name

In this example, we will create a procedure in PL/SQL

CREATE PROCEDURE GetStudentDetails


StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, BirthDate, City, Country
FROM Students WHERE StudentID=@StudentID
END

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

Drop Procedure in PL/SQL


To drop a procedure in PL/SQL use the DROP PROCEDURE command

Syntax
DROP PROCEDURE syntax is:
DROP PROCEDURE procedure_name

PL/SQL DROP PROCEDURE Example

DROP PROCEDURE GetStudentDetails

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.

14. PL/SQL Views


PL/SQL views are saved queries that you can use to simplify complex data access. They act as virtual
tables, presenting a subset of data from one or more tables.
 PL/SQL CREATE VIEW
 PL/SQL DROP VIEW
 PL/SQL UPDATE VIEW
 PL/SQL RENAME VIEW
 PL/SQL DELETE VIEW

15. PL/SQL Indexes


PL/SQL itself doesn’t manage indexes directly, but it can be your secret weapon for optimizing them.
Indexes, like library catalogs, speed up data retrieval. By understanding how indexes work within PL/SQL,
you can craft code that leverages their power.
 PL/SQL Indexes
 PL/SQL Create Index
 PL/SQL Drop Index
 PL/SQL Show Indexes
 PL/SQL Unique Index
 Clustered Index vs Non-Clustered Index

16. PL/SQL EXCEPTION HANDLERS


PL/SQL’s EXCEPTION HANDLERS act like safety nets for your code. They anticipate potential errors
during execution, like data issues or unexpected conditions. By defining handlers, you can gracefully handle
these exceptions, preventing program crashes and ensuring your PL/SQL block continues execution
smoothly. So, explore this section to know how to use PL/SQL EXCEPTION HANDLERS.
 Exceptions in PL/SQL
 RAISE Exceptions in PL/SQL
 RAISE_APPLICATION_ERROR in PL/SQL

16.1 Exception Handling in PL/SQL


An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides
us the exception block which raises the exception thus helping the programmer to find out the fault and
resolve it.
There are two types of exceptions defined in PL/SQL
1. User defined exception.
2. System defined exceptions.
Syntax to write an exception
WHEN exception THEN
statement;
DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;

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.

16.1.1 System defined exceptions:


These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is violated.

System-defined exceptions are further divided into two categories:


1. Named system exceptions.
2. Unnamed system exceptions.

 Named system exceptions:


They have a predefined name by the system like ACCESS_INTO_NULL,
DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the list is quite big.
So we will discuss some of the most commonly used exceptions:
Lets create a table geeks.
create table geeks(g_id int , g_name varchar(20), marks int);
insert into geeks values(1, 'Suraj',100);
insert into geeks values(2, 'Praveen',97);
insert into geeks values(3, 'Jessie', 99);

1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows. For eg:

DECLARE
temp varchar(20);

BEGIN

SELECT g_id into temp from geeks where g_name='GeeksforGeeks';

exception

WHEN no_data_found THEN

dbms_output.put_line('ERROR');

dbms_output.put_line('there is no name as');

dbms_output.put_line('GeeksforGeeks in geeks table');

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

-- raises an exception as SELECT

-- into trying to return too many rows

SELECT g_name into temp from geeks;

dbms_output.put_line(temp);

EXCEPTION

WHEN too_many_rows THEN


dbms_output.put_line('error trying to SELECT too many rows');

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

SELECT g_name into temp from geeks where g_name='Suraj';

dbms_output.put_line('the g_name is '||temp);

EXCEPTION

WHEN value_error THEN

dbms_output.put_line('Error');

dbms_output.put_line('Change data type of temp to varchar(20)');

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;

dbms_output.put_line('the result after division is'||answer);

exception

WHEN zero_divide THEN

dbms_output.put_line('dividing by zero please check the values again');

dbms_output.put_line('the value of a is '||a);

dbms_output.put_line('the value of b is '||b);

END;

Output:
dividing by zero please check the values again
the value of a is 10
the value of b is 0

 Unnamed system exceptions:


Oracle doesn’t provide name for some system exceptions called unnamed system
exceptions. These exceptions don’t occur frequently. These exceptions have two parts code and an
associated message.The way to handle to these exceptions is to assign name to them using Pragma
EXCEPTION_INIT

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;

pragma exception_init (exp, -20015);

n int:=10;

BEGIN

FOR i IN 1..n LOOP

dbms_output.put_line(i*i);

IF i*i=36 THEN

RAISE exp;

END IF;

END LOOP;

EXCEPTION

WHEN exp THEN

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

x int:=&x; /*taking value at run time*/

y int:=&y;

div_r float;

exp1 EXCEPTION;

exp2 EXCEPTION;

BEGIN

IF y=0 then

raise exp1;

ELSEIF y > x then

raise exp2;

ELSE

div_r:= x / y;

dbms_output.put_line('the result is '||div_r);

END IF;

EXCEPTION
WHEN exp1 THEN

dbms_output.put_line('Error');

dbms_output.put_line('division by zero not allowed');

WHEN exp2 THEN

dbms_output.put_line('Error');

dbms_output.put_line('y is greater than x please check the input');

END;

Input 1: x = 20
y = 10

Output: the result is 2


Input 2: x = 20
y=0

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

FOR i IN 1..n LOOP

dbms_output.put_line(i*i);

IF i*i=36 THEN

RAISE myex;

END IF;

END LOOP;

EXCEPTION

WHEN myex THEN

RAISE_APPLICATION_ERROR(-20015, 'Welcome to GeeksForGeeks'); END;

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.

Scope rules in exception handling:


 We can’t DECLARE an exception twice but we can DECLARE the same exception in two
different blocks.
 Exceptions DECLARE inside a block are local to that block and global to all its sub-blocks.
As a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions .
DECLARE in a sub-block
If we re DECLARE a global exception in a sub-block, the local declaration prevails i.e. the scope of local is
more.
Example:

DECLARE

GeeksforGeeks EXCEPTION;

age NUMBER:=16;

BEGIN

-- sub-block BEGINs

DECLARE

-- this declaration prevails

GeeksforGeeks EXCEPTION;

age NUMBER:=22;

BEGIN

IF age > 16 THEN

RAISE GeeksforGeeks; /* this is not handled*/

END IF;

END;

-- sub-block ends

EXCEPTION

-- Does not handle raised exception

WHEN GeeksforGeeks THEN

DBMS_OUTPUT.PUT_LINE
('Handling GeeksforGeeks exception.');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE

('Could not recognize exception GeeksforGeeks in this scope.');

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 ..

.. check for 'no data found' error

Select ..

.. check for 'no data found' error

Select ..

.. check for 'no data found' error

 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

WHEN NO_DATA_FOUND THEN /* catches all 'no data found' errors */

...

WHEN ZERO_DIVIDE THEN /* different types of */

WHEN value_error THEN /* errors handled in same block */

...
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.

16.3 PL/SQL RAISE Exceptions


Exceptions in PL/SQL are mechanisms used to manage runtime errors and unexpected situations
that may occur during the execution of a PL/SQL block. By raising exceptions, you can gracefully handle
errors, ensure data integrity, and provide meaningful error messages to users or developers. There are
three main types of exceptions in PL/SQL:
Table of Content
 User-Defined Exception
 Internally Defined Exception
 Current Exception

How to Raise Exceptions in PL/SQL?


PL/SQL provides structured ways to raise exceptions within code blocks. This process involves using
the RAISE statement to trigger an error, followed by catching it in an EXCEPTION block.

Syntax:

DECLARE

custom_exception EXCEPTION;

BEGIN

-- Some condition that may warrant raising a user-defined exception

IF some_condition THEN

-- Raise a user-defined exception

RAISE custom_exception;

END IF;

-- Rest of the code...

EXCEPTION

WHEN custom_exception THEN

-- Handle the user-defined exception


DBMS_OUTPUT.PUT_LINE('Custom exception handled!');

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.

16.3.1 User-Defined Exception


It is a type of exception that is defined by a developer to handle specific error conditions or
business rules in their PL/SQL code. we can declare a user-defined exception using the EXCEPTION keyword
and we can raise it using the RAISE statement.
Example:

DECLARE

custom_exception EXCEPTION;

BEGIN

IF true THEN

-- If a specific condition is met, raise the user-defined exception

RAISE custom_exception;

END IF;

EXCEPTION

WHEN custom_exception THEN

DBMS_OUTPUT.PUT_LINE('Custom exception handled!');

END;

Output:

Statement processed.

Custom exception handled!

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

-- Some computation that might cause an internally defined exception

result := 10 / 0; -- This will raise ZERO_DIVIDE exception

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Cannot divide by zero!');

END;

Output:

Statement processed.

Cannot divide by zero!

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.

16.3.3 Current Exception


It is a type of exception that is currently being handled in the PL/SQL block. It is useful in nested
blocks where an exception might be raised in an inner block and you want to reference that specific
exception in an outer block. SQLERRM function is used to refer current exception.

Example:

DECLARE

custom_exception EXCEPTION;
BEGIN

BEGIN

-- Some operation that might raise an exception

RAISE custom_exception;

EXCEPTION

WHEN OTHERS THEN

-- Handle the exception and reference the current exception

DBMS_OUTPUT.PUT_LINE('Exception handled: ' || SQLERRM);

END;

END;

Output:

Statement processed.

Exception handled: User-Defined Exception

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.

16.4 Example: Using Exceptions in PL/SQL


The below example is demonstrating the use of user-defined exceptions in a real-world scenario. It
illustrates how to create a table, a PL/SQL procedure, and handle exceptions related to a specific business
rule (salary limit).

Step 1: Create a employee table

CREATE TABLE employee (

emp_id NUMBER PRIMARY KEY,

emp_name VARCHAR2(50),

emp_salary NUMBER

);
Step 2: Create a Procedure with an Exception

CREATE OR REPLACE PROCEDURE insert_employee(

p_emp_id NUMBER,

p_emp_name VARCHAR2,

p_emp_salary NUMBER

IS

emp_salary_limit EXCEPTION;

BEGIN

-- Check if the salary is within the allowed limit

IF p_emp_salary > 100000 THEN

-- If not, raise a user-defined exception

RAISE emp_salary_limit;

ELSE

-- Insert the employee details into the table

INSERT INTO employee(emp_id, emp_name, emp_salary)

VALUES (p_emp_id, p_emp_name, p_emp_salary);

DBMS_OUTPUT.PUT_LINE('Employee inserted successfully.');

END IF;

EXCEPTION

WHEN emp_salary_limit THEN

-- Handle the user-defined exception

DBMS_OUTPUT.PUT_LINE('Error: Employee salary exceeds the allowed limit.');

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

1. Attempt to Insert an Employee with a High Salary

DECLARE

emp_id_param NUMBER := 101;

emp_name_param VARCHAR2(50) := 'John Doe';

emp_salary_param NUMBER := 120000;

BEGIN

insert_employee(emp_id_param, emp_name_param, emp_salary_param);

END;

Output:

Statement processed. high salary

Error: Employee salary exceeds the allowed limit.

2. Attempt to Insert an Employee with a Low Salary

DECLARE

emp_id_param NUMBER := 101;

emp_name_param VARCHAR2(50) := 'John Doe';

emp_salary_param NUMBER := 10000;

BEGIN

insert_employee(emp_id_param, emp_name_param, emp_salary_param);

END;

Output:

Statement processed.

Employee inserted successfully.


Important Points About PL/SQL Exceptions
 You can explicitly raise exceptions using the RAISE statement. This can be used to raise user-defined
exceptions or even predefined exceptions based on specific conditions.
 PL/SQL supports nested blocks, where exceptions raised in an inner block can be handled by outer blocks.
 Exceptions should be used primarily for error handling, not for regular control structures.
 Use meaningful names for user-defined exceptions to clearly indicate the nature of the error.

17. PL/SQL RECORDS & CURSORS


PL/SQL empowers you to manage large datasets efficiently with records and cursors. Records act as
strongly-typed structures, mirroring database table definitions to hold retrieved data. Cursors, on the other
hand, function as iterators, allowing you to process data one row at a time. Explore this section to get an
overview on PL/SQL RECORDS and CURSORS.

 PL/SQL Record
 PL/SQL Cursors
 PL/SQL Cursor Update
 PL/SQL Cursor FOR LOOP
 PL/SQL Cursors with Parameters
 PL/SQL REF CURSOR

17.1 Cursors in PL/SQL


 A Cursor in PL/SQL is a pointer to a context area that stores the result set of a query.
 The cursor is used to retrieve data one row at a time from the results set, unlike other SQL
commands that operate on all rows at once.
 Cursors update table records in a singleton or row-by-row manner.

 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.

17.1.1 Explicit cursor


An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.

Syntax for creating cursor

CURSOR cursor_name IS select_statement;

Where,

 cursor_name: A suitable name for the cursor.


 select_statement: A select query which returns multiple rows

How to use Explicit Cursor?


There are four steps in using an Explicit Cursor.

1. DECLARE the cursor in the Declaration section.


2. OPEN the cursor in the Execution Section.
3. FETCH the data from the cursor into PL/SQL variables or records in the Execution Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

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;

process the records;


END LOOP;
CLOSE cursor_name;
END;

17.2 PL/SQL Cursor Update


Updatable cursors are used to perform manipulation operations such as deleting,
inserting, and updating rows. FOR UPDATE keyword is used in cursor declaration. Updation can be
performed with FOR UPDATE and FOR UPDATE OF keyword. FOR UPDATE locks the selected row so another
transaction can’t access it. FOR UPDATE OF is used to provide the column for which the row should be
locked.

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

Example 1: Updating Geeks Table Scores Using For UPDATE in PL/SQL


Update the score from the Geeks table using FOR UPDATE.
Query:

SET SERVEROUTPUT ON;


DECLARE
CURSOR cursor_geek IS
SELECT Id, Name, Score
FROM Geeks
FOR UPDATE;
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 cursor_geek;
LOOP
FETCH cursor_geek INTO variable_id, variable_name, variable_score;
EXIT WHEN cursor_geek%NOTFOUND;
-- update
UPDATE Geeks
SET Score = variable_score + 100
WHERE CURRENT OF cursor_geek;
END LOOP;
CLOSE cursor_geek;
COMMIT;
--Print the updated table
DBMS_OUTPUT.PUT_LINE('TABLE AFTER UPDATES');
FOR element IN (SELECT * FROM Geeks) LOOP
DBMS_OUTPUT.PUT_LINE(element.Id || ' ' || element.Name || ' ' || element.Score);
END LOOP;
END;
/

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

Example 2: Updating Geeks Table Scores Using For UPDATE OF in PL/SQL


Update the score from the Geeks table using FOR UPDATE OF.

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:

SET SERVEROUTPUT ON;

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;

-- Print the updated table


DBMS_OUTPUT.PUT_LINE('TABLE AFTER UPDATES');
FOR element IN (SELECT * FROM Geeks) LOOP
DBMS_OUTPUT.PUT_LINE(element.Id || ' ' || element.Name || ' ' || element.Score);
END LOOP;
END;
/
Output:

Explanation: FOR UPDATE OF keyword is used to lock the score column from the geeks table.

Advantages and Disadvantages of the Updatable Cursors


Advantages
 It is used to insert,update, and delete rows from the table.
 It provides a more efficient way than SQL statements.
 It performs updation in less number of round trips between the database and the application.
Disadvantages
 It may increase complexity while handling multiple tables from the database.
 It may not support updates on aggregations or joins.
 It may face concurrency issues if another process is going on.

17.3 PL/SQL Parameterized Cursors


Oracle uses a special memory space called a context area for storing and retrieving information. The
context area contains all the details related to the database. The cursor is the virtual pointer to the context
area, in the database. The cursor helps you to process through the rows one by one. There are two types of
cursors Implicit cursor and Explicit cursor.
 Implicit Cursor: In the implicit cursor SELECT INTO, INSERT, UPDATE, and DELETE queries are used,
without declaring the cursor with a cursor name in the declaration block.
 Explicit Cursor: In explicit cursor, the cursor is declared with a particular name to fetch or add data
through the rows one by one. It is declared in the declaration section of the PL/SQL block.

PL/SQL Cursors with Parameters


The cursor can be declared with the parameter or without the parameter. It can have any number
of parameters as per requirement. Cursors with Parameters are used to work with particular data.
Parameters are used to create reusable and adaptable code. Explicit cursors may be declared with
parameters. The parameter contains a variable and its datatype. The parameter can have a default value
associated with a variable.

Syntax:

DECLARE

declare variables;

--create a cursor with parameter;

BEGIN OPEN cursor;

FETCH cursor;

-- process the rows

CLOSE cursor;

END;

Example of a Parameterized Cursor


GFG cursor is initialized with a parameter to retrieve the Id, name, and rank of Geek from the Geeks Table.
The requested data must satisfy the specified condition.

SET SERVEROUTPUT ON;

DECLARE

CURSOR GFG (Min_rank NUMBER) IS

SELECT Id, name, rank

FROM Geeks

WHERE rank > Min_rank;

-- 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

FETCH GFG INTO cur_id, cur_name, cur_rank;

EXIT WHEN GFG%NOTFOUND;

-- Process fetched data

DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name || ', Rank: ' ||
cur_rank);

-- Close the loop

END LOOP;

-- Close the cursor

CLOSE GFG;

END;

Output:

Cursor with Parameter


Table: Establishing a table named Geeks and adding data to it.

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.

17.4 PL/SQL Parameterized Cursor with Default Value


Default values can be passed in the parameterized cursor. If default values are passed in the
parameterized cursor in the DECLARE block, the cursor can be called without argument in the BEGIN block if
default values are to be used. If arguments are mentioned then they overwrite the default value.
Syntax:

DECLARE

declare variables;

create a cursor with default value for parameter;

BEGIN OPEN cursor;

FETCH cursor;

process the rows;

CLOSE cursor;

END;

Example of PL/SQL Parameterized Cursor with Default Value


GFG cursor is initialized with a default value for the parameter to retrieve the Id, name, and rank of
Geek from the Geeks Table. The requested data must satisfy the specified condition mentioned in the cursor.
PL/SQL

SET SERVEROUTPUT ON;

DECLARE

--default value for the parameter

CURSOR GFG (Min_rank NUMBER :=951) IS

SELECT Id, name, rank

FROM Geeks

WHERE rank > Min_rank;

-- 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 and fetch data using the cursor with no argument

OPEN GFG;

LOOP

FETCH GFG INTO cur_id, cur_name, cur_rank;

EXIT WHEN GFG%NOTFOUND;

-- Process fetched data

DBMS_OUTPUT.PUT_LINE('ID: ' || cur_id || ', Name: ' || cur_name || ', Rank: ' ||
cur_rank);

-- Close the loop

END LOOP;

-- Close the cursor

CLOSE GFG;

END;

Output of Parameterized Cursor with Default Value:

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.

18. PL/SQL PACKAGES


PL/SQL packages are like treasure chests for your code. They group related functions, procedures,
variables, and more into a single unit. This keeps your code organized, reusable, and hides internal workings
for cleaner applications.
 PL/SQL Package
 PL/SQL Package Specification
 PL/SQL Package Body

18.1 PL/SQL packages


 Are a way to organize and encapsulate related procedures, functions, variables, triggers, and other
PL/SQL items into a single item Packages provide a modular approach to write and maintain the
code. It makes it easy to manage large codes.
 A package is compiled and then stored in the database, which then can be shared with many
applications. The package also has specifications, which declare an item to be public or private.
Public items can be referenced from outside of the package.
 A PL/SQL package is a collection of related Procedures, Functions, Variables, and other elements
that are grouped for Modularity and Reusability.
Key Benefits of Using PL/SQL Packages
The needs of the Packages are described below:
 Modularity: Packages provide a modular structure, allowing developers to organize and manage code
efficiently.
 Code Reusability: Procedures and functions within a package can be reused across multiple programs,
reducing redundancy.
 Private Elements: Packages support private procedures and functions, limiting access to certain code
components.
 Encapsulation: Packages encapsulate related logic, protecting internal details and promoting a clear
interface to other parts of the code.
Structure of a PL/SQL Package
A PL/SQL package consists of two parts:
1. A package Specification
2. A package Body

18.2 Package Specification


The package specification declares the public interface of the package. It includes declarations
of procedures, functions, variables, cursors, and other constructs that are meant to be accessible from
outside the package. The specification is like a header file that defines what a package can do.

Example of Package Specification:

CREATE OR REPLACE PACKAGE my_package AS


PROCEDURE my_procedure(p_param1 NUMBER);

FUNCTION calculate_sum(x NUMBER, y NUMBER) RETURN NUMBER;

-- Other declarations...

END my_package;

18.3 Package Body


The package body contains the implementation of the details of the package. It includes the coding
of the procedures or functions which are decalared in the package specification. The body can also contain
private variables and procedures that are not exposed to outside the code.

Example of Package Body:

CREATE OR REPLACE PACKAGE BODY my_package AS

PROCEDURE my_procedure(p_param1 NUMBER) IS

BEGIN

-- Implementation code...

END my_procedure;

FUNCTION calculate_sum(x NUMBER, y NUMBER) RETURN NUMBER IS

BEGIN

-- Implementation code...

END calculate_sum;

-- Other implementation details...

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.

Using Oracle PL/SQL Packages in Code

DECLARE

result NUMBER;
BEGIN

-- Call a procedure from the package

my_package.my_procedure(42);

-- Call a function from the package

result := my_package.calculate_sum(10, 20);

-- Other code...

END;

Here, my_procedure is called with the value 42, and the result of calculate_sum(10, 20) is displayed.

PL/SQL Packages Examples

Example 1: Creating a Basic Arithmetic Package in PL/SQL


Let’s look at an example where we define a package to perform basic arithmetic operations.
XML

-- Enable the display of server output

SET SERVEROUTPUT ON;

-- Create a PL/SQL package specification

CREATE OR REPLACE PACKAGE math_operations AS

-- Procedure to add two numbers with an output parameter

PROCEDURE add_numbers(x NUMBER, y NUMBER, result OUT NUMBER);

-- Function to multiply two numbers

FUNCTION multiply_numbers(x NUMBER, y NUMBER) RETURN NUMBER;

END math_operations;

/
-- Create the body of the math_operations package

CREATE OR REPLACE PACKAGE BODY math_operations AS

-- Implementation of the add_numbers procedure

PROCEDURE add_numbers(x NUMBER, y NUMBER, result OUT NUMBER) IS

BEGIN

result := x + y;

END add_numbers;

-- Implementation of the multiply_numbers function

FUNCTION multiply_numbers(x NUMBER, y NUMBER) RETURN NUMBER IS

BEGIN

RETURN x * y;

END multiply_numbers;

END math_operations;

-- PL/SQL block to test the math_operations package

DECLARE

-- Declare variables to store results

sum_result NUMBER;

product_result NUMBER;

BEGIN

-- Call the procedure and pass output parameter


math_operations.add_numbers(5, 7, sum_result);

-- Display the result of the add_numbers procedure

DBMS_OUTPUT.PUT_LINE('Sum Result: ' || sum_result);

-- Call the function and retrieve the result

product_result := math_operations.multiply_numbers(3, 4);

-- Display the result of the multiply_numbers function

DBMS_OUTPUT.PUT_LINE('Product Result: ' || product_result);

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.

Example 2: Implementing Employee Calculations with a PL/SQL Package


In this example, we create a package to calculate employee-related details.

-- Enable the display of server output

SET SERVEROUTPUT ON;

-- Create a PL/SQL package specification for employee_operations

CREATE OR REPLACE PACKAGE employee_operations AS


-- Procedure to calculate annual salary

PROCEDURE calculate_annual_salary(monthly_salary NUMBER, annual_salary OUT


NUMBER);

-- Function to get the full name of an employee

FUNCTION get_full_name(first_name VARCHAR2, last_name VARCHAR2) RETURN


VARCHAR2;

END employee_operations;

-- Create the body of the employee_operations package

CREATE OR REPLACE PACKAGE BODY employee_operations AS

-- Implementation of the calculate_annual_salary procedure

PROCEDURE calculate_annual_salary(monthly_salary NUMBER, annual_salary OUT


NUMBER) IS

BEGIN

-- Assuming 12 months in a year for simplicity

annual_salary := monthly_salary * 12;

END calculate_annual_salary;

-- Implementation of the get_full_name function

FUNCTION get_full_name(first_name VARCHAR2, last_name VARCHAR2) RETURN


VARCHAR2 IS

BEGIN

-- Concatenate the first and last names

RETURN first_name || ' ' || last_name;


END get_full_name;

END employee_operations;

-- PL/SQL block to test the employee_operations package

DECLARE

-- Declare variables

annual_salary_result NUMBER;

full_name_result VARCHAR2(100);

BEGIN

-- Call the procedure to calculate annual salary

employee_operations.calculate_annual_salary(5000, annual_salary_result);

-- Display the result of the calculate_annual_salary procedure

DBMS_OUTPUT.PUT_LINE('Annual Salary: ' || annual_salary_result);

-- Call the function to get the full name

full_name_result := employee_operations.get_full_name('Chetan', 'Singh');

-- Display the result of the get_full_name function

DBMS_OUTPUT.PUT_LINE('Full Name: ' || full_name_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

19. PL/SQL TRIGGERS


PL/SQL triggers are special procedures that automatically executes (or “trigger”) in response to certain
events, such as data changes.
 PL/SQL Triggers
 PL/SQL Statement-level Triggers
 PL/SQL Row-level Triggers
 PL/SQL INSTEAD OF Triggers
 PL/SQL Disable Triggers
 PL/SQL Enable Triggers
 PL/SQL Drop Triggers
 PL/SQL Fixing Mutating Table Error

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.

PL/SQL Trigger Structure


Triggers are fired on the tables or views which are in the database. Either table, view, schema, or a
database are the basic requirement to execute a trigger. The trigger is specified first and then the action
statement are specified later.

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 .

Types of PL/SQL Triggers


Trigger timing and operations forms different combinations such as BEFORE INSERT OR BEFORE
DELETE OR BEFORE UPDATE .BEFORE and AFTER are known as conditional triggers.

1. Conditional Trigger: Before


Trigger is activated before the operation on the table or view is performed.

Query:
-- Create Geeks table
CREATE TABLE Geeks (
Id INT,
Name VARCHAR2(20),
Score INT
);

-- Insert into Geeks Table


INSERT INTO Geeks (Id, Name, Score) VALUES (1, 'Sam', 800);
INSERT INTO Geeks (Id, Name, Score) VALUES (2, 'Ram', 699);
INSERT INTO Geeks (Id, Name, Score) VALUES (3, 'Tom', 250);
INSERT INTO Geeks (Id, Name, Score) VALUES (4, 'Om', 350);
INSERT INTO Geeks (Id, Name, Score) VALUES (5, 'Jay', 750);
-- insert statement should be written for each entry in Oracle Sql Developer

CREATE TABLE Affect (


Id INT,
Name VARCHAR2(20),
Score INT
);

-- BEFORE INSERT trigger


CREATE OR REPLACE TRIGGER BEFORE_INSERT
BEFORE INSERT ON Geeks
FOR EACH ROW
BEGIN
INSERT INTO Affect (Id, Name, Score)
VALUES (:NEW.Id, :NEW.Name, :NEW.Score);
END;
/
INSERT INTO Geeks (Id, Name, Score) VALUES (6, 'Arjun', 500);

2. BEFORE DELETE Trigger

-- BEFORE DELETE trigger


CREATE OR REPLACE TRIGGER BEFORE_DELETE
BEFORE DELETE ON Geeks
FOR EACH ROW
BEGIN
INSERT INTO Affect (Id, Name, Score)
VALUES (:OLD.Id, :OLD.Name, :OLD.Score);
END;
/
DELETE FROM Geeks WHERE Id = 3;
3. BEFORE UPDATE Trigger

-- BEFORE UPDATE trigger


CREATE OR REPLACE TRIGGER BEFORE_UPDATE
BEFORE UPDATE ON Geeks
FOR EACH ROW
BEGIN
INSERT INTO Affect (Id, Name, Score)
VALUES (:OLD.Id, :OLD.Name, :OLD.Score);
END;
/
UPDATE Geeks SET Score = 900 WHERE Id = 5;
SELECT * FROM Affect;
SELECT * FROM Geeks;

Output:

Conditional Trigger Before


Explanation:
 BEFORE_INSERT Trigger is fired before adding a row in Geeks Table,and row is inserted in the Affect
table.
 BEFORE_DELETE Trigger is activated before the row is delete from the Geeks table and row which
satisfy the condition is added to Affect table.
 BEFORE_UPDATE TRIGGER is activated before the row with Id=5 is updated and row with old values is
added to Affect table
Geeks table after trigger events

4. Conditional Trigger Before

5. Conditional Trigger: After


Trigger is activated after the operation on the table or view is performed.
Query:

SET SERVEROUTPUT ON;

CREATE TABLE Geeks (


Id INT,
Name VARCHAR2(20),
Score INT
);

-- Insert into Geeks Table


INSERT INTO Geeks (Id, Name, Score) VALUES (1, 'Sam', 800);
INSERT INTO Geeks (Id, Name, Score) VALUES (2, 'Ram', 699);
INSERT INTO Geeks (Id, Name, Score) VALUES (3, 'Tom', 250);
INSERT INTO Geeks (Id, Name, Score) VALUES (4, 'Om', 350);
INSERT INTO Geeks (Id, Name, Score) VALUES (5, 'Jay', 750);
-- insert statement should be written for each entry in Oracle Sql Developer

CREATE TABLE Affect (


Id INT,
Name VARCHAR2(20),
Score INT
);
SELECT * FROM Geeks;
-- AFTER DELETE trigger
CREATE OR REPLACE TRIGGER AFTER_DELETE
AFTER DELETE ON Geeks
FOR EACH ROW
BEGIN
INSERT INTO Affect (Id, Name, Score)
VALUES (:OLD.Id, :OLD.Name, :OLD.Score);
END;
/
DELETE FROM Geeks WHERE Id = 4;

-- AFTER UPDATE trigger


CREATE OR REPLACE TRIGGER AFTER_UPDATE
AFTER UPDATE ON Geeks
FOR EACH ROW
BEGIN
INSERT INTO Affect (Id, Name, Score)
VALUES (:NEW.Id, :NEW.Name, :NEW.Score);
END;
/
UPDATE Geeks SET Score = 1050 WHERE Id = 5;
SELECT * FROM Affect;
SELECT * FROM Geeks;

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;

20. PL/SQL COLLECTIONS


PL/SQL collections organize your data like a pro. Imagine grouping related information together –
names and addresses, product IDs and stock levels. These collections, called VARRAYs, nested tables, and
associative arrays, streamline data manipulation and enhance code readability.

 PL/SQL Associative Array


 PL/SQL Nested Tables
 PL/SQL VARRAY

You might also like