control_stmt_plsql
control_stmt_plsql
PL/SQL (Procedural Language/Structured Query Language) is Oracle’s extension to SQL that allows for
procedural programming within databases. It features various conditional statements to control the flow
of execution based on specific conditions.
In this article, We will learn about the various PL/SQL Conditional Statements in detail with the help of
examples and so on.
IF THEN
IF THEN ELSE
NESTED-IF-THEN
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:
declare
begin
if condition then
dbms_output.put_line('output');
end if;
dbms_output.put_line('output2');
end;
declare
begin
dbms_output.put_line('num1 small');
end if;
end;
As the condition present in the if statement is false. So, the block below the if statement is not executed.
Output:
I am Not in if
2. IF THEN ELSE
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when
the condition is false.
Syntax:-
if (condition) then
-- condition is true
else
-- condition is false
Example:-
declare
begin
dbms_output.put_line('i am in if block');
ELSE
end if;
end;
Output:-
i'm in if 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
if (condition2) then
end if;
end if;
declare
begin
end if;
end if;
dbms_output.put_line('after end if');
end;
Output:-
after end if
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
--statement
else
--statement
endif
Example:-
declare
dbms_output.put_line('num1 small');
dbms_output.put_line('both equal');
ELSE
dbms_output.put_line('num2 greater');
end if;
end;
Output:-
num1 small
after end if
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;
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;
PL/SQL Loops
Last Updated : 18 Oct, 2024
PL/SQL stands for Procedural Language Extension to the Structured Query Language
and it is designed specifically for Oracle databases it extends Structured Query
Language (SQL) capabilities by allowing the creation of stored
procedures, functions, and triggers. It is a block-structured language that combines
SQL with the procedural features of programming languages.
In this article, we will learn about How to use the Loop statement of PL/SQL with all its
features like EXIT, EXIT WHEN, and Nested Loop for example.
LOOP Statement in PL/SQL
One of the key features in PL/SQL for controlling program flow is the LOOP statement.
The LOOP statement is a feature of PL/SQL that allows you to repeatedly execute a
block of code until a specified condition is satisfied.
Procedural Language/Structured Query Language (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
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');
EXIT WHEN counter > 5; -- Exit the loop when counter exceeds 5
END LOOP;
END;
/
Output:
Statement processed.
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
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);
Oracle PL/SQL provides various loop structures that help developers execute a block of
code multiple times based on certain conditions. The main loop structures
include LOOP ... END LOOP, WHILE ... END LOOP, and FOR ... END LOOP. In this
article, we will explore the WHILE loop in detail, including its syntax, usage scenarios,
and examples. We'll also discuss controlling the loop flow using statements like EXIT
and EXIT WHEN.
What is a WHILE Loop in PL/SQL?
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;
condition: A Boolean expression that determines whether the loop will continue
executing. If it evaluates to TRUE, the loop executes the block of code inside. If FALSE
or NULL, the loop exits.
LOOP: Marks the beginning of the code block to be executed.
END LOOP: Marks the end of the loop block.
Examples of PL/SQL WHILE Loop
Let's look at some examples to better understand how to use the WHILE loop effectively
in different scenarios.
Example 1: Using PL/SQL WHILE Loop for Iterative Execution
In this example, we look 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);
PL/SQL stands for Procedural Language/ Structured Query Language. 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
Here, we look into the versatility of the PL/SQL FOR loop, a key construct for procedural
programming in Oracle databases, explore its syntax, provide examples of its
application, demonstrate the use of the REVERSE keyword for reverse iteration, and
discuss the effectiveness of nested FOR loops.
FOR LOOP in PL/SQL
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:
PL/
SQL FOR LOOP
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.
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:
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.
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:
F
OR LOOP WITH REVERSE KEYWORD
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.