Sub topic 9
Simple CASE: Comparing One Value to Many
This chapter assumes you can write a basic SELECT ... FROM ... WHERE query and know common column types such as numbers, text, and dates. It also assumes you have seen the searched CASE form (CASE WHEN condition THEN result) from the previous chapter. Here you will learn the second form, the simple CASE. It is shorter to write for one job: translating the values of a single expression into other values.
The shape of a simple CASE
A simple CASE names one expression right after the CASE keyword. Each WHEN then supplies a value to compare against it.
CASE expression
WHEN value_1 THEN result_1
WHEN value_2 THEN result_2
ELSE default_result
ENDThe database compares expression to value_1 with equality. If they are equal, the whole CASE returns result_1. If not, it tries value_2, and so on. If no WHEN matches, it returns the ELSE result.
Here is the classic use. An orders table stores a one-letter status code, and you want readable labels:
SELECT order_id,
CASE status
WHEN 'P' THEN 'Pending'
WHEN 'S' THEN 'Shipped'
WHEN 'D' THEN 'Delivered'
ELSE 'Unknown'
END AS status_label
FROM orders;For each row, the database reads status and walks down the WHEN list. A row with status = 'S' produces Shipped. A row with status = 'X' matches nothing and produces Unknown. The result is a new column named status_label, and the stored data does not change.
A shorthand for equality tests
A simple CASE is shorthand for a searched CASE in which every condition has the form expression = value. These two queries are equivalent:
-- Simple form
SELECT order_id,
CASE status
WHEN 'P' THEN 'Pending'
WHEN 'S' THEN 'Shipped'
ELSE 'Other'
END AS status_label
FROM orders;
-- Searched form
SELECT order_id,
CASE
WHEN status = 'P' THEN 'Pending'
WHEN status = 'S' THEN 'Shipped'
ELSE 'Other'
END AS status_label
FROM orders;The simple form has two advantages:
- You write the tested expression once, so there is less to mistype.
- When the expression is long, such as
UPPER(TRIM(country_code)), the query stays readable.
Because the two forms mean the same thing, everything that is true of equality in SQL carries over. That includes the case rules for text and the behavior of NULL, covered below.
What simple CASE cannot do
The simple form only tests equality, against one expression. That rules out several things a searched CASE handles easily.
| You want to... | Simple CASE | Use instead |
|---|---|---|
| Test a range such as `salary >= 50000` | No | Searched CASE |
| Test two different columns in one `CASE` | No | Searched CASE |
| Match several values with one `WHEN` | No (portably) | Searched CASE with `IN (...)` |
| Test for `NULL` | No | Searched CASE with `IS NULL` |
The multiple-value case comes up often. You might want 'P' and 'S' both to count as open orders. The portable answer is a searched CASE:
SELECT order_id,
CASE
WHEN status IN ('P', 'S') THEN 'open'
ELSE 'closed'
END AS order_state
FROM orders;Or you can repeat the result in two simple WHEN branches (WHEN 'P' THEN 'open' followed by WHEN 'S' THEN 'open').
The NULL trap
This is the most common mistake with the simple form. Equality with NULL is never true, and NULL = NULL is not true either. It evaluates to unknown. Every WHEN in a simple CASE is an equality test, so WHEN NULL can never match:
SELECT first_name,
CASE commission
WHEN NULL THEN 'no commission'
ELSE 'has commission'
END AS commission_status
FROM employees;This query runs without error, but every row, including rows where commission is NULL, falls through to 'has commission'. The result is wrong and gives no warning.
The fix is a searched CASE with IS NULL:
SELECT first_name,
CASE
WHEN commission IS NULL THEN 'no commission'
ELSE 'has commission'
END AS commission_status
FROM employees;The same applies when the tested expression is NULL for a row. If status is NULL, then no WHEN 'P', WHEN 'S', or any other value matches. The row goes to ELSE. That is often what you want, since the ELSE 'Unknown' branch can serve as the catch-all for missing data. Just be aware that you are relying on it.
Order, duplicates, and the missing ELSE
The WHEN values are checked from top to bottom, and the first match wins. Later branches are not used for that row, even if they would also match.
SELECT order_id,
CASE status
WHEN 'S' THEN 'Shipped'
WHEN 'S' THEN 'Sent'
ELSE 'Other'
END AS label
FROM orders;Rows with status 'S' always get Shipped. The second WHEN 'S' is dead code, and most databases accept it without complaint. Duplicates are usually a copy-and-paste mistake, so look for them when a mapping seems to ignore one of your branches.
If you leave out ELSE and no WHEN matches, the CASE returns NULL. That behavior is easy to miss in a report: a status code added to the system next month will silently show as an empty label. Writing an explicit ELSE makes the unexpected value visible. The next chapter covers evaluation order, the default ELSE NULL, and result types in full.
Types and text comparison
Two typing rules matter for the simple form.
- The tested expression and each
WHENvalue must be comparable. Comparing a text column to a number, as inCASE status WHEN 1 THEN ..., may raise a type error or trigger an implicit conversion, depending on the database. Match the types explicitly. Ifstatusis stored as text, write'1'. - All
THENandELSEresults must resolve to one compatible type. Mixing'Pending'and0as results fails in strict databases such as PostgreSQL. Use text in every branch, or cast the results.
Text equality also follows the column's collation, which is the rule set for comparing and sorting text. In a case-insensitive collation, as is common in SQL Server and MySQL, 'p' matches WHEN 'P'. In a case-sensitive setup, as is typical in PostgreSQL, it does not. With fixed-width CHAR columns, trailing spaces can also affect comparisons. When the data is messy, normalize the expression once at the top:
SELECT order_id,
CASE UPPER(TRIM(status))
WHEN 'P' THEN 'Pending'
WHEN 'S' THEN 'Shipped'
WHEN 'D' THEN 'Delivered'
ELSE 'Unknown'
END AS status_label
FROM orders;This is where the simple form is at its best. The cleanup appears once, not in every branch.
Common uses
Simple CASE fits wherever you decode a small, fixed set of values.
- Decoding codes into labels, as in the status example above.
- Custom sort keys. Mapping values to numbers gives an order that alphabetical sorting cannot:
SELECT order_id, status
FROM orders
ORDER BY CASE status
WHEN 'urgent' THEN 1
WHEN 'normal' THEN 2
ELSE 3
END,
order_id;Alphabetically, normal sorts before urgent. The CASE turns each status into a rank, so urgent orders come first. The final order_id makes the order stable within each rank. A later chapter covers CASE in ORDER BY, GROUP BY, and WHERE in more detail.
- Choosing a code per row for aggregation, which the conditional aggregation chapter builds on.
Choosing between the two forms
Use this rule: if every condition is "the same expression equals a literal", use the simple form. Otherwise use the searched form. Moving from simple to searched later costs nothing, because the meaning is the same.
| Situation | Better choice |
|---|---|
| Map status codes to labels | Simple |
| Map a normalized expression such as `UPPER(TRIM(x))` to labels | Simple |
| Band salaries into low, medium, and high | Searched |
| Handle `NULL` and non-`NULL` values differently | Searched |
| Combine conditions with `AND` and `OR` | Searched |
Common errors
WHEN NULL: it never matches. UseIS NULLin a searchedCASE.- Comparison operators in a simple
CASE:CASE salary WHEN >= 50000 THEN ...is a syntax error. Only values are allowed afterWHEN. - Forgetting
END: everyCASE, in either form, must be closed withEND. - Mixed result types: a text label in one branch and a number in another can fail or force a surprising conversion.
- No
ELSE: unmatched rows quietly becomeNULL. - Wrong comma placement: a
CASEis a single expression, so the commas that separate select-list items go afterEND AS alias, not inside it.
Exercise
A query uses CASE region WHEN NULL THEN 'unassigned' ELSE region END AS region_label. Customers whose region is NULL still show NULL in region_label. Why, and how do you fix it?
Show answer
In a simple CASE each WHEN is an equality test, and region = NULL is never true, so the NULL rows fall through to ELSE and return region, which is NULL. Rewrite it as a searched CASE: CASE WHEN region IS NULL THEN 'unassigned' ELSE region END AS region_label. (COALESCE(region, 'unassigned') also works.)
Exercise
Write a query on orders(order_id, status) that returns order_id and a column is_open. It should give 'yes' for status 'P' or 'S', 'no' for status 'D', and 'unknown' for anything else, including NULL. Use a simple CASE only.
Show answer
SELECT orderid, CASE status WHEN 'P' THEN 'yes' WHEN 'S' THEN 'yes' WHEN 'D' THEN 'no' ELSE 'unknown' END AS isopen FROM orders; A NULL status matches no WHEN value, so it reaches ELSE.
Exercise
Which of these cannot be written as a simple CASE: (a) mapping 'M', 'F' to 'Male', 'Female'; (b) labelling age under 18 as 'minor'; (c) mapping the result of UPPER(country) to region names? Explain.
Show answer
Only (b). It needs a comparison (age < 18), and a simple CASE can only test equality against listed values. (a) and (c) are equality mappings on one expression, so the simple form works for both.