Sub topic 10
Repeating While a Condition Holds: WHILE LOOP
This chapter assumes that you know basic SQL, anonymous PL/SQL blocks, scalar variables, and how to run a script with DBMS_OUTPUT enabled.
A WHILE LOOP repeats a group of statements while its condition evaluates to TRUE. PL/SQL tests the condition before every iteration. If the condition is FALSE or NULL before the first test, the loop runs zero times.
Basic WHILE LOOP
The general form is:
WHILE condition LOOP
statements;
END LOOP;The statements must change something that can eventually make the condition false. Otherwise, the block can run forever.
This example subtracts four until the value is zero or negative:
DECLARE
l_n PLS_INTEGER := 14;
BEGIN
WHILE l_n > 0 LOOP
DBMS_OUTPUT.PUT_LINE('Before: ' || l_n);
l_n := l_n - 4;
END LOOP;
DBMS_OUTPUT.PUT_LINE('After: ' || l_n);
END;
/The output is:
Before: 14
Before: 10
Before: 6
Before: 2
After: -2When l_n is -2, the condition l_n > 0 is FALSE, so PL/SQL stops before another iteration.
The condition must make progress
A common error is forgetting to update the variable used by the condition:
DECLARE
l_n PLS_INTEGER := 1;
BEGIN
WHILE l_n <= 3 LOOP
DBMS_OUTPUT.PUT_LINE(l_n);
l_n := l_n + 1;
END LOOP;
END;
/Here, l_n increases on every iteration. The loop prints 1, 2, and 3, then stops when l_n becomes 4.
A WHILE LOOP is useful when the number of iterations is not known in advance. For example, an application might retry work while a status remains PENDING. Use a numeric FOR LOOP when you already have a clear numeric range.
Conditions involving NULL
PL/SQL uses three-valued logic: a condition can be TRUE, FALSE, or NULL. A comparison with NULL usually produces NULL, not TRUE.
Therefore, this loop does not run:
DECLARE
l_limit NUMBER := NULL;
l_n NUMBER := 1;
BEGIN
WHILE l_n <= l_limit LOOP
DBMS_OUTPUT.PUT_LINE(l_n);
l_n := l_n + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The loop did not start');
END;
/Test missing values explicitly with IS NULL or IS NOT NULL before entering the loop.
WHILE LOOP versus basic LOOP
A WHILE LOOP checks its condition before the body. A basic LOOP always enters the body at least once and requires EXIT or EXIT WHEN to stop. Choose WHILE LOOP when the precondition naturally describes whether another iteration is allowed.
Exercise
What happens if l_n starts at 0 in WHILE l_n > 0 LOOP?
Show answer
The body runs zero times because the condition is FALSE before the first iteration.