Sub topic 6
The Searched CASE Statement
A searched CASE statement tests Boolean conditions in order. The first condition that is TRUE determines which statement runs. Unlike a simple CASE statement, it does not compare one selector with a list of fixed values.
Assume you know how to declare variables and run an anonymous PL/SQL block with DBMS_OUTPUT enabled.
Syntax and Evaluation Order
The general form is:
CASE
WHEN condition_1 THEN
statements_1;
WHEN condition_2 THEN
statements_2;
ELSE
statements_else;
END CASE;PL/SQL evaluates condition_1, then condition_2, and so on. It stops after the first TRUE condition. Conditions after a match are not evaluated.
| Part | Purpose |
|---|---|
| `WHEN condition` | Tests a Boolean condition |
| `THEN` | Begins the statements for a matching condition |
| `ELSE` | Handles the case where no condition is true |
| `END CASE` | Ends the `CASE` statement |
The following block classifies a score:
DECLARE
l_score NUMBER := 72;
BEGIN
CASE
WHEN l_score >= 90 THEN
DBMS_OUTPUT.PUT_LINE('Grade: A');
WHEN l_score >= 80 THEN
DBMS_OUTPUT.PUT_LINE('Grade: B');
WHEN l_score >= 70 THEN
DBMS_OUTPUT.PUT_LINE('Grade: C');
ELSE
DBMS_OUTPUT.PUT_LINE('Grade: F');
END CASE;
END;
/The score is 72. The first two conditions are false, and l_score >= 70 is true, so the block prints Grade: C. The ELSE branch does not run.
Order matters. If the WHEN l_score >= 70 condition appeared first, a score of 95 would receive Grade: C, because that condition would match before the more specific test for 90.
NULL and Missing Matches
A condition involving NULL evaluates to NULL, not TRUE. For example, l_score >= 70 is NULL when l_score is NULL. Therefore, that WHEN branch does not match. Use an explicit test when missing values need special handling.
DECLARE
l_score NUMBER := NULL;
BEGIN
CASE
WHEN l_score IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Score is missing');
WHEN l_score >= 70 THEN
DBMS_OUTPUT.PUT_LINE('Passing score');
ELSE
DBMS_OUTPUT.PUT_LINE('Failing score');
END CASE;
END;
/When to Use It
Use a searched CASE statement when several mutually exclusive conditions select different actions. It is often clearer than deeply nested IF statements, especially when all tests describe one decision.
Keep conditions ordered from the most specific or highest-priority rule to the least specific rule.
Exercise
What does this block print, and why? DECLARE l_n NUMBER := 8; BEGIN CASE WHEN l_n > 10 THEN DBMS_OUTPUT.PUT_LINE('High'); WHEN l_n > 5 THEN DBMS_OUTPUT.PUT_LINE('Medium'); ELSE DBMS_OUTPUT.PUT_LINE('Low'); END CASE; END; /
Show answer
It prints Medium. The first condition is false, the second is true, and evaluation stops after that match.