Sub topic 12
Skipping Iterations and Leaving Nested Loops: CONTINUE and Labels
This chapter assumes you can write the basic LOOP, WHILE LOOP, and numeric FOR LOOP, and that you can run anonymous blocks with DBMS_OUTPUT enabled. Here you will learn to skip the rest of one iteration with CONTINUE, and to name loops with labels so that EXIT and CONTINUE can target an outer loop.
EXIT and CONTINUE Compared
EXIT ends the loop. Execution resumes after END LOOP. CONTINUE ends only the current iteration. Execution jumps to the next iteration of the loop. Both statements have a WHEN form that takes a Boolean condition.
| Statement | Effect | Where control goes |
|---|---|---|
| `EXIT;` | Leaves the innermost loop | Statement after `END LOOP` |
| `EXIT WHEN cond;` | Leaves it only if `cond` is TRUE | Same |
| `CONTINUE;` | Abandons the current iteration | Next iteration of the innermost loop |
| `CONTINUE WHEN cond;` | Abandons it only if `cond` is TRUE | Same |
| `EXIT label [WHEN cond];` | Leaves the named enclosing loop | After that loop's `END LOOP` |
| `CONTINUE label [WHEN cond];` | Starts the next iteration of the named loop | Top of that loop |
CONTINUE WHEN cond is shorthand for IF cond THEN CONTINUE; END IF;. It follows the NULL rule from the first chapter. If cond evaluates to NULL, the statement does nothing and the loop body keeps running.
How CONTINUE Behaves in Each Loop Type
What happens after CONTINUE depends on the loop.
- Numeric FOR LOOP: the counter advances automatically, so the loop always makes progress.
- Cursor FOR LOOP: the next row is fetched.
- WHILE LOOP: the condition is tested again before the next iteration.
- Basic LOOP: control returns to the top of the loop, and nothing else happens. You must update any counter yourself.
The last case is the common source of bugs. Put the code that changes the loop state before the CONTINUE.
DECLARE
l_n PLS_INTEGER := 0;
BEGIN
LOOP
l_n := l_n + 1; -- advance first, so CONTINUE cannot skip it
EXIT WHEN l_n > 7; -- test for exit before any CONTINUE
CONTINUE WHEN MOD(l_n, 2) = 0;
DBMS_OUTPUT.PUT_LINE('Odd: ' || l_n);
END LOOP;
END;
/This prints Odd: 1, 3, 5, and 7. If you moved l_n := l_n + 1; below the CONTINUE, l_n would reach 2 and then stay there. Every later pass would skip the increment, and the loop would never end.
The same hazard applies to EXIT WHEN placed after a CONTINUE. A skipped iteration never reaches that exit test. Put the exit test first when the loop must always be able to finish.
Flattening Code with CONTINUE
CONTINUE is useful as a guard clause. Without it, the real work sits inside a growing pile of nested IF statements. With it, you filter out unwanted iterations at the top and leave the main body at one indentation level.
This example uses the Oracle HR sample schema. It skips employees who earn no commission.
BEGIN
FOR r IN (SELECT employee_id, last_name, commission_pct
FROM employees
WHERE department_id = 80
ORDER BY employee_id) LOOP
CONTINUE WHEN r.commission_pct IS NULL;
DBMS_OUTPUT.PUT_LINE(r.last_name || ': ' || r.commission_pct);
END LOOP;
END;
/Note the IS NULL test. Writing CONTINUE WHEN r.commission_pct = NULL would evaluate to NULL for every row, so nothing would ever be skipped.
If a filter can be expressed in the query's WHERE clause, put it there instead. The database then never sends the unwanted rows to PL/SQL. Use CONTINUE for conditions that depend on PL/SQL logic, such as results of function calls or values computed earlier in the loop.
Loop Labels
A label is a name in double angle brackets placed immediately before a loop.
<<outer>>
FOR i IN 1..3 LOOP
...
END LOOP outer;Rules for labels:
- The label goes directly before
LOOP,WHILE, orFOR. - Repeating the label after
END LOOPis optional. It is a good habit because it shows whichEND LOOPcloses which loop, which matters when loops are deeply nested. - A label is an identifier, so it follows the usual naming rules. It is not a string or a variable.
- Without a label,
EXITandCONTINUEalways affect the innermost loop. - With a label, they can target that loop or any other enclosing loop.
Leaving or Continuing an Outer Loop
The spine example combines both statements in nested loops.
BEGIN
<<outer>>
FOR i IN 1..3 LOOP
FOR j IN 1..3 LOOP
CONTINUE WHEN j = 2;
EXIT outer WHEN i = 2;
DBMS_OUTPUT.PUT_LINE(i || ',' || j);
END LOOP;
END LOOP outer;
END;
/Trace it to see the difference between the two statements:
- With
i = 1,j = 1prints1,1. - With
j = 2,CONTINUE WHEN j = 2skips the rest of that inner iteration. - With
j = 3, the block prints1,3. - With
i = 2andj = 1,EXIT outer WHEN i = 2is TRUE. Both loops end at once, so the output is only1,1and1,3.
A plain EXIT in the inner loop would only end the j loop. The i loop would carry on with i = 3.
CONTINUE also accepts a label, which lets an inner loop abandon the current pass of an outer loop. This version prints a triangle of pairs.
BEGIN
<<rows>>
FOR i IN 1..3 LOOP
FOR j IN 1..3 LOOP
CONTINUE rows WHEN j > i;
DBMS_OUTPUT.PUT_LINE(i || ',' || j);
END LOOP;
END LOOP rows;
END;
/The output is 1,1, 2,1, 2,2, 3,1, 3,2, and 3,3. As soon as j exceeds i, control jumps to the next value of i and skips the remaining j values.
Common Errors and Edge Cases
- Outside a loop.
EXITandCONTINUEare legal only inside a loop. Placing one in a block with no enclosing loop fails at compile time with PLS-00376. - Wrong label. The label must belong to a loop that encloses the statement. A label on a block, or on a loop that has already ended, is rejected at compile time.
- Crossing subprogram boundaries. A
CONTINUEorEXITcannot jump out of a procedure or function into a caller's loop. To signal "stop" from a called subprogram, use a return value or an exception. - Exception handlers. A loop body can contain its own
BEGIN ... EXCEPTION ... ENDblock. Handling an error there and then runningCONTINUEis a common way to skip bad rows. Put theCONTINUEafter the inner block, because the handler itself belongs to the inner block. - Overuse. Several
CONTINUEstatements scattered through a long body make the logic hard to follow. If the skip conditions multiply, a singleIF ... ELSIFchain or a rewritten query is often clearer. - Version.
CONTINUEwas added in Oracle Database 11g. Older code reaches the same result withIFblocks or aGOTO.
Exercises
Exercise
The block below contains a basic loop. What goes wrong, and how do you fix it? DECLARE ln PLSINTEGER := 0; BEGIN LOOP CONTINUE WHEN MOD(ln, 2) = 0; ln := ln + 1; EXIT WHEN ln > 5; END LOOP; END;
Show answer
ln starts at 0, which is even, so CONTINUE WHEN is TRUE on the first pass. The increment and the exit test are skipped, ln stays 0, and the loop runs forever. Fix it by moving ln := ln + 1; and EXIT WHEN l_n > 5; above the CONTINUE WHEN line, so the loop state changes and the exit test runs on every iteration.
Exercise
Write a block with an outer FOR loop over i in 1..3 and an inner FOR loop over j in 1..3. It must print i,j for every pair, except that it moves to the next value of i as soon as i j equals 4, and it stops both loops entirely when i j equals 6. What does it print?
Show answer
Use a label and CONTINUE/EXIT on that label: BEGIN <<outer>> FOR i IN 1..3 LOOP FOR j IN 1..3 LOOP EXIT outer WHEN i j = 6; CONTINUE outer WHEN i j = 4; DBMSOUTPUT.PUTLINE(i || ',' || j); END LOOP; END LOOP outer; END; / It prints 1,1, 1,2, 1,3, 2,1, and then 3,1, 3,2. The pair 2,2 has product 4, so CONTINUE outer skips the rest of the j loop for i = 2 and starts i = 3. For i = 3, the pair 3,1 prints and the pair 3,2 prints. The pair 3,2 has product 6, so EXIT outer ends both loops before printing it. The final output is therefore 1,1, 1,2, 1,3, 2,1, 3,1.