A CASE expression can go wherever a single value can go, and in a SELECT it is usually used to add a column whose value depends on each row. Write one or more WHEN ... THEN pairs, add an optional ELSE, and close the expression with END. Give the new column a name with AS.
The basic structure
CASE
WHEN condition THEN result
WHEN condition THEN result
ELSE default_result
END
WHENholds a test, andTHENholds the result if that test is true.ELSEis optional. It gives the result for rows that match noWHEN.ENDis required and ends the expression.
A CASE in a SELECT query
The examples assume a table called dbo.Students with StudentName, Score and Grade columns. This query adds a Feedback column:
SELECT StudentName,
Score,
CASE
WHEN Score >= 90 THEN 'Excellent'
WHEN Score >= 70 THEN 'Good'
ELSE 'Needs review'
END AS Feedback
FROM dbo.Students;
For the rows Ana (95), Ben (84) and Dara (58), the output is:
| StudentName | Score | Feedback |
|---|---|---|
| Ana | 95 | Excellent |
| Ben | 84 | Good |
| Dara | 58 | Needs review |
The conditions are checked from top to bottom. Ana’s score meets the first test, so she gets Excellent and the second test is not checked for her.
A simple CASE
A simple CASE compares one expression with a list of values. This version labels rows by their Grade:
SELECT StudentName,
CASE Grade
WHEN 'A' THEN 'Honors'
WHEN 'B' THEN 'Good standing'
ELSE 'Other'
END AS Standing
FROM dbo.Students;
A simple CASE only checks for equality. For a range, such as scores from 70 up to 89, use the searched form, as in the first example, and write WHEN Score >= 70 AND Score < 90.
Handling NULL and unmatched rows
A NULL value fails every comparison, including = and >=, so a row with no score goes to the ELSE. If you want a specific label for missing values, give them their own WHEN and put it first:
CASE
WHEN Score IS NULL THEN 'No score'
WHEN Score >= 70 THEN 'Passed'
ELSE 'Failed'
END
Without an ELSE, a row that matches no WHEN gets NULL. Add an ELSE when you want a value for every row.
Where else CASE works
CASE is not limited to the select list. It can also appear in WHERE, ORDER BY and HAVING clauses, and in the SET clause of an UPDATE. For changing data, the guide to a case statement in update query in sql server covers the same expression in more depth.
Common mistakes
- Leaving out
END. The expression is not complete without it, and the query fails with a syntax error. - Putting a broad condition first. With
WHEN Score >= 70placed aboveWHEN Score >= 90, Ana’s 95 getsGood, because the first test is true for her. - Comparing with
= NULL. UseIS NULLinstead. - Mixing result types. Every
THENvalue has to fit one data type. Mixing text such as'Good'with numbers can cause a conversion error. - Treating CASE as a statement. In SQL Server,
CASEis an expression that returns a value. It cannot decide which statements run. For that, T-SQL usesIF ... ELSE.
With these pieces, you can write a CASE in a query and check the values it returns.