A CASE expression looks at each row, tests its conditions in order, and returns one value for that row. The example below labels students by their score, which shows how the pieces fit together.
The examples assume a table called dbo.Students with StudentName, Score and Grade columns.
A searched CASE example
This query adds a Feedback column based on each student’s score:
SELECT StudentName,
Score,
CASE
WHEN Score >= 90 THEN 'Excellent'
WHEN Score >= 70 THEN 'Good'
ELSE 'Needs review'
END AS Feedback
FROM dbo.Students;
With the sample rows Ana (95), Ben (84), Chen (71), Dara (58) and Eli (no score), the output is:
| StudentName | Score | Feedback |
|---|---|---|
| Ana | 95 | Excellent |
| Ben | 84 | Good |
| Chen | 71 | Good |
| Dara | 58 | Needs review |
| Eli | NULL | Needs review |
How each row is checked
- Ana: 95 is at least 90, so the first test is true and she gets
Excellent. The second test is never checked for her. - Ben and Chen: their scores fail the first test but pass the second, so they get
Good. - Dara: her score passes neither test, so the
ELSEvalue applies. - Eli: a
NULLscore makes both comparisons unknown rather than true, so he also gets theELSEvalue.
If you want a specific label for missing scores, add WHEN Score IS NULL THEN 'No score' as the first branch.
A simple CASE example
A simple CASE compares one expression with a list of values. This query labels each row by its Grade:
SELECT StudentName,
CASE Grade
WHEN 'A' THEN 'Honors'
WHEN 'B' THEN 'Good standing'
ELSE 'Other'
END AS Standing
FROM dbo.Students;
Here the value in Grade is compared with 'A' and then with 'B'. Any other grade, or a missing one, gets Other.
CASE is an expression in SQL Server
Many people call this a “CASE statement,” but in SQL Server it is an expression. It returns a value for a column or a query, and it cannot control which statements run. The SQL Server documentation says it can’t be used to control the flow of Transact-SQL statements, blocks, functions or procedures. For that, T-SQL uses IF ... ELSE.
Some other systems do have a separate CASE statement. In MySQL, for example, a procedural CASE statement is used inside stored programs. If you searched for a CASE statement in SQL Server, the expression described here is what you need.
Using CASE to change data
The same expression can go in the SET clause of an UPDATE, which lets each row get a different value. For a step-by-step guide to that, read the article on case statement in update query in sql server, which covers the same rules for ELSE and NULL in a data-changing statement.