Sub topic 9
The Basic LOOP with EXIT and EXIT WHEN
This chapter assumes that you can declare variables and run an anonymous PL/SQL block with DBMS_OUTPUT enabled. A basic LOOP repeats its statements until execution reaches an EXIT statement. PL/SQL does not stop a basic loop automatically, so every useful basic loop needs a reachable exit condition.
The loop’s working model
The structure is:
LOOP
statements;
EXIT WHEN condition;
END LOOP;PL/SQL runs the statements from top to bottom. When it reaches END LOOP, it returns to the first statement and starts another iteration. EXIT leaves the innermost loop immediately. EXIT WHEN condition leaves the loop only when the condition evaluates to TRUE.
Using EXIT
You can place EXIT inside an IF statement when the exit rule needs more context:
DECLARE
l_n PLS_INTEGER := 0;
l_total PLS_INTEGER := 0;
BEGIN
LOOP
l_n := l_n + 1;
IF l_n > 3 THEN
EXIT;
END IF;
l_total := l_total + l_n;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/The loop increments l_n on every iteration. When l_n becomes 4, the IF executes EXIT. The value 4 is therefore not added to l_total, and the output is:
Total: 6An unconditional EXIT is useful when several statements determine whether processing is complete. However, the exit must be reachable. If no execution path reaches it, the block contains an infinite loop.
Using EXIT WHEN
EXIT WHEN expresses the same pattern more directly:
DECLARE
l_n PLS_INTEGER := 0;
l_total PLS_INTEGER := 0;
BEGIN
LOOP
l_n := l_n + 1;
EXIT WHEN l_n > 3;
l_total := l_total + l_n;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/The position of EXIT WHEN matters. Here, the condition is tested after incrementing l_n and before adding it. Moving the exit test changes which values the loop processes.
| Form | Meaning |
|---|---|
| `EXIT;` | Leave the innermost loop now |
| `EXIT WHEN condition;` | Leave when `condition` is `TRUE` |
| `END LOOP;` | Return to the start unless the loop was exited |
Choosing a basic LOOP
Use a basic LOOP when the stopping point is naturally in the middle of the work, or when the loop may finish through more than one exit path. Use a WHILE LOOP when the condition should be checked before the first iteration. Use a numeric FOR LOOP when the number range is known.
Exercise
What is the output of the following block, and why is 0 included?
Show answer
It prints 0, 1, and 2. The exit test runs after the value is printed, so the loop exits only when l_n becomes 3.