Sub topic 7
CASE Expressions Versus CASE Statements
This chapter assumes you can write an anonymous PL/SQL block, declare and assign scalar variables, and have seen the simple and searched CASE forms. It also assumes you know that a CASE statement with no matching branch and no ELSE raises CASE_NOT_FOUND. Here you will learn the second axis along which CASE varies: whether it is a statement or an expression. The two look nearly the same and behave differently in several ways.
Two Constructs with One Keyword
PL/SQL has two constructs that both start with CASE.
- A CASE statement is an executable statement. Each branch holds one or more statements, and the whole construct ends with
END CASE;. - A CASE expression is a piece of an expression. Each branch holds a value, and the whole construct ends with
END, with noCASEkeyword. It produces one value, so it appears wherever a value is allowed: the right side of an assignment, an argument to a function, or a column in a SQL query.
Both come in the simple form (one selector compared to each WHEN value) and the searched form (each WHEN holds a Boolean condition). The statement/expression split is independent of the simple/searched split, so there are four combinations.
DECLARE
l_status VARCHAR2(1) := 'I';
l_text VARCHAR2(20);
BEGIN
-- CASE statement: branches run statements; ends with END CASE;
CASE l_status
WHEN 'A' THEN l_text := 'Active';
WHEN 'I' THEN l_text := 'Inactive';
ELSE l_text := 'Unknown';
END CASE;
DBMS_OUTPUT.PUT_LINE('Statement: ' || l_text);
-- CASE expression: branches yield values; ends with END
l_text := CASE l_status
WHEN 'A' THEN 'Active'
WHEN 'I' THEN 'Inactive'
ELSE 'Unknown'
END;
DBMS_OUTPUT.PUT_LINE('Expression: ' || l_text);
END;
/Both halves print the same text. The statement version repeats the assignment l_text := in every branch. The expression version states the assignment once and lets CASE supply the value. When the only job of every branch is to set the same variable, the expression is shorter and harder to get wrong. If you add a branch and forget the assignment, a statement leaves the variable unchanged. An expression cannot omit the value.
Syntax Differences at a Glance
| Feature | CASE statement | CASE expression |
|---|---|---|
| Terminator | `END CASE;` | `END` (the surrounding statement supplies the `;`) |
| Branch contents | One or more statements, each ending in `;` | A single value or expression, with no `;` |
| Where it can appear | Where a statement can appear in a PL/SQL block | Anywhere an expression is allowed, including SQL |
| No branch matches and no `ELSE` | Raises `CASE_NOT_FOUND` | Returns `NULL` |
| Result | None | One value with one datatype |
| Can contain `DBMS_OUTPUT` calls, DML, `RETURN` | Yes | No, because branches are values, not statements |
Most syntax errors come from mixing these conventions. A semicolon after a value inside an expression, or END CASE closing an expression, fails to compile. So does a bare END closing a statement.
The Missing ELSE Behaves Differently
This is the most important behavioral difference. Without an ELSE, the two constructs react to an unmatched selector in opposite ways.
DECLARE
l_code VARCHAR2(1) := 'X';
l_text VARCHAR2(20);
BEGIN
l_text := CASE l_code
WHEN 'A' THEN 'Active'
WHEN 'I' THEN 'Inactive'
END;
DBMS_OUTPUT.PUT_LINE('Expression result: ' || NVL(l_text, '(null)'));
CASE l_code
WHEN 'A' THEN l_text := 'Active';
WHEN 'I' THEN l_text := 'Inactive';
END CASE;
DBMS_OUTPUT.PUT_LINE('Never reached');
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Statement raised CASE_NOT_FOUND');
END;
/The expression quietly returns NULL, so the first line prints Expression result: (null). The statement raises CASE_NOT_FOUND, control jumps to the handler, and Never reached is not printed.
The expression's silence is the riskier of the two. A NULL flows onward into later arithmetic, concatenation, or a column in a table, and the problem shows up far from its cause. If an unmatched value indicates a bug, add an explicit ELSE that makes the problem visible. In an expression, ELSE can call a function that raises an error. Alternatively, use a statement, which already raises one.
Type Rules for Expressions
A statement has no result, so its branches can do unrelated things. An expression produces one value, so all its result expressions must be of compatible types. Do not mix a string result with a number result, and do not rely on implicit conversion to sort it out. When the types are not compatible, the compiler rejects the expression or Oracle raises a conversion error at run time. A common cause is an ELSE 0 next to branches that return text. Write ELSE '0' if you want text, or convert explicitly with TO_CHAR.
An expression used in a PL/SQL assignment may also yield a BOOLEAN. A CASE expression inside a SQL statement must produce a SQL datatype, and in Oracle releases before 23ai BOOLEAN is not one of them. This is the usual reason a CASE expression that works in a block fails when pasted into a query.
Using CASE Expressions in SQL
Only the expression form is valid inside a SQL statement. The statement form is PL/SQL syntax and a SQL parser does not accept it. This query runs as written in SQL*Plus, SQLcl, or SQL Developer, because it uses only DUAL.
SELECT n,
CASE
WHEN n < 0 THEN 'negative'
WHEN n = 0 THEN 'zero'
ELSE 'positive'
END AS sign_label
FROM (SELECT -5 AS n FROM dual
UNION ALL SELECT 0 FROM dual
UNION ALL SELECT 8 FROM dual)
ORDER BY n;The same expression works in WHERE, ORDER BY, and the SET clause of an UPDATE. Placing it in an UPDATE replaces several separate statements, or a loop with an IF, with one pass over the table. The last chapter of this tutorial returns to that idea.
Evaluation Order and Short-Circuiting
Both forms evaluate WHEN clauses from top to bottom and stop at the first match. Later branches are not evaluated. This lets you guard a risky operation.
DECLARE
l_total NUMBER := 100;
l_count NUMBER := 0;
l_avg NUMBER;
BEGIN
l_avg := CASE
WHEN l_count = 0 THEN NULL
ELSE l_total / l_count
END;
DBMS_OUTPUT.PUT_LINE('Average: ' || NVL(TO_CHAR(l_avg), 'n/a'));
END;
/The division is in the ELSE branch and is never reached when l_count is 0, so ZERO_DIVIDE is not raised. The output is Average: n/a. Order matters for the same reason in the searched form. Put the most specific condition first, because an earlier, broader condition hides the later ones.
NULL in a Simple CASE
A simple CASE compares the selector to each WHEN value with equality. Because NULL = NULL is not TRUE, a WHEN NULL branch never matches.
DECLARE
l_bonus NUMBER := NULL;
l_text VARCHAR2(20);
BEGIN
l_text := CASE l_bonus
WHEN NULL THEN 'matched NULL'
ELSE 'fell to ELSE'
END;
DBMS_OUTPUT.PUT_LINE('Simple: ' || l_text);
l_text := CASE
WHEN l_bonus IS NULL THEN 'matched NULL'
ELSE 'fell to ELSE'
END;
DBMS_OUTPUT.PUT_LINE('Searched: ' || l_text);
END;
/The first line prints fell to ELSE and the second prints matched NULL. When the selector can be NULL, use the searched form with IS NULL. The same rule applies to the statement form.
Choosing Between the Two
Ask what each branch needs to do.
Use an expression when every branch computes a value for the same destination, and when the logic must run inside SQL. Use a statement when a branch has side effects, such as inserting a row, calling a procedure, or raising an application error, or when different branches do different amounts of work.
Common Errors Summary
- Closing an expression with
END CASE, or a statement with plainEND, causes a compile error. - Adding
;after a value inside an expression causes a compile error. - Omitting
ELSEin an expression produces an unexpectedNULL. Omitting it in a statement raisesCASE_NOT_FOUND. - Mixing result types, such as text in one branch and a number in another, causes a compile or conversion error.
- Writing
WHEN NULLin a simple CASE gives a branch that never matches. UseIS NULLin a searched CASE. - Putting a CASE statement inside a SQL query is not allowed. Use the expression form.
Exercise
A block contains this code, where llevel is a VARCHAR2 variable with the value 'Z'. What happens when it runs, and what changes if the CASE is rewritten as a CASE expression assigned to lmsg without an ELSE? CASE llevel WHEN 'H' THEN lmsg := 'High'; WHEN 'L' THEN l_msg := 'Low'; END CASE;
Show answer
As written, the statement form finds no matching WHEN and has no ELSE, so it raises CASENOTFOUND, which stops the block unless a handler catches it. As an expression (lmsg := CASE llevel WHEN 'H' THEN 'High' WHEN 'L' THEN 'Low' END;), no error is raised and l_msg is set to NULL. To make the unmatched case visible in the expression form, add an ELSE that supplies a default value or raises an error.
Exercise
Why does this expression always return 'other' when lbonus is NULL, and how do you fix it? ltext := CASE l_bonus WHEN NULL THEN 'none' ELSE 'other' END;
Show answer
A simple CASE compares the selector with equality, and NULL = NULL is not TRUE, so the WHEN NULL branch never matches. Use the searched form instead: ltext := CASE WHEN lbonus IS NULL THEN 'none' ELSE 'other' END;