CASE WHEN returns a calculated value based on the first true condition, enabling inline IF-ELSE logic in any SQL clause.
CASE WHEN lets you embed IF-ELSE logic directly in SQL. It evaluates conditions in order and returns the first matching result, or the ELSE result when none match.
Use the searched form: CASE WHEN condition THEN result [ELSE default] END
. Alias the expression for readability.
You can use it in SELECT
, ORDER BY
, GROUP BY
, HAVING
, UPDATE
, and even inside window functions or subqueries.
Yes. Add successive WHEN
clauses. The first true condition stops evaluation, so order them from most specific to most general.
CASE WHEN total_amount > 1000 THEN 'Large' WHEN total_amount > 500 THEN 'Medium' ELSE 'Small' END AS order_size
Explicitly test for IS NULL
or co-alesce columns. Otherwise, NULL makes comparisons return UNKNOWN and skip true branches.
Minimal. PostgreSQL short-circuits evaluation. Heavy expressions inside branches may slow execution; move them to CTEs when needed.
Indent each WHEN, alias the CASE, and comment complex logic. Future maintainers will thank you.
An explicit ELSE prevents unexpected NULLs and clarifies intent.
No. Use it in SELECT, ORDER BY, GROUP BY, HAVING, or as an update value. For conditional filtering, combine boolean logic directly in WHERE.
PostgreSQL has no standalone IF in standard SQL. CASE WHEN is the ANSI-compliant replacement and works in any SQL context.
There is no explicit limit. Practical readability usually caps the list; refactor when you exceed a dozen conditions.