Sub topic 6
The Searched CASE Statement
This chapter assumes you can run an anonymous PL/SQL block with DBMS_OUTPUT enabled and that you know how IF-ELSIF-ELSE works. It also assumes you know that a condition can evaluate to TRUE, FALSE, or NULL. The previous chapter covered the simple CASE statement, which compares one selector value against a list of values. Here you will learn the searched form, which evaluates a full Boolean condition in each branch.
What a searched CASE statement is
A searched CASE statement has no selector after the CASE keyword. Each WHEN clause holds its own Boolean condition. PL/SQL tests the conditions from top to bottom, runs the statements of the first branch whose condition is TRUE, and skips the rest.
CASE
WHEN condition_1 THEN statements_1
WHEN condition_2 THEN statements_2
...
[ELSE else_statements]
END CASE;The statement ends with END CASE;. Each branch can hold any number of statements, so you do not need a BEGIN ... END wrapper inside a branch.
DECLARE
l_amount NUMBER := 120;
l_member VARCHAR2(1) := 'Y';
l_fee NUMBER;
BEGIN
CASE
WHEN l_member = 'Y' AND l_amount >= 50 THEN
l_fee := 0;
DBMS_OUTPUT.PUT_LINE('Free shipping for members');
WHEN l_amount >= 100 THEN
l_fee := 0;
DBMS_OUTPUT.PUT_LINE('Free shipping for large orders');
ELSE
l_fee := 7.5;
DBMS_OUTPUT.PUT_LINE('Standard shipping');
END CASE;
DBMS_OUTPUT.PUT_LINE('Fee: ' || l_fee);
END;
/This prints Free shipping for members and Fee: 0. Both of the first two conditions are TRUE for these values, but only the first branch runs.
How it differs from the simple CASE statement
The simple CASE statement is shorthand for a series of equality tests against one selector. The searched form can test anything that yields a Boolean.
| Feature | Simple CASE | Searched CASE |
|---|---|---|
| Selector after `CASE` | Yes, one expression | None |
| What each `WHEN` holds | A value or expression to compare with `=` | A full Boolean condition |
| Ranges (`>=`, `BETWEEN`) | No | Yes |
| Several variables in one test | No | Yes |
| Testing for NULL | Cannot match NULL | Works with `IS NULL` |
| Typical use | One code mapped to actions | Ranges, combined rules, mixed tests |
Any simple CASE can be rewritten as a searched CASE. The reverse is not true.
Evaluation order
PL/SQL evaluates the WHEN conditions in the order you write them. It stops at the first one that is TRUE. This has two consequences: the order of branches can change the result, and conditions after the matching branch are never evaluated.
Order matters when conditions overlap
Put the most specific condition first. The following block has the conditions in the wrong order:
DECLARE
l_score NUMBER := 95;
BEGIN
CASE
WHEN l_score >= 70 THEN DBMS_OUTPUT.PUT_LINE('Medium');
WHEN l_score >= 90 THEN DBMS_OUTPUT.PUT_LINE('High');
ELSE DBMS_OUTPUT.PUT_LINE('Low');
END CASE;
END;
/It prints Medium. A score of 95 satisfies >= 70, so the >= 90 branch is unreachable. Swap the two WHEN clauses and it prints High. The compiler does not warn about this, because it cannot know the conditions overlap in a harmful way.
An alternative is to write non-overlapping conditions, such as l_score >= 70 AND l_score < 90. This makes each branch independent of order. It is longer, but it survives later edits better when many branches exist.
Later conditions are not evaluated
Because evaluation stops at the first TRUE condition, a function call in a later WHEN never runs. The next block makes this visible with a helper function that prints a message each time it is called.
DECLARE
FUNCTION check_it(p_name VARCHAR2, p_result BOOLEAN) RETURN BOOLEAN IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Evaluating ' || p_name);
RETURN p_result;
END check_it;
BEGIN
CASE
WHEN check_it('first', FALSE) THEN DBMS_OUTPUT.PUT_LINE('Branch 1');
WHEN check_it('second', TRUE) THEN DBMS_OUTPUT.PUT_LINE('Branch 2');
WHEN check_it('third', TRUE) THEN DBMS_OUTPUT.PUT_LINE('Branch 3');
END CASE;
END;
/The output is:
Evaluating first
Evaluating second
Branch 2The third condition is never evaluated. You can use this to put cheap tests first and expensive ones, such as function calls, later. Do not rely on it for side effects. A condition should only ask a question, not change data.
NULL in searched CASE conditions
A WHEN branch runs only when its condition is TRUE. If the condition is NULL, PL/SQL treats it like FALSE and moves on. This is the same rule as in an IF statement, and it is the main source of surprises.
DECLARE
l_bonus NUMBER := NULL;
BEGIN
CASE
WHEN l_bonus IS NULL THEN
DBMS_OUTPUT.PUT_LINE('No bonus recorded');
WHEN l_bonus > 100 THEN
DBMS_OUTPUT.PUT_LINE('Large bonus');
ELSE
DBMS_OUTPUT.PUT_LINE('Small bonus');
END CASE;
END;
/This prints No bonus recorded. Without the IS NULL branch, l_bonus > 100 would be NULL, and the block would print Small bonus. That would be wrong, because a missing bonus is not a small one.
The simple CASE statement cannot handle this case, because it compares with =, and NULL = NULL is NULL:
DECLARE
l_bonus NUMBER := NULL;
BEGIN
CASE l_bonus
WHEN NULL THEN DBMS_OUTPUT.PUT_LINE('Matched NULL');
ELSE DBMS_OUTPUT.PUT_LINE('ELSE: NULL = NULL is not TRUE');
END CASE;
END;
/The WHEN NULL branch never runs. When a value can be NULL, use the searched form and test it with IS NULL as the first branch. That way, the later comparisons only ever see non-NULL values.
Handling no match
An IF statement with no ELSE does nothing when no condition is TRUE. A CASE statement behaves differently. If no WHEN condition is TRUE and there is no ELSE, PL/SQL raises the predefined exception CASE_NOT_FOUND (ORA-06592). The next chapters cover handling this exception in detail. For now, the practical rules are:
- Add an
ELSEbranch whenever the conditions are not guaranteed to cover every case. - Use the
ELSEbranch to report unexpected data, for example by raising an application error. - If you really want "do nothing", write
ELSE NULL;so the intent is explicit.
DECLARE
l_qty NUMBER := -5;
BEGIN
CASE
WHEN l_qty = 0 THEN
DBMS_OUTPUT.PUT_LINE('Out of stock');
WHEN l_qty > 0 THEN
DBMS_OUTPUT.PUT_LINE('In stock');
ELSE
RAISE_APPLICATION_ERROR(-20001, 'Invalid quantity: ' || l_qty);
END CASE;
END;
/Here the ELSE branch stops the block with a clear message instead of letting bad data pass through quietly.
Searched CASE statement versus CASE expression
The searched CASE statement runs statements. It is not the same as the searched CASE expression, which returns a value and ends with END, not END CASE. If you only need to assign a value to a variable, an expression is usually shorter:
DECLARE
l_score NUMBER := 85;
l_label VARCHAR2(10);
BEGIN
l_label := CASE
WHEN l_score >= 90 THEN 'High'
WHEN l_score >= 70 THEN 'Medium'
ELSE 'Low'
END;
DBMS_OUTPUT.PUT_LINE(l_label);
END;
/Use the statement form when a branch has to do more than produce a value, such as calling procedures, running DML, or printing several lines. A later chapter compares the two forms in detail.
Searched CASE or IF-ELSIF
Both constructs run the first branch whose condition is TRUE, so they are largely interchangeable. Choose by readability:
- Use searched CASE when you have three or more parallel, mutually exclusive branches. The
WHENlines align and the structure is easy to scan. - Use IF-ELSIF when you have one or two branches, or when the missing-ELSE case should quietly do nothing.
- Use IF when branches need to be nested with different conditions at each level.
Common mistakes
- Writing a selector and a condition together.
CASE l_score WHEN l_score >= 90 THEN ...is a simple CASE, so it comparesl_scoreto a Boolean and fails to compile with a type mismatch. Remove the selector to make it searched. - Putting a semicolon after a condition. Write
WHEN x > 1 THEN, with the semicolon only after each statement. - Ending with
END;instead ofEND CASE;. The statement form requiresEND CASE;. PlainENDbelongs to the expression form. - Overlapping conditions in the wrong order. Test specific conditions before general ones.
- Forgetting NULL. Test
IS NULLfirst, or the value will fall intoELSE.
Exercise
Consider this block. What does it print, and what would change if ltemp were NULL? DECLARE ltemp NUMBER := 25; BEGIN CASE WHEN ltemp > 30 THEN DBMSOUTPUT.PUTLINE('Hot'); WHEN ltemp > 20 THEN DBMSOUTPUT.PUTLINE('Warm'); WHEN ltemp > 10 THEN DBMSOUTPUT.PUT_LINE('Mild'); END CASE; END; /
Show answer
With ltemp = 25, the first condition is FALSE and the second is TRUE, so the block prints Warm and skips the Mild branch. If ltemp were NULL, every condition would evaluate to NULL, which counts as not TRUE. No branch would run, and because there is no ELSE the block would raise CASENOTFOUND (ORA-06592). Adding an ELSE branch, or an earlier WHEN l_temp IS NULL branch, would prevent the error.
Exercise
Rewrite this IF chain as a searched CASE statement that behaves the same way when lqty is NULL. IF lqty > 100 THEN DBMSOUTPUT.PUTLINE('Bulk'); ELSIF lqty > 0 THEN DBMSOUTPUT.PUT_LINE('Normal'); END IF;
Show answer
CASE WHEN lqty > 100 THEN DBMSOUTPUT.PUTLINE('Bulk'); WHEN lqty > 0 THEN DBMSOUTPUT.PUTLINE('Normal'); ELSE NULL; END CASE; The ELSE NULL; branch is required. The IF chain does nothing when lqty is NULL or not positive, but a CASE statement without ELSE would raise CASENOT_FOUND in those cases.