Sub topic 8
Searched CASE: WHEN condition THEN result
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries, know the common column types (numbers, text, dates), and understand GROUP BY with aggregates like COUNT and SUM. It also assumes you have seen computed columns and aliases earlier in the tutorial, such as salary * 12 AS annual_salary.
What a searched CASE is
A searched CASE expression is SQL's way of choosing one value from several, based on conditions you write. It is an expression, not a statement. It produces a single value for each row, so you can use it anywhere you could use a column or a literal.
The general form is:
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
ELSE default_result
ENDEach condition is a full boolean test, the same kind you would put in a WHERE clause. The database checks the conditions from top to bottom and returns the result for the first condition that is true. If none is true, it returns the ELSE value.
The word "searched" separates this form from the simple CASE, which compares one expression against a list of values. The simple form has its own chapter. The searched form is the more general one, because every WHEN can test something completely different.
A first example
This query sorts each employee into a salary band:
SELECT first_name,
salary,
CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees;For each row, the database evaluates salary >= 100000. If it is true, the row gets 'high' and the remaining branches are skipped. Otherwise it tests salary >= 50000. A row that fails both tests gets 'low' from ELSE.
The AS salary_band is a column alias, as in earlier chapters. Without it, most databases would label the column with the raw CASE text or a generated name.
The next diagram shows the flow for one row.
The parts of the expression
| Part | Role | Notes |
|---|---|---|
| `CASE` | Opens the expression | Nothing follows it before the first `WHEN` |
| `WHEN condition` | A boolean test | Any predicate that is valid in `WHERE` |
| `THEN result` | The value to return | Any expression, not only a literal |
| `ELSE default` | Value when no `WHEN` is true | Optional |
| `END` | Closes the expression | Required, and easy to forget |
You need at least one WHEN ... THEN pair. Most databases do not limit how many you can have.
Order matters
Because the first true condition wins, the order of the branches changes the result. Ranges are the usual trap. Here the branches are reversed:
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 passes the first test (>= 50000), so the row gets 'medium'. The 'high' branch can never be reached. The query runs without any error, and every high earner is mislabeled.
When you write range conditions, put the most restrictive test first. With open-ended ranges like these, that means going from the largest threshold down. Alternatively, make each branch independent by using BETWEEN or an explicit upper bound, so the order no longer matters:
SELECT first_name,
salary,
CASE
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 AND salary < 100000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees;The extra bound is redundant here, but it makes each branch readable on its own. That helps when someone later reorders or edits the list.
Conditions can be any predicate
A searched CASE is flexible because each WHEN holds a complete condition. You can combine tests with AND, OR, and NOT, and use IN, BETWEEN, LIKE, and IS NULL. You can also compare one column to another, or test different columns in different branches:
SELECT first_name,
department_id,
salary,
commission,
CASE
WHEN department_id IN (10, 20) AND salary >= 80000 THEN 'priority'
WHEN commission IS NOT NULL THEN 'commissioned'
WHEN first_name LIKE 'A%' THEN 'a-names'
ELSE 'standard'
END AS review_group
FROM employees;The three branches test three different things. The simple CASE form cannot do this, because it compares a single expression for equality each time.
The result can be an expression
The THEN and ELSE parts accept any expression, including column references and arithmetic. This lets you apply a different formula depending on the row:
SELECT first_name,
salary,
salary * CASE
WHEN salary < 50000 THEN 1.05
WHEN salary < 100000 THEN 1.03
ELSE 1.01
END AS salary_after_raise
FROM employees;Here the whole CASE acts as a number inside a multiplication. Because it is an expression, it can sit inside a larger expression, as an argument to a function, or inside another CASE. Deep nesting gets hard to read, so prefer a flat list of WHEN branches when you can.
Testing for NULL
A WHEN condition passes only when it evaluates to true. If it evaluates to false or to unknown, the database moves to the next branch. This matters because comparing anything to NULL gives unknown, not true or false.
Suppose a row has a NULL salary. In the salary band query, salary >= 100000 is unknown, and so is salary >= 50000. Both branches are skipped and the row falls to ELSE, so a missing salary gets labeled 'low'. The query reports no error. It is just wrong.
To handle missing values explicitly, test for NULL with IS NULL and put that branch first:
SELECT first_name,
salary,
CASE
WHEN salary IS NULL THEN 'unknown'
WHEN salary >= 100000 THEN 'high'
WHEN salary >= 50000 THEN 'medium'
ELSE 'low'
END AS salary_band
FROM employees;The same rule explains why you must use a searched CASE to test for NULL:
SELECT first_name,
CASE
WHEN commission IS NULL THEN 'no commission'
ELSE 'has commission'
END AS commission_status
FROM employees;Writing WHEN commission = NULL would never be true, because commission = NULL is unknown for every row. Every row would go to ELSE.
Leaving out ELSE
ELSE is optional. If no WHEN is true and there is no ELSE, the expression returns NULL. A later chapter covers this default and the rules for the result type in detail. For now, keep one habit in mind. Unless you want NULL for unmatched rows, write an ELSE, so that a surprising row produces a visible value such as 'other' instead of a quiet NULL.
Keeping result types compatible
All the THEN and ELSE results are combined into one column type for the whole expression. Mixing a text result with a number, as in THEN 'high' ... ELSE 0, produces an error in strict databases such as PostgreSQL. Other databases may convert the values silently, which can give surprising output. Choose one type for all branches. If the branches differ, convert them explicitly, for example with CAST(salary AS VARCHAR(20)). The chapter on type conversion and dialect differences returns to this.
Common mistakes
- Forgetting
END. The parser reports a syntax error, usually near the next keyword, which can make the real cause hard to spot. - Using commas between branches. Branches are separated only by whitespace, as in
WHEN ... THEN ... WHEN ... THEN .... - Putting a column name after
CASEand then writing full conditions.CASE salary WHEN salary >= 100000 THEN ...mixes the simple form with the searched form. Either drop the column afterCASE(searched) or compare it to plain values in eachWHEN(simple). - Ordering overlapping ranges badly. The first true branch wins, so check the order whenever conditions can overlap.
- Expecting
NULLto match a comparison. UseIS NULLexplicitly. - Mixing result types. Keep every
THENandELSEvalue to one type.
Exercises
Exercise
A query uses CASE WHEN score >= 60 THEN 'pass' WHEN score >= 90 THEN 'distinction' ELSE 'fail' END. A student with score 95 is reported as 'pass'. Why, and how do you fix it?
Show answer
The first true branch wins. 95 satisfies score >= 60, so 'pass' is returned and the score >= 90 branch is never tested. Put the more restrictive condition first: WHEN score >= 90 THEN 'distinction' WHEN score >= 60 THEN 'pass' ELSE 'fail'.
Exercise
Write a query on employees (firstname, commission) that returns firstname and a column pay_type. It should show 'salary only' when commission is missing and 'salary plus commission' otherwise. Explain why CASE commission WHEN NULL would not work.
Show answer
SELECT firstname, CASE WHEN commission IS NULL THEN 'salary only' ELSE 'salary plus commission' END AS paytype FROM employees; The form CASE commission WHEN NULL compares commission = NULL, which is unknown for every row and never true, so every row would take the ELSE branch. NULL has to be tested with IS NULL in a searched CASE.
Exercise
In the salary band query, an employee has a NULL salary. Without an IS NULL branch, what band do they get, and why?
Show answer
They get the ELSE value, 'low'. The conditions salary >= 100000 and salary >= 50000 both evaluate to unknown for a NULL salary, and a WHEN branch is taken only when its condition is true. Every branch is skipped and the row reaches ELSE. Adding WHEN salary IS NULL THEN 'unknown' as the first branch fixes it.