Sub topic 9
The Basic LOOP with EXIT and EXIT WHEN
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 that a condition in PL/SQL can be TRUE, FALSE, or NULL, which the first chapter of this tutorial covers. The basic LOOP is the simplest loop in PL/SQL and the one the other loops build on, so you need to understand how it exits.
The working model
A basic loop has this shape:
LOOP
statements;
END LOOP;It has no condition and no counter. Once the block reaches LOOP, it runs the statements, jumps back to the top, and runs them again. It stops only when something inside the body tells it to. If nothing does, the loop runs forever.
Three consequences follow:
- The body always runs at least once, because nothing is tested before the first pass.
- You decide where the exit test goes. It can sit at the top, in the middle, or at the bottom of the body.
- Writing the exit is your responsibility. The compiler does not check that a basic loop can end.
EXIT and EXIT WHEN
EXIT leaves the innermost enclosing loop immediately. Execution continues with the first statement after END LOOP. You normally put it inside an IF:
IF l_n > 3 THEN
EXIT;
END IF;EXIT WHEN condition is shorthand for exactly that. It is shorter and easier to read, so prefer it when the loop has a single simple reason to stop.
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('Basic loop total: ' || l_total);
END;
/The trace is:
l_nbecomes 1, the test is FALSE, andl_totalbecomes 1.l_nbecomes 2, the test is FALSE, andl_totalbecomes 3.l_nbecomes 3, the test is FALSE, andl_totalbecomes 6.l_nbecomes 4, the test is TRUE, and the loop ends before the addition.
The output is Basic loop total: 6.
Where you put the exit test
Because the test can go anywhere, a basic loop can behave like a pre-test loop or a post-test loop.
DECLARE
l_n PLS_INTEGER := 10;
BEGIN
-- Test at the top: behaves like a WHILE loop, the body may run zero times
LOOP
EXIT WHEN l_n >= 10;
DBMS_OUTPUT.PUT_LINE('Never printed');
END LOOP;
-- Test at the bottom: the body always runs at least once
LOOP
DBMS_OUTPUT.PUT_LINE('Body ran once, l_n = ' || l_n);
EXIT WHEN l_n >= 10;
l_n := l_n + 1;
END LOOP;
END;
/The first loop prints nothing. The second prints one line, because the body runs before the test is reached.
PL/SQL has no separate "do-while" statement, so a test at the bottom of a basic loop is how you write one. Use it when the first pass must happen no matter what, such as a retry of an operation or a prompt that has to run once before you can check the answer.
NULL in an exit condition
EXIT WHEN exits only when the condition is TRUE. FALSE and NULL both mean "keep looping." This is the same rule IF follows, and it causes the most common infinite loop in basic loops.
DECLARE
l_limit NUMBER := NULL;
l_n PLS_INTEGER := 0;
BEGIN
LOOP
l_n := l_n + 1;
DBMS_OUTPUT.PUT_LINE('Iteration ' || l_n);
-- l_n > l_limit is NULL, so only the second operand can end the loop
EXIT WHEN l_n > l_limit OR l_n >= 5;
END LOOP;
END;
/The comparison l_n > l_limit is NULL on every pass. NULL OR FALSE is NULL, so the loop continues. On the fifth pass NULL OR TRUE is TRUE, and the loop stops. If you had written only EXIT WHEN l_n > l_limit, the loop would never end.
A safety guard
A basic loop is easy to write without a way out, so many developers add a guard that caps the number of iterations. This matters most when the exit depends on data you do not control.
DECLARE
c_max_tries CONSTANT PLS_INTEGER := 5;
l_tries PLS_INTEGER := 0;
l_done BOOLEAN := FALSE;
BEGIN
LOOP
l_tries := l_tries + 1;
-- Pretend the work succeeds on the third attempt
l_done := (l_tries = 3);
EXIT WHEN l_done OR l_tries >= c_max_tries;
END LOOP;
IF l_done THEN
DBMS_OUTPUT.PUT_LINE('Succeeded after ' || l_tries || ' tries');
ELSE
DBMS_OUTPUT.PUT_LINE('Gave up after ' || l_tries || ' tries');
END IF;
END;
/After the loop, you check which condition ended it. This prints Succeeded after 3 tries.
Use >= rather than = in guard conditions. If the counter ever skips the exact value, = never matches and the loop never ends.
The classic use: fetching from an explicit cursor
The basic loop is the standard way to read an explicit cursor row by row. This example assumes the Oracle HR sample schema.
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name
FROM employees
WHERE department_id = 50
ORDER BY employee_id;
l_id employees.employee_id%TYPE;
l_name employees.last_name%TYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO l_id, l_name;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_id || ' ' || l_name);
END LOOP;
CLOSE c_emp;
END;
/The order of the statements matters. %NOTFOUND becomes TRUE when a FETCH finds no more rows, so the test must come directly after the FETCH and before you use the variables. When a fetch returns no row, l_id and l_name keep the values from the previous row. If you print first and test afterward, the last row appears twice.
The loop also leaves CLOSE to you. A cursor FOR loop, covered later in this tutorial, does the open, fetch, exit test, and close for you. The explicit form is still worth knowing for cases where you need to control when the cursor opens or closes, or fetch in batches.
Edge cases and gotchas
- EXIT outside a loop is a compile error. An
EXITthat is not inside a loop fails to compile withPLS-00376: illegal EXIT statement; it must appear inside a loop. - EXIT leaves only the innermost loop. In nested loops, an unlabeled
EXITends the inner loop and the outer one continues. A later chapter shows how a label lets you leave an outer loop. - EXIT works inside nested constructs. You can place
EXITinside anIF, aCASE, or a nestedBEGIN ... ENDblock, and it still leaves the enclosing loop. - Exceptions end the loop too. An unhandled exception inside the loop propagates out of it. If you want the loop to continue after an error, wrap the body in its own block with an exception handler.
- Loop variables are not special. In a basic loop you declare and update any counter yourself. Forgetting the increment is the usual cause of a loop that never ends.
Ways to leave a loop
EXIT is not the only way out. This table compares the options.
| Mechanism | What it leaves | Typical use |
|---|---|---|
| `EXIT` | The innermost loop (or a labeled outer loop) | Stop when a rule inside an `IF` is met |
| `EXIT WHEN cond` | The same loop, only if `cond` is TRUE | A single clear stop condition |
| `RETURN` | The whole subprogram | Stop all work in a function or procedure |
| Exception | The loop and the block, unless handled inside | An error that makes continuing pointless |
| `GOTO label` | Jumps to a label outside the loop | Rare, and usually avoidable |
RETURN is only valid in subprograms, not in an anonymous block's top level in the way a procedure uses it. In an anonymous block it ends the block, which is rarely what you want when you only need to stop a loop.
Choosing the basic loop
Use the basic loop when the number of iterations is not known in advance and the stop test does not fit naturally at the top of the loop. Typical cases are fetching from an explicit cursor, retrying until success, and reading input where the stop test needs a value produced inside the body. When you do know the count, the numeric FOR loop is safer, because it cannot loop forever.
Exercise
A loop starts with ln := 5 and its body is "ln := ln + 1; EXIT WHEN ln = 3;". Does it end? How would you fix it?
Show answer
It does not end normally. ln starts above 3 and only grows, so ln = 3 is never TRUE and the loop runs until an overflow error stops it. Change the condition to a form that is true once the limit is passed, for example EXIT WHEN l_n >= 3 (which exits on the first pass here), or fix the starting value if the intent was to count up to 3.
Exercise
In an explicit cursor loop, a developer writes FETCH, then DBMSOUTPUT.PUTLINE of the fetched variables, then EXIT WHEN c%NOTFOUND. The last row prints twice. Why, and what is the fix?
Show answer
When the final FETCH finds no row, the variables are not changed, so they still hold the previous row's values, and PUT_LINE prints them before the exit test runs. Move EXIT WHEN c%NOTFOUND to directly after the FETCH.