Sub topic 14
Choosing the Right Control-Flow Construct
This chapter assumes you can already write IF, CASE, and the four loop forms in an anonymous block, and that you know how NULL behaves in conditions. It covers how to choose among them. Most tasks can be written several ways. The better choice is the one that states the intent most directly, fails in the most useful way, and is easiest to change later.
Decide in Two Steps
Ask two questions in order.
- Do I need to choose, or to repeat? Choosing uses IF or CASE. Repeating uses a loop.
- Within that family, what is the shape of the problem? The shape could be a value to compute, a number of repetitions, a condition that controls the repetition, or a set of rows.
Choosing Between Branches
Compute a value: CASE expression
If the purpose of the branching is to produce one value, use a CASE expression. It is a single assignment, so there is no risk that one branch forgets to set the variable.
DECLARE
l_score NUMBER := 72;
l_grade VARCHAR2(1);
BEGIN
l_grade := CASE
WHEN l_score >= 90 THEN 'A'
WHEN l_score >= 80 THEN 'B'
WHEN l_score >= 70 THEN 'C'
ELSE 'F'
END;
DBMS_OUTPUT.PUT_LINE('Grade: ' || l_grade);
END;
/The IF-ELSIF version of this code assigns l_grade four times. If someone adds a branch and forgets the assignment, the variable keeps its old value without any error. The CASE expression has a single assignment target, so that mistake cannot happen.
Run different statements: IF or CASE statement
When each branch runs different statements, such as a call, a DML statement, or a RAISE, you need a statement form.
| Situation | Best fit | Reason |
|---|---|---|
| One yes/no test, one action | IF-THEN | Simplest form |
| Two outcomes | IF-THEN-ELSE | Both paths are visible |
| One variable compared with several constants | Simple CASE statement | Names the selector once |
| Different conditions on different variables | IF-ELSIF-ELSE | Each branch can test anything |
| Ranges or mixed Boolean tests, laid out as a table | Searched CASE statement | Aligned, one condition per line |
| Branch result is a value | CASE expression | One assignment, no missed branch |
IF and CASE are equivalent for many chains. The difference is in how they handle a missing branch and a NULL.
Failure behavior should influence the choice
| Construct | No branch matches | NULL involved |
|---|---|---|
| IF-ELSIF without ELSE | Nothing runs, silently | A NULL condition counts as not TRUE, so control falls through |
| CASE statement without ELSE | Raises `CASE_NOT_FOUND` | Simple CASE never matches NULL, because equality with NULL is not TRUE |
| CASE expression without ELSE | Returns NULL | Same as the CASE statement for matching |
If an unexpected value means a bug, use a CASE statement without ELSE, or write an ELSE that raises an error. The failure then appears where the bad value arrives. If an unexpected value is normal and should do nothing, use IF without ELSE, or add an explicit ELSE NULL; to a CASE statement to show that you meant it.
DECLARE
l_status VARCHAR2(1) := NULL;
BEGIN
CASE
WHEN l_status IS NULL THEN DBMS_OUTPUT.PUT_LINE('No status yet');
WHEN l_status = 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
ELSE DBMS_OUTPUT.PUT_LINE('Other');
END CASE;
END;
/Use a searched CASE here. A simple CASE with WHEN NULL would never match, because it compares with =.
Keep nesting shallow
Deep IF nesting is a signal to restructure. Two common fixes:
- Replace
IF a THEN IF b THEN ... END IF; END IF;withIF a AND b THEN. This is safe because PL/SQL stops evaluating an AND once the left side is not TRUE. - Turn an inner IF that guards the rest of a loop body into
CONTINUE WHENorEXIT WHEN, as shown below.
Choosing a Loop
By the question each loop answers
| Loop | Use it when | Watch for |
|---|---|---|
| Numeric FOR | The iteration count is known when the loop starts | The counter is read-only inside the body, and the bounds are evaluated once |
| Cursor FOR | You need every row of a query | The loop opens, fetches, and closes for you |
| WHILE | The condition decides whether the body runs at all, possibly zero times | The condition must change inside the body, or the loop never ends |
| Basic LOOP | The body must run at least once, or the exit test is in the middle | Without an `EXIT`, it runs forever |
Prefer the most specific loop. A numeric FOR cannot forget to increment its counter, and a cursor FOR cannot forget to close its cursor. A WHILE loop with a hand-maintained counter, or a basic LOOP with manual OPEN, FETCH, and CLOSE, can go wrong in both of those ways.
Let EXIT and CONTINUE replace flags
A frequent pattern is a Boolean flag that records "we are finished" and is checked in the loop condition, with nested IFs around the real work. Compare these two blocks. Both add odd numbers from 1 to 10 and stop before the total would pass 20. Both print Total: 16.
DECLARE
l_total PLS_INTEGER := 0;
l_i PLS_INTEGER := 1;
l_done BOOLEAN := FALSE;
BEGIN
WHILE l_i <= 10 AND NOT l_done LOOP
IF MOD(l_i, 2) = 1 THEN
IF l_total + l_i > 20 THEN
l_done := TRUE;
ELSE
l_total := l_total + l_i;
END IF;
END IF;
l_i := l_i + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/DECLARE
l_total PLS_INTEGER := 0;
BEGIN
FOR i IN 1..10 LOOP
CONTINUE WHEN MOD(i, 2) = 0;
EXIT WHEN l_total + i > 20;
l_total := l_total + i;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/The second version has no flag, no manual counter, and no nesting. Each early-out is a guard line at the top of the body, and the last line is the work. Use this guard-clause style when the loop body has several reasons to skip or stop.
A caution applies to EXIT. It should leave a loop for a reason that you can state in a sentence. If a loop has four EXIT WHEN lines scattered through a long body, a different loop type or a helper procedure is usually clearer.
Nested loops: use labels, not flags
To leave an outer loop from inside an inner one, label the outer loop and name it in EXIT. A flag has to be tested in every enclosing loop, and a label does not.
BEGIN
<<rows>>
FOR r IN 1..3 LOOP
FOR c IN 1..3 LOOP
EXIT rows WHEN r * c > 4;
DBMS_OUTPUT.PUT_LINE(r || 'x' || c);
END LOOP;
END LOOP rows;
END;
/This prints 1x1, 1x2, 1x3, 2x1, 2x2, and stops at 2x3 because the product is 6. Labels are also worth adding to deeply nested loops that do not need them. Writing END LOOP rows; tells the reader which loop is closing.
Combining Constructs
Constructs combine freely, and each does one job. A cursor FOR loop supplies the rows, and a CASE expression turns a column into text:
BEGIN
FOR r IN (SELECT LEVEL AS n FROM dual CONNECT BY LEVEL <= 5) LOOP
DBMS_OUTPUT.PUT_LINE(
r.n || ' is ' || (CASE WHEN MOD(r.n, 2) = 0 THEN 'even' ELSE 'odd' END));
END LOOP;
END;
/This query uses only dual, so it runs in any schema.
Common Mistakes When Choosing
- Using IF where a CASE expression returns the value. The result is repeated assignments that are easy to desynchronize.
- Using a simple CASE to test for NULL. It never matches. Use a searched CASE with
IS NULL. - Omitting ELSE where silence hides bugs. Decide deliberately between an error (CASE statement without ELSE) and a no-op.
- Using WHILE or a basic LOOP for a fixed count. A numeric FOR is shorter and cannot skip the increment.
- Modifying the counter of a numeric FOR. Assignment to it is a compile error. If you need to skip ahead, use WHILE.
- Opening a cursor by hand for a plain pass over rows. A cursor FOR loop does the same work with less code.
A loop that executes a SQL statement once per row is a separate design question, and it is often better written as one set-based statement. The next chapter covers that.
Exercise
A block reads a status code in l_code and must set l_text to 'Open', 'Closed', or 'Unknown'. Which construct is the best fit, and why? Write it.
Show answer
A CASE expression, because the branches only produce a value. For example: ltext := CASE lcode WHEN 'O' THEN 'Open' WHEN 'C' THEN 'Closed' ELSE 'Unknown' END; It is a single assignment, and the ELSE makes the unexpected-value case explicit instead of returning NULL.
Exercise
This loop sums 1 to 100 but must stop as soon as the running total exceeds 50, and skip multiples of 5. Rewrite it using the right loop and guard lines instead of the flag. DECLARE li PLSINTEGER := 1; lsum PLSINTEGER := 0; lstop BOOLEAN := FALSE; BEGIN WHILE li <= 100 AND NOT lstop LOOP IF MOD(li, 5) <> 0 THEN lsum := lsum + li; IF lsum > 50 THEN lstop := TRUE; END IF; END IF; li := l_i + 1; END LOOP; END;
Show answer
Use a numeric FOR loop with CONTINUE WHEN and EXIT WHEN: BEGIN FOR i IN 1..100 LOOP CONTINUE WHEN MOD(i, 5) = 0; lsum := lsum + i; EXIT WHEN lsum > 50; END LOOP; END; The count is known (1 to 100), so the numeric FOR replaces the manual counter. The sum is added before the test, as in the original, so the loop stops after the total first exceeds 50. Declare lsum PLS_INTEGER := 0 first.