CASE WHEN has two forms. The searched form, which is the one most people use, tests a condition for each WHEN:
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
ELSE default_result
END
The simple form compares one expression with a list of values:
CASE input_expression
WHEN value_1 THEN result_1
WHEN value_2 THEN result_2
ELSE default_result
END
In both forms, END is required and ELSE is optional.
The parts
CASEstarts the expression.WHENandTHENform a pair: the test, and the result if the test is true. You can have as many pairs as you need.ELSEgives the result for rows that match noWHEN. It is optional.ENDcloses the expression.
How SQL checks the branches
SQL checks the WHEN branches in the order you write them. It returns the result of the first one that is true and does not check the rest for that row. If no branch is true and there is no ELSE, the result is NULL.
Because of this order, put the most specific conditions first. For example, test Score >= 90 before Score >= 70.
Simple form or searched form
- The simple form only checks for equality, such as
CASE Grade WHEN 'A' THEN .... - The searched form accepts any true-or-false test, including ranges like
Score >= 70 AND Score < 90, and checks such asIS NULL.
The searched form covers everything the simple form does, so it is the safer choice when you are unsure.
A worked example
This query gives each student a ScoreBand. It uses the searched form, and it tests for missing scores first:
SELECT StudentName,
CASE
WHEN Score IS NULL THEN 'Missing'
WHEN Score >= 70 AND Score < 90 THEN 'Middle'
WHEN Score >= 90 THEN 'Top'
ELSE 'Low'
END AS ScoreBand
FROM dbo.Students;
Ana (95) gets Top, Ben (84) gets Middle, Dara (58) gets Low, and Eli, with no score, gets Missing.
Rules that trip people up
- Result types must fit together. SQL Server returns the highest-precedence data type among the results, and every other result has to convert to it. Mixing text and numbers can cause a conversion error.
- Nesting has a limit. In SQL Server, a CASE can be nested up to 10 levels deep.
- All-NULL results are an error. If every result expression is the literal
NULL, SQL Server returns error 8133. Make at least one result return a column or a typed value.
Where CASE can be used
CASE works in any place that takes an expression. In SQL Server, that includes the SELECT list, WHERE, ORDER BY, HAVING, and the SET clause of an UPDATE.
Portability
The WHEN ... THEN ... ELSE ... END form is standard SQL. It works in SQL Server, MySQL, PostgreSQL, Oracle and SQLite, so the example above can be adapted to most major databases with little change.