PL/SQL WHILE Loop

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:

WHILE condition
LOOP
   sequence_of_statements;
END LOOP;Code language: SQL (Structured Query Language) (sql)

A condition is a Boolean variable or expression that evaluates to a Boolean value of TRUE, FALSE or NULL. The condition is checked at the beginning of each iteration.

  • If the condition evaluates to TRUE, the sequence_of_statements is executed.
  • If the condition evaluates to FALSE or NULL, the loop terminates and control is passed to the next executable statement following the END LOOP keywords.

It is important to note that the sequence of statements may not execute at all if the condition evaluates to  FALSE or NULL before entering the loop.

In addition, inside the loop you have to update some variables to make the condition becomes to FALSE or NULL at some points to terminate the loop, otherwise, you will have an endless loop, which causes a stack overflow error.

The PL/SQL 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
PL/SQL WHILE loop

PL/SQL WHILE LOOP example

This example calculates factorial of 10 by using PL/SQL WHILE LOOP statement:

SET SERVEROUTPUT ON SIZE 1000000;
DECLARE
  n_counter   NUMBER := 10;
  n_factorial NUMBER := 1;
  n_temp      NUMBER;
BEGIN
  n_temp := n_counter;
  WHILE n_counter > 0
  LOOP
    n_factorial := n_factorial * n_counter;
    n_counter   := n_counter - 1;
  END LOOP;

  DBMS_OUTPUT.PUT_LINE('factorial of ' || n_temp ||
                       ' is ' || n_factorial);

END;
/Code language: SQL (Structured Query Language) (sql)

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.