Sub topic 10
Repeating While a Condition Holds: WHILE LOOP
This chapter assumes you can write an anonymous PL/SQL block, declare and assign scalar variables, and run a script with DBMS_OUTPUT enabled. It also assumes you know the basic LOOP with EXIT WHEN and that a condition in PL/SQL can be TRUE, FALSE, or NULL.
What a WHILE LOOP does
A WHILE LOOP repeats a block of statements as long as a Boolean condition is TRUE. The condition is tested before each iteration, including the first one. If it is not TRUE at that moment, the loop body does not run.
WHILE condition LOOP
statements;
END LOOP;Compare this with the basic LOOP, which always runs its body at least once because the EXIT WHEN test usually sits inside the body. A WHILE LOOP can run zero times.
The flow looks like this:
A worked example
The following block starts with 10 and subtracts 4 until the value is no longer positive.
DECLARE
l_n PLS_INTEGER := 10;
BEGIN
WHILE l_n > 0 LOOP
DBMS_OUTPUT.PUT_LINE('l_n = ' || l_n);
l_n := l_n - 4;
END LOOP;
DBMS_OUTPUT.PUT_LINE('After WHILE: ' || l_n);
END;
/The output is:
l_n = 10
l_n = 6
l_n = 2
After WHILE: -2Notice that the loop did not stop exactly at 0. The condition is only checked at the top of each iteration. When l_n became 2, the body ran once more and moved it to -2. Only then did the test l_n > 0 fail. If your logic depends on the value at exit, remember that the body finishes completely before the next test.
Zero iterations
Because the test comes first, a WHILE LOOP is the right choice when "do nothing" is a valid outcome.
DECLARE
l_n PLS_INTEGER := 0;
BEGIN
WHILE l_n > 0 LOOP
DBMS_OUTPUT.PUT_LINE('Never printed');
l_n := l_n - 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Loop body ran zero times');
END;
/A basic LOOP that put the EXIT WHEN at the end of the body would run once here, which may be wrong for the task.
The NULL trap
The loop continues only when the condition is TRUE. FALSE and NULL both end it. This matters because comparing anything with NULL produces NULL, not FALSE.
DECLARE
l_limit NUMBER := NULL;
l_i PLS_INTEGER := 0;
BEGIN
WHILE l_i < l_limit LOOP
l_i := l_i + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Iterations: ' || l_i);
END;
/This prints Iterations: 0. The condition 0 < NULL is NULL, so the loop exits at once, with no error and no warning. A missing limit silently turns the loop into a no-op. If NULL is possible, handle it before the loop, for example with IF l_limit IS NULL THEN ... or NVL(l_limit, 0), so the behavior is deliberate.
Changing the state inside the body
The body must change something that the condition depends on. Otherwise the condition stays TRUE and the loop never ends.
DECLARE
l_n PLS_INTEGER := 1;
BEGIN
WHILE l_n <= 3 LOOP
DBMS_OUTPUT.PUT_LINE('Pass ' || l_n);
-- Missing: l_n := l_n + 1; (the loop would never end)
END LOOP;
END;
/As written, with the update line commented out, this is an infinite loop. In SQL*Plus you would have to interrupt the session, and on a server the session keeps consuming CPU until it is killed. Make a habit of writing the update statement first, or immediately after you write the WHILE line.
Common causes of endless WHILE loops:
- The counter or flag is never updated.
- The update happens inside an
IFbranch that is not always reached. - The update moves the value away from the exit condition, for example adding when you meant to subtract.
- The condition depends on a variable that is NULL, which can also cause the opposite problem: the loop never starts.
Leaving early with EXIT and skipping with CONTINUE
You can use EXIT, EXIT WHEN, CONTINUE, and CONTINUE WHEN inside a WHILE LOOP. This is useful when a second reason to stop appears in the middle of the body.
DECLARE
l_n PLS_INTEGER := 0;
l_total PLS_INTEGER := 0;
BEGIN
WHILE l_n < 100 LOOP
l_n := l_n + 1;
CONTINUE WHEN MOD(l_n, 2) = 0; -- skip even numbers
l_total := l_total + l_n;
EXIT WHEN l_total > 20; -- second stopping rule
END LOOP;
DBMS_OUTPUT.PUT_LINE('n = ' || l_n || ', total = ' || l_total);
END;
/The output is n = 9, total = 25. The odd numbers 1, 3, 5, 7, 9 add up to 25 on the fifth odd value, which exceeds 20, and EXIT WHEN ends the loop even though l_n < 100 is still TRUE.
Be careful with CONTINUE in a WHILE LOOP. It jumps back to the condition test and skips the rest of the body. If the statement that updates the loop variable comes after the CONTINUE, that update is skipped too, and the loop can repeat the same state forever. In the example above, l_n is incremented first, before CONTINUE WHEN, for exactly that reason.
A realistic use: processing until a state is reached
A WHILE LOOP suits cases where you do not know in advance how many iterations you need, and the count is not a simple range. A common pattern is reducing a value until it fits a limit, or walking through a string.
DECLARE
l_text VARCHAR2(100) := 'red,green,blue';
l_pos PLS_INTEGER;
l_token VARCHAR2(30);
BEGIN
WHILE l_text IS NOT NULL LOOP
l_pos := INSTR(l_text, ',');
IF l_pos = 0 THEN
l_token := l_text;
l_text := NULL;
ELSE
l_token := SUBSTR(l_text, 1, l_pos - 1);
l_text := SUBSTR(l_text, l_pos + 1);
END IF;
DBMS_OUTPUT.PUT_LINE('Token: ' || l_token);
END LOOP;
END;
/The output is:
Token: red
Token: green
Token: blueHere the condition l_text IS NOT NULL is deliberate. The body consumes part of the string on each pass, and setting l_text := NULL on the last token is what ends the loop. The condition uses IS NOT NULL and so is always TRUE or FALSE, never NULL.
Choosing WHILE over the other loops
| Situation | Best fit |
|---|---|
| The body must run at least once, for example an initial read | Basic `LOOP` with `EXIT WHEN` |
| The body might run zero times, and the number of passes is not known in advance | `WHILE LOOP` |
| The number of passes is a known integer range | Numeric `FOR LOOP` |
| You are processing each row of a query | Cursor `FOR LOOP` |
A WHILE LOOP also differs from a numeric FOR LOOP in who controls the counter. In a FOR LOOP, PL/SQL declares the counter, increments it, and does not let you assign to it. In a WHILE LOOP, you declare it, initialize it, and update it yourself, so you also own every mistake in doing so. If the task is simply "do this N times", the FOR LOOP removes that class of errors.
Summary of rules
- The condition is tested before every iteration, so the body can run zero times.
- The body continues only when the condition is TRUE. FALSE and NULL both end the loop.
- The body must change the state the condition depends on, or the loop will not terminate.
EXIT,EXIT WHEN,CONTINUE, andCONTINUE WHENall work inside aWHILE LOOP.- Advance the loop state before any
CONTINUE.
Exercise
What does this block print, and why? DECLARE ln PLSINTEGER := 3; BEGIN WHILE ln < 3 LOOP DBMSOUTPUT.PUTLINE('in loop'); ln := ln + 1; END LOOP; DBMSOUTPUT.PUTLINE('done, ln = ' || l_n); END; /
Show answer
It prints only "done, l_n = 3". The condition 3 < 3 is FALSE on the first test, so the body runs zero times and the loop is skipped.
Exercise
This loop never ends. Explain why and fix it without removing the CONTINUE WHEN. DECLARE li PLSINTEGER := 0; BEGIN WHILE li < 5 LOOP CONTINUE WHEN li = 2; li := li + 1; END LOOP; END; /
Show answer
When li reaches 2, CONTINUE WHEN jumps back to the condition test before li := li + 1 runs, so li stays 2 forever. Move the increment above the CONTINUE WHEN (and adjust the test if you want to skip a different value), so that every path through the body advances l_i.
Exercise
In the block below, what does the loop do, and what would you change to make the missing limit an explicit error? DECLARE lmax NUMBER := NULL; li PLSINTEGER := 1; BEGIN WHILE li <= lmax LOOP li := l_i + 1; END LOOP; END; /
Show answer
The condition 1 <= NULL evaluates to NULL, so the loop ends immediately without running its body and without raising an error. To make it an explicit error, test before the loop, for example IF lmax IS NULL THEN RAISEAPPLICATIONERROR(-20001, 'lmax is required'); END IF;