Summary: in this tutorial, you will learn how PL/SQL WHILE loop statement to execute a sequence of statements repeatedly based on a condition that is checked at the beginning of each iteration.
Introduction to PL/SQL WHILE Loop
Sometimes, you don’t know in advance how many times a sequence of statements needs to execute because it depends on a condition which is not fixed at compile time. In such cases, you should use PL/SQL
WHILE LOOP statement.
The following illustrates the PL/SQL
WHILE LOOP syntax:
condition is a Boolean variable or expression that evaluates to a Boolean value of
NULL. The condition is checked at the beginning of each iteration.
- If the
- If the
NULL, the loop terminates and control is passed to the next executable statement following the
It is important to note that the sequence of statements may not execute at all if the
condition evaluates to
NULL before entering the loop.
In addition, inside the loop you have to update some variables to make the
condition becomes to
NULL at some points to terminate the loop, otherwise, you will have an endless loop, which causes a stack overflow error.
WHILE loop is effective when you don’t know how many times the loop will execute. If the number of iterations is predetermined, you should use the PL/SQL FOR loop statement instead.
The following flowchart illustrates the PL/SQL
WHILE loop statement:
PL/SQL WHILE LOOP example
This example calculates factorial of 10 by using PL/SQL
WHILE LOOP statement:
SET SERVEROUTPUT ON SIZE 1000000;
n_counter NUMBER := 10;
n_factorial NUMBER := 1;
n_temp := n_counter;
WHILE n_counter > 0
n_factorial := n_factorial * n_counter;
n_counter := n_counter - 1;
DBMS_OUTPUT.PUT_LINE('factorial of ' || n_temp ||
' is ' || n_factorial);
How it works.
- First, we initialize the counter to 10 and factorial to 1.
- Second, in each iteration, we multiply the factorial with the counter and decrease the counter by 1. The loop is terminated when the counter reaches zero.
- Third, we display the result of the factorial of 10.
In this tutorial, you’ve learned how to use PL/SQL
WHILE LOOP statement to execute a sequence of statements repeatedly based on a condition that is checked before each iteration of the loop.