Sub topic 10
How CASE Evaluates: Order, ELSE, and Result Type
This chapter assumes you can write searched and simple CASE expressions, know that NULL means "unknown", and have used COALESCE. Here you will learn the rules that decide which branch CASE returns and what data type the result has. Most CASE bugs come from three things: branches in the wrong order, a missing ELSE, and mixed result types.
Branches are tested top to bottom
A CASE expression checks its WHEN conditions in the order you wrote them. It stops at the first condition that is true and returns that branch's result. It does not look at later branches.
This means overlapping conditions are resolved by position, not by which one fits best. The query below has its branches in the wrong order:
SELECT first_name,
salary,
CASE
WHEN salary >= 50000 THEN 'medium'
WHEN salary >= 100000 THEN 'high'
ELSE 'low'
END AS salary_band
FROM employees;An employee earning 120000 satisfies salary >= 50000, so the result is 'medium'. The 'high' branch can never be reached. Put the most specific or most restrictive condition first, or make the conditions mutually exclusive with BETWEEN or explicit upper bounds.
SELECT first_name,
salary,
CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees;Because the first match wins, each later WHEN can rely on the earlier ones having failed. In the second query, the 'medium' branch only sees rows below 100000. That is why it needs no upper bound.
Only TRUE selects a branch
SQL conditions have three outcomes: true, false, and unknown. A comparison that involves NULL is unknown. CASE treats false and unknown the same way: it moves on to the next branch.
SELECT first_name,
commission,
CASE
WHEN commission > 0 THEN 'paid'
ELSE 'none'
END AS commission_label
FROM employees;An employee with commission = 0 gets 'none'. An employee with commission = NULL also gets 'none', because NULL > 0 is unknown and falls through to ELSE. If you need to tell those two cases apart, add a branch with IS NULL before the comparison:
SELECT first_name,
commission,
CASE
WHEN commission IS NULL THEN 'not applicable'
WHEN commission > 0 THEN 'paid'
ELSE 'zero'
END AS commission_label
FROM employees;Order matters here too. If the IS NULL branch came second, it would still work, because the > 0 test returns unknown for NULL and passes control on. Putting the NULL test first makes the intent clear to the reader.
A simple CASE (CASE status WHEN 'P' THEN ...) compares with =. Since NULL = NULL is unknown, a WHEN NULL branch in a simple CASE never matches. Use a searched CASE with IS NULL instead.
The default ELSE is NULL
If no WHEN matches and you wrote no ELSE, CASE returns NULL. SQL does not raise an error for an unmatched value.
SELECT first_name,
salary,
CASE
WHEN salary >= 100000 THEN 'high'
END AS flag
FROM employees;Rows below 100000 get NULL in flag. This is sometimes what you want, especially inside aggregates, where NULL values are skipped. The following counts only the matching rows, because COUNT(expression) ignores NULL:
SELECT COUNT(CASE WHEN salary >= 100000 THEN 1 END) AS high_earners
FROM employees;In ordinary output columns, a silent NULL often hides a gap in your logic. Say what you mean in one of two ways:
- Write
ELSE NULLwhen you wantNULLon purpose, so readers know it is deliberate. - Write an explicit
ELSE 'unknown'(or similar) when every row should get a visible value. A value that appears in your data but not in yourWHENlist then shows up in the output instead of disappearing.
Evaluation order is not always execution order
The SQL standard describes CASE as evaluated in order, and in most queries you can rely on that. A common use is to guard a risky expression:
SELECT order_id,
CASE
WHEN order_count = 0 THEN NULL
ELSE total_revenue / order_count
END AS avg_order_value
FROM sales_summary;For each row, the division runs only if order_count is not zero. This is why CASE works as a guard, though NULLIF(order_count, 0) is shorter for this specific case.
There are exceptions. A database's optimizer may evaluate parts of an expression earlier than the row-by-row model suggests. Two cases are well documented in PostgreSQL:
- A subexpression that does not depend on any column, such as
1/0, can be simplified once while the query is planned. That can raise an error even if no row would ever reach that branch. - An aggregate inside a
CASEbranch is computed for the whole group beforeCASEpicks a branch. ACASEcannot stop an aggregate from running.
-- In PostgreSQL this can fail while the query is planned,
-- even when no row has x <= 0, because 1/0 is a constant.
SELECT CASE WHEN x > 0 THEN x ELSE 1/0 END
FROM tab;The result type
A CASE expression is a single column in the result, so it has one data type. The database determines that type from all the result expressions together: every THEN value and the ELSE value. The types in the WHEN conditions do not matter, since they are only tested for true or false.
The rules work like those for UNION: the engine finds a type that every branch can be converted to. Typical outcomes:
| Branch results | Resulting type |
|---|---|
| `1` and `2` (both integers) | integer |
| `1` and `2.5` (integer and decimal) | decimal |
| `'a'` and `'bbb'` (text of different lengths) | text, long enough for the longest |
| `'high'` and `NULL` | text; `NULL` takes the type of the other branches |
| `'high'` and `0` (text and integer) | depends on the database |
The last row is where errors appear. PostgreSQL and SQL Server try to turn 'high' into a number and fail with a conversion error, sometimes only when a row actually reaches that branch. MySQL converts the numbers to text and succeeds. SQLite does not enforce column types and returns whichever value was chosen. Because behavior varies, write branches that already have the same type:
SELECT first_name,
CASE
WHEN salary >= 100000 THEN 'high'
ELSE CAST(salary AS VARCHAR(20))
END AS salary_or_label
FROM employees;Converting explicitly makes the result type text on every database. VARCHAR is the portable choice here, though PostgreSQL also accepts TEXT, and MySQL requires CHAR in a CAST instead.
Mixed numeric types can also change your numbers. If one branch returns an integer and another a decimal, the whole column becomes decimal, so an integer branch may appear as 1.00. The reverse matters for division: CASE WHEN x > 0 THEN 1 ELSE 2 END is an integer, and dividing by it with / can truncate on engines that use integer division, such as PostgreSQL and SQL Server.
Nested CASE and NULL results
A CASE can appear inside the THEN or ELSE of another CASE. It follows the same rules at each level. The inner CASE is evaluated only when the outer branch that contains it is chosen.
SELECT first_name,
CASE
WHEN department_id = 10 THEN
CASE
WHEN salary >= 100000 THEN 'senior sales'
ELSE 'sales'
END
ELSE 'other'
END AS role_label
FROM employees;Deep nesting is hard to read. When the outer test and the inner test combine with AND, one flat searched CASE is clearer: put the combined condition in a single WHEN.
SELECT first_name,
CASE
WHEN department_id = 10 AND salary >= 100000 THEN 'senior sales'
WHEN department_id = 10 THEN 'sales'
ELSE 'other'
END AS role_label
FROM employees;The order rule is what makes the flat version work. The second branch is only reached when the first failed, so it covers department 10 employees below 100000 (and those with a NULL salary).
Checklist for a CASE you wrote
- Are the
WHENbranches ordered so that the most specific condition comes first? - What happens to rows where a condition is
NULL? They fall through, so check thatELSEhandles them sensibly. - Did you leave out
ELSEon purpose? If so, isNULLthe right output? - Do all
THENandELSEvalues have the same type, or have you cast them? - Are you relying on
CASEto prevent an error from a constant expression or an aggregate? If so, rewrite the guard.
Exercise
The query below is meant to label employees 'high' (100000 or more), 'medium' (50000 or more), and 'low' otherwise. Employees earning 120000 are labeled 'medium', and employees with a NULL salary are labeled 'low'. Fix the ordering so 120000 gets 'high', and add a branch so a NULL salary gets 'unknown'. SELECT first_name, CASE WHEN salary >= 50000 THEN 'medium' WHEN salary >= 100000 THEN 'high' ELSE 'low' END AS band FROM employees;
Show answer
Put the most restrictive condition first and test for NULL explicitly: SELECT first_name, CASE WHEN salary IS NULL THEN 'unknown' WHEN salary >= 100000 THEN 'high' WHEN salary >= 50000 THEN 'medium' ELSE 'low' END AS band FROM employees; A salary of 120000 now matches the 'high' branch first. A NULL salary matches the IS NULL branch. Without it, the comparisons would be unknown and the row would fall to ELSE and be labeled 'low'.
Exercise
What is the result type of CASE WHEN salary >= 100000 THEN 1 ELSE 0.5 END, and what does CASE WHEN salary >= 100000 THEN 'high' END return for an employee earning 40000?
Show answer
The first expression returns a decimal type, because the integer 1 and the decimal 0.5 are converted to a type that holds both, so the 1 branch appears as 1.0 (or similar). The second expression has no ELSE, so it defaults to ELSE NULL and returns NULL for the employee earning 40000. Its type is text, taken from the 'high' branch.