Sub topic 4
Nested IF Statements and Short-Circuit Evaluation
This chapter assumes you can write an anonymous PL/SQL block, declare scalar variables, and use IF-THEN-ELSIF-ELSE. It also assumes you know that a condition can be TRUE, FALSE, or NULL, and that only TRUE runs the THEN branch. Here you will nest IF statements, see when PL/SQL skips part of a condition, and learn the errors that follow from both.
Nesting IF Statements
An IF statement can sit inside the THEN, ELSIF, or ELSE branch of another IF statement. The inner IF runs only if the outer branch is chosen. Each IF needs its own END IF.
DECLARE
l_age PLS_INTEGER := 20;
l_has_card BOOLEAN := TRUE;
BEGIN
IF l_age >= 18 THEN
IF l_has_card THEN
DBMS_OUTPUT.PUT_LINE('Entry allowed');
ELSE
DBMS_OUTPUT.PUT_LINE('Show a membership card');
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Too young');
END IF;
END;
/The output is Entry allowed. The outer condition is TRUE, so the inner IF is evaluated. A BOOLEAN variable such as l_has_card can be used as a condition on its own. You do not need to write l_has_card = TRUE.
Note the labels on the arrows. A NULL condition takes the same path as FALSE, because only TRUE selects the THEN branch.
Nesting versus combining with AND
Two nested IFs with no ELSE branches in between behave like one IF with AND.
DECLARE
l_age PLS_INTEGER := 20;
l_has_card BOOLEAN := TRUE;
BEGIN
IF l_age >= 18 AND l_has_card THEN
DBMS_OUTPUT.PUT_LINE('Entry allowed');
END IF;
END;
/Use AND when both conditions lead to a single outcome. Use nesting when the inner test needs its own ELSE, as in the first example, or when the inner test is expensive or only makes sense once the outer test passes.
Keep nesting shallow
Deep nesting is hard to read, and it is easy to attach an ELSE to the wrong IF. Three common remedies:
- Use ELSIF when the tests are alternatives at the same level, instead of an ELSE followed by another IF.
- Combine tests with AND or OR when they lead to the same action.
- Put a block of logic in a local or stored subprogram with a descriptive name.
The first remedy matters because ELSE IF is not the same as ELSIF. The spelling difference changes the number of END IF statements you need.
DECLARE
l_score NUMBER := 75;
BEGIN
IF l_score >= 90 THEN
DBMS_OUTPUT.PUT_LINE('A');
ELSE
IF l_score >= 70 THEN
DBMS_OUTPUT.PUT_LINE('C or better');
END IF; -- closes the inner IF
END IF; -- closes the outer IF
END;
/With ELSE IF you open a second IF, so you must close two. With ELSIF there is one IF and one END IF. Forgetting the second END IF gives a compile error such as PLS-00103 (encountered the symbol ";" or end of file when expecting END IF).
Short-Circuit Evaluation
PL/SQL evaluates AND and OR conditions from left to right and may stop as soon as the result is known.
FALSE AND anythingis FALSE, so the right operand is not needed.TRUE OR anythingis TRUE, so the right operand is not needed.
This is called short-circuit evaluation. It lets you guard a risky test with a safe one.
DECLARE
l_count PLS_INTEGER := 0;
l_total PLS_INTEGER := 50;
BEGIN
IF l_count > 0 AND l_total / l_count > 10 THEN
DBMS_OUTPUT.PUT_LINE('Average is above 10');
ELSE
DBMS_OUTPUT.PUT_LINE('No division was needed');
END IF;
END;
/Because l_count > 0 is FALSE, the division is not evaluated and no ZERO_DIVIDE error is raised. The output is No division was needed.
How NULL interacts with AND and OR
Short-circuiting is a consequence of three-valued logic. The table shows the results when one operand is NULL.
| Expression | Result |
|---|---|
| `TRUE AND NULL` | NULL |
| `FALSE AND NULL` | FALSE |
| `NULL AND FALSE` | FALSE |
| `TRUE OR NULL` | TRUE |
| `FALSE OR NULL` | NULL |
| `NOT NULL` | NULL |
A NULL result in an IF is treated like FALSE for the THEN branch. This produces a trap with NOT. If l_bonus is NULL, IF NOT (l_bonus > 100) is also NULL, so neither IF l_bonus > 100 nor IF NOT (l_bonus > 100) runs its THEN branch. The ELSE branch runs in both cases, which can make the two tests look contradictory.
DECLARE
l_bonus NUMBER := NULL;
BEGIN
IF l_bonus > 100 THEN
DBMS_OUTPUT.PUT_LINE('Large');
ELSIF NOT (l_bonus > 100) THEN
DBMS_OUTPUT.PUT_LINE('Not large');
ELSE
DBMS_OUTPUT.PUT_LINE('Unknown: the bonus is NULL');
END IF;
END;
/The output is Unknown: the bonus is NULL. Test for NULL first, with IS NULL, if the value can be missing.
Do not rely on evaluation order for side effects
Oracle documents short-circuit evaluation for PL/SQL, but your logic should not depend on it when a function has side effects. Consider:
CREATE OR REPLACE FUNCTION log_and_check(p_value NUMBER) RETURN BOOLEAN IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Checked ' || p_value);
RETURN p_value > 0;
END;
/
BEGIN
IF log_and_check(-1) AND log_and_check(5) THEN
DBMS_OUTPUT.PUT_LINE('Both positive');
END IF;
END;
/The output is Checked -1. The second call never runs because the first returned FALSE. If the second call did required work, such as writing an audit row, that work would be skipped. Do side-effect work in its own statement, then test the saved result.
DECLARE
l_first BOOLEAN;
l_second BOOLEAN;
BEGIN
l_first := log_and_check(-1);
l_second := log_and_check(5);
IF l_first AND l_second THEN
DBMS_OUTPUT.PUT_LINE('Both positive');
END IF;
END;
/Now both calls always run. The IF is a plain test of two stored values.
Where short-circuiting does not apply
Short-circuit behavior is a property of PL/SQL Boolean expressions. Do not assume it inside SQL statements. The optimizer is free to reorder predicates in a WHERE clause, so a guard like WHERE n <> 0 AND 100 / n > 5 is not guaranteed to protect the division. Move the guard into a CASE expression, whose branches are evaluated in order, or filter the rows in an inline view.
SELECT CASE WHEN n <> 0 THEN 100 / n END AS ratio
FROM (SELECT 0 AS n FROM dual UNION ALL SELECT 4 FROM dual);The CASE returns NULL for the row where n is 0 and 25 for the row where n is 4, with no ZERO_DIVIDE error.
Also be careful with the other conditional constructs. Oracle also short-circuits CASE, COALESCE, and DECODE in the sense that later branches are not evaluated once one matches, but that is a separate rule for each construct. Later chapters cover CASE in detail.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| PLS-00103 near END or end of file | `ELSE IF` used without a second END IF | Use ELSIF, or add the missing END IF |
| ELSE branch runs when the value is missing | A comparison with NULL returned NULL | Test `IS NULL` before comparing |
| ZERO_DIVIDE inside an IF | The risky test came before its guard | Put the guard first on the left of AND |
| Audit call sometimes skipped | A function with side effects sits on the right of AND or OR | Call it in a separate statement and test the result |
| Guard works in PL/SQL but fails in a WHERE clause | SQL predicates can be reordered | Use CASE or an inline view |
Exercises
Exercise
In the block below, what does it print, and why is no exception raised? DECLARE lqty PLSINTEGER := 0; BEGIN IF lqty <> 0 AND 100 / lqty > 5 THEN DBMSOUTPUT.PUTLINE('High'); ELSE DBMSOUTPUT.PUTLINE('Skipped'); END IF; END;
Show answer
It prints Skipped. The left operand l_qty <> 0 is FALSE, so the AND is FALSE without evaluating 100 / l_qty. The division by zero never happens, so ZERO_DIVIDE is not raised.
Exercise
A variable llimit is NULL. Which branch runs in: IF llimit > 10 THEN (A) ELSIF NOT (l_limit > 10) THEN (B) ELSE (C) END IF? Explain.
Show answer
Branch C runs. l_limit > 10 is NULL, so A is skipped. NOT NULL is also NULL, so B is skipped. Only the ELSE branch remains. To handle the missing value deliberately, test l_limit IS NULL first.
Exercise
Rewrite this so it uses ELSIF and needs one END IF: IF n < 0 THEN r := 'neg'; ELSE IF n = 0 THEN r := 'zero'; ELSE r := 'pos'; END IF; END IF;
Show answer
IF n < 0 THEN r := 'neg'; ELSIF n = 0 THEN r := 'zero'; ELSE r := 'pos'; END IF;