Sub topic 3
Simple CASE: comparing one value to many
This chapter assumes you can write SELECT ... FROM ... WHERE queries, know common data types, and use GROUP BY with COUNT and SUM.
A simple CASE expression compares one value to a list of candidates and returns the label for the first match. Its form is CASE expression WHEN value THEN result ... ELSE default END.
SELECT order_id,
CASE status
WHEN 'P' THEN 'Pending'
WHEN 'S' THEN 'Shipped'
WHEN 'D' THEN 'Delivered'
ELSE 'Unknown'
END AS status_label
FROM orders;Each WHEN value is compared with equality. A simple CASE cannot test ranges such as salary >= 50000, and it cannot test for NULL. Use a searched CASE (WHEN condition THEN result) for those cases.
How CASE evaluates
CASE checks WHEN branches from top to bottom and returns the result of the first true branch. It stops at that point, so list specific conditions before general ones. If no branch matches and there is no ELSE, the result is NULL.
All THEN and ELSE results should share one data type. Some engines convert them silently. Others raise an error when a value cannot be converted. Use CAST when the types differ.
Using CASE in ORDER BY, GROUP BY, and WHERE
CASE can sort rows by a custom order:
SELECT order_id, status
FROM orders
ORDER BY CASE status
WHEN 'urgent' THEN 1
WHEN 'normal' THEN 2
ELSE 3
END,
order_id;To group by a CASE result, repeat the expression in GROUP BY. In WHERE, a CASE can build a condition:
SELECT order_id
FROM orders
WHERE CASE status WHEN 'P' THEN 1 ELSE 0 END = 1;Conditional aggregation with CASE
Placing CASE inside SUM or COUNT counts only the rows that meet a condition. One pass over the table produces several totals:
SELECT department_id,
COUNT(*) AS headcount,
SUM(CASE WHEN salary >= 100000 THEN 1 ELSE 0 END) AS high_earners
FROM employees
GROUP BY department_id;Type conversion and dialect differences
- PostgreSQL can reject a CASE whose branches mix incompatible types, such as text and integer.
- PostgreSQL and MySQL accept a SELECT alias in GROUP BY. SQL Server and Oracle require the full expression there.
- Some dialects use different names or syntax for conditional functions, so check your engine's documentation.
Exercise
Exercise
Write a query that labels each employee's salary as 'high' (100000 or more) or 'standard', and counts the rows in each label. Use a searched CASE.
Show answer
SELECT CASE WHEN salary >= 100000 THEN 'high' ELSE 'standard' END AS band, COUNT(*) AS n FROM employees GROUP BY CASE WHEN salary >= 100000 THEN 'high' ELSE 'standard' END;