CASE
Inline conditional expression. Evaluates WHEN branches top-to-bottom and returns the first match; returns ELSE (or NULL if omitted) when nothing matches. Works anywhere an expression is allowed: SELECT, WHERE, ORDER BY, aggregate arguments.
Syntax #
sql
CASE
WHEN condition_1 THEN value_1
WHEN condition_2 THEN value_2
ELSE fallback
ENDExample #
Loading SQL editor...
Warning
Branch order is evaluated top-down, first match wins. Overlapping conditions with the broad one listed first make later branches unreachable, and the query still runs with no error. Write branches from narrowest to broadest (>= 200 before >= 50). Missing ELSE silently returns NULL, which can distort averages and filtered sums; spell out the fallback unless NULL is truly what you want.