CASE WHEN lets you build conditional logic inside SQL statements, returning different values based on each row’s data.
CASE WHEN evaluates each row against one or more conditions and returns the first matching result. If no condition matches, the optional ELSE branch supplies a default.
Use the searched form for complex Boolean expressions, or the simple form when comparing one expression to many values. Both end with END and usually need an alias in SELECT.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END AS alias
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE default_result
END AS alias
Segment customers by purchase size directly in a SELECT. Assign labels such as "High Value", "Medium Value", or "Low Value" based on total_amount thresholds.
Place CASE WHEN inside SELECT to create virtual columns, inside UPDATE to set values conditionally, or in ORDER BY to sort with custom priority.
Wrap the CASE WHEN in a subquery or CTE, then use its alias in an outer WHERE clause. PostgreSQL does not allow CASE directly inside WHERE for filtering.
Keep conditions mutually exclusive to avoid ambiguity. Order WHEN clauses from most-specific to least-specific. Always include an ELSE to handle unexpected data.
Omit END and PostgreSQL raises “CASE construct not terminated.” Always add END and, in SELECT, follow with AS new_column.
Writing CASE expression WHEN condition>10 THEN ... is invalid. Use searched form: CASE WHEN expression>10 THEN ...
Yes in effect, but CASE WHEN is an expression, not a control-flow statement, so it can appear inside SELECT, ORDER BY, GROUP BY, and UPDATE.
Yes. The THEN clause may return the result of a scalar subquery, such as (SELECT AVG(price) FROM Products).
Minimal impact. It is evaluated row-by-row during execution. Use indexes on columns referenced in WHEN conditions for best speed.
Simple compares one expression to many values; searched evaluates full Boolean conditions. Choose based on complexity.
Yes. Place another CASE inside a THEN or ELSE branch to handle multi-level logic, but keep nesting shallow for readability.
No, but omitting ELSE returns NULL when no conditions match, which can hide data issues. Always supply an ELSE.