Conditional logic with CASE
◈ 2 cardsSQL's if/else — bucket and relabel values inline.
if/else, inline
CASE is SQL's conditional expression. It checks conditions top to bottom and returns the first match's value:
SELECT title, price,
CASE WHEN price < 12 THEN 'budget'
WHEN price < 20 THEN 'standard'
ELSE 'premium' END AS band
FROM books;
It works anywhere an expression is allowed — SELECT, WHERE, ORDER BY, even inside an aggregate. There's also a short "simple" form: CASE status WHEN 'paid' THEN 1 ELSE 0 END.