Sub topic 5
The Simple CASE Statement
This chapter assumes you can write an anonymous PL/SQL block and declare scalar variables. It also assumes you have read the IF-ELSIF-ELSE chapter and can run a script with DBMS_OUTPUT enabled. By the end you should be able to write a simple CASE statement and predict which branch runs. You should also know what happens when no branch matches or the selector is NULL.
What a simple CASE statement is
A simple CASE statement picks one branch of statements by comparing a single value, the selector, with a list of candidate values. Use it when one variable or expression is tested against several constants, such as a status code or a type letter.
DECLARE
l_status VARCHAR2(1) := 'A';
BEGIN
CASE l_status
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
WHEN 'S' THEN DBMS_OUTPUT.PUT_LINE('Suspended');
ELSE DBMS_OUTPUT.PUT_LINE('Unknown');
END CASE;
END;
/This prints Active. The parts of the syntax are:
CASE selectornames the value to test.- Each
WHEN value THEN statementsis one branch. The branch body is one or more complete statements, each ending in a semicolon. ELSE statementsis optional. It runs when noWHENmatches.END CASE;closes the construct. It is a statement, so it ends with a semicolon.
The closing words matter. A CASE statement ends with END CASE;. A CASE expression, covered in a later chapter, ends with plain END and produces a value.
How the comparison works
The rules that decide which branch runs are short, and each one has a consequence.
- The selector is evaluated once, before any
WHENis looked at. - The
WHENvalues are tested from top to bottom. Each test isselector = when_value. - The first test that is TRUE runs its branch. Oracle skips the remaining
WHENclauses without evaluating them. - Control then goes to the statement after
END CASE;. There is no fall-through into the next branch, so you do not writeBREAK.
The selector is evaluated once, which matters when it is a function call. This block counts how often the selector function runs:
DECLARE
l_calls PLS_INTEGER := 0;
FUNCTION next_code RETURN VARCHAR2 IS
BEGIN
l_calls := l_calls + 1;
RETURN 'B';
END next_code;
BEGIN
CASE next_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('first');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('second');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('third');
END CASE;
DBMS_OUTPUT.PUT_LINE('Calls: ' || l_calls);
END;
/The output is second and then Calls: 1. Three WHEN clauses were available, but the function ran once. An IF-ELSIF chain that repeats next_code = 'A', next_code = 'B' and so on would call it once per test unless you copied the result into a variable first.
Order and duplicates
Because the first match wins, duplicate WHEN values are not an error. The later duplicate is simply unreachable:
DECLARE
l_code PLS_INTEGER := 2;
BEGIN
CASE l_code
WHEN 1 THEN DBMS_OUTPUT.PUT_LINE('one');
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE('two, first copy');
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE('two, second copy never runs');
ELSE DBMS_OUTPUT.PUT_LINE('other');
END CASE;
END;
/Only two, first copy is printed. Treat a duplicate as a likely copy-and-paste mistake and remove it.
The WHEN values do not have to be literals. Variables, constants, and expressions are allowed. They are evaluated lazily, in order, and only until one matches. That is useful, but a WHEN expression with side effects, such as a function that writes to a table, may run or not run depending on its position. Keep WHEN values free of side effects.
Several statements and empty branches
A branch can hold any number of statements, including nested IF statements, loops, and other CASE statements. You do not need BEGIN ... END around them:
DECLARE
l_type VARCHAR2(1) := 'R';
l_fee NUMBER := 0;
l_note VARCHAR2(30);
BEGIN
CASE l_type
WHEN 'R' THEN
l_fee := 10;
l_note := 'Regular';
WHEN 'P' THEN
l_fee := 25;
l_note := 'Premium';
ELSE
NULL; -- deliberately do nothing
END CASE;
DBMS_OUTPUT.PUT_LINE(l_note || ' fee: ' || l_fee);
END;
/This prints Regular fee: 10.
Every branch needs at least one statement. If a value should do nothing, write the null statement NULL;. Writing ELSE NULL; is also a clear way to tell the next reader that unmatched values are intentionally ignored. It prevents the error described below.
Matching several values to one branch
A WHEN clause takes one value. PL/SQL has no comma list such as WHEN 'A', 'B', and no IN list in a simple CASE. You have two options:
- Repeat the work, ideally by calling a local procedure from each branch.
- Switch to a searched CASE or an IF statement, where each condition is a full Boolean expression such as
l_status IN ('A','B').
If you find yourself repeating the same body under many WHEN values, the searched form is usually clearer. It is the subject of the next chapter.
When nothing matches
A simple CASE statement has a stricter rule than IF. If no WHEN matches and there is no ELSE, Oracle raises the predefined exception CASE_NOT_FOUND (ORA-06592). An IF statement with no matching branch and no ELSE silently does nothing. A CASE statement does not.
DECLARE
l_code VARCHAR2(1) := 'X';
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No WHEN branch matched and there is no ELSE');
END;
/This raises the exception, and the handler prints its message. Without the EXCEPTION section the error would propagate to the caller. A later chapter covers handling this case in more detail.
NULL as the selector
The comparison is selector = when_value, and a comparison with NULL is never TRUE. So a NULL selector matches no WHEN clause, and WHEN NULL does not help:
DECLARE
l_status VARCHAR2(1) := NULL;
BEGIN
CASE l_status
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN NULL THEN DBMS_OUTPUT.PUT_LINE('This line never prints');
ELSE DBMS_OUTPUT.PUT_LINE('ELSE: NULL never equals anything');
END CASE;
END;
/The output is the ELSE message. Without the ELSE, this block would raise CASENOTFOUND. This is the same three-valued logic from the first chapter of this tutorial, applied inside CASE.
If NULL needs its own branch, a simple CASE cannot express it. Test it first with IF, or use a searched CASE where a condition can be l_status IS NULL:
DECLARE
l_status VARCHAR2(1) := NULL;
BEGIN
IF l_status IS NULL THEN
DBMS_OUTPUT.PUT_LINE('Status missing');
ELSE
CASE l_status
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
ELSE DBMS_OUTPUT.PUT_LINE('Unknown');
END CASE;
END IF;
END;
/Keep the types consistent
Each comparison is an ordinary equality test, so the selector and every WHEN value should have the same datatype or one that converts cleanly to it. Mixing, for example, a VARCHAR2 selector with numeric WHEN values either fails to compile or relies on an implicit conversion that can raise a conversion error at run time for non-numeric text. Pick one type and write the literals to match: '1' for a character selector, 1 for a numeric one.
Simple CASE compared with IF-ELSIF
| Aspect | Simple CASE statement | IF-ELSIF-ELSE |
|---|---|---|
| What is tested | One selector against `WHEN` values with equality | Any Boolean condition in each branch |
| Selector evaluation | Once | Each condition is evaluated as the chain reaches it |
| No match and no ELSE | Raises CASE_NOT_FOUND | Does nothing |
| NULL handling | NULL never matches a `WHEN` | A NULL condition counts as not TRUE |
| Ranges or compound tests | Not possible | Natural |
| Closing keyword | `END CASE;` | `END IF;` |
Choose simple CASE when the decision is "which of these exact values is it?". Choose IF-ELSIF when conditions differ from branch to branch, or when you need ranges, LIKE, or IS NULL tests.
Common mistakes
- Writing
END;instead ofEND CASE;at the close of a CASE statement. The compiler reports a syntax error, becauseEND;closes the enclosing block. - Leaving out
ELSEand later hitting ORA-06592 on a value nobody planned for. - Putting
WHEN NULLin the list and expecting it to catch NULL values. - Writing an empty branch, such as
ELSEfollowed directly byEND CASE;. UseNULL;. - Copying a
WHENvalue, which leaves a branch that can never run.
Exercise
The block below declares l_level NUMBER := NULL; and then runs CASE l_level WHEN 1 THEN DBMS_OUTPUT.PUT_LINE('low'); WHEN NULL THEN DBMS_OUTPUT.PUT_LINE('missing'); END CASE; with no ELSE and no exception section. What happens, and how would you change the code so that a NULL prints missing?
Show answer
The NULL selector matches neither WHEN 1 nor WHEN NULL, because NULL = anything is NULL, not TRUE. With no ELSE, Oracle raises CASENOTFOUND (ORA-06592) and the unhandled exception goes to the caller. To print missing, test IF l_level IS NULL THEN ... ELSE CASE ... END CASE; END IF;, or use a searched CASE with WHEN l_level IS NULL THEN. Adding an ELSE alone would avoid the error but would not distinguish NULL from other unmatched values.
Exercise
A block has CASE get_rate WHEN 1 THEN ... WHEN 2 THEN ... WHEN 3 THEN ... END CASE; where get_rate is a function with no parameters. How many times does get_rate run if its result is 3, and why?
Show answer
Once. A simple CASE evaluates its selector a single time and then compares that stored result with each WHEN value in order, so the number of WHEN clauses does not change the call count.