What are the two forms of the CASE expression, and when should I reach for each one?
Simple CASE compares one expression against a list of values and returns the matching branch. Searched CASE evaluates a condition for each branch in order and returns the first one that is true. Searched CASE is the more flexible form and the one you will use most.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL
);
INSERT INTO orders (id, customer_id, amount, status) VALUES
(1, 1, 120.00, 'shipped'),
(2, 1, 75.50, 'pending'),
(3, 2, 940.00, 'pending'),
(4, 2, 30.00, 'cancelled');
-- Searched CASE: a condition per branch, first match wins.
SELECT id,
amount,
CASE
WHEN amount >= 500 THEN 'large'
WHEN amount >= 100 THEN 'medium'
ELSE 'small'
END AS size_band
FROM orders
ORDER BY id;The bands come out large, medium, large and small. Order 3 is large even though it is still pending, because the CASE only looks at amount — status is not part of the condition. Keep unrelated conditions out of a CASE or the branch order starts to matter in ways that are easy to misread.
Searched CASE stops at the first matching WHEN, so the branch order encodes a priority. If you write WHEN amount >= 100 before WHEN amount >= 500, every large order is classified as medium, because the first branch already matched.
Simple CASE is the switch statement shape: CASE status WHEN 'pending' THEN ... WHEN 'shipped' THEN ... END. It is neater when you are mapping one column through a fixed set of values, and it is the right choice when the mapping must be exhaustive — pair it with an ELSE branch so an unexpected status produces a visible value rather than NULL.
The rule that catches people out: CASE lives in the expression list, so it belongs in SELECT, ORDER BY, GROUP BY or inside another expression — but not in WHERE. To filter on a computed value, wrap the query in a CTE or a subquery and filter on the alias in the outer query.