Label SQL Query Results with CASE Expressions

CASE returns one value from a list of alternatives. It is useful for labels, categories and conditional calculations inside a query. It is an expression, so it does not execute separate statement blocks like IF...ELSE.

Map Codes with a Simple CASE

SQL
SELECT Code,
       CASE Code
           WHEN N'R' THEN N'Ready'
           WHEN N'H' THEN N'On hold'
           ELSE N'Unknown'
       END AS StatusLabel
FROM (VALUES (N'R'), (N'H'), (N'X')) AS v(Code)
ORDER BY Code;

The output maps R to Ready, H to On hold and X to Unknown. A simple CASE compares one input expression with each listed value.

Use Conditions for Ranges and Nulls

SQL
SELECT ItemId, Quantity,
       CASE
           WHEN Quantity IS NULL THEN N'Not recorded'
           WHEN Quantity < 0 THEN N'Invalid'
           WHEN Quantity = 0 THEN N'Empty'
           WHEN Quantity < 10 THEN N'Low'
           ELSE N'Available'
       END AS StockLabel
FROM (VALUES (1, 0), (2, 4), (3, 10), (4, NULL), (5, -1))
     AS v(ItemId, Quantity)
ORDER BY ItemId;

Expect Empty, Low, Available, Not recorded and Invalid in item order. The searched form evaluates conditions, so arrange overlapping ranges with the most specific tests first. IS NULL is the appropriate test for a missing value.

Avoid Type and Evaluation Surprises

Keep all result branches compatible. Mixing text labels and numbers can trigger implicit conversions according to data-type precedence. Convert deliberately if the desired result is text. When ELSE is omitted and nothing matches, the result is null.

Do not rely on CASE as a universal short-circuit guard for expressions that can fail, particularly aggregates evaluated before the expression. To handle a potentially zero denominator, use an appropriate operation such as numerator / NULLIF(denominator, 0) and decide how null should be represented. CASE labels data, but it does not enforce a database constraint or repair invalid stored values.

Microsoft References

Author: Herman Schoenfeld