CASE WHEN returns different values based on Boolean conditions evaluated row-by-row.
CASE WHEN lets you branch logic inside a SELECT, UPDATE, or ORDER BY. It checks conditions top-down and returns the first matching result, giving you IF/ELSE behavior without procedural code.
Write CASE, then one or more WHEN condition THEN value pairs, optionally an ELSE value, and finish with END.PostgreSQL evaluates each row individually.
CASE WHEN keeps transformations in a single SQL statement, reducing round trips and ensuring consistent logic across rows.
Use CASE WHEN to label Orders as ‘Small’, ‘Medium’, or ‘Large’ based on total_amount. This enables instant dashboard grouping without editing application code.
Yes. Place another CASE inside the THEN or ELSE clause.Keep nesting minimal for readability.
No. WHERE expects a Boolean. Instead, move CASE WHEN to a subquery or use OR/AND directly in WHERE.
Yes. If the first WHEN matches most rows, evaluation stops early and saves CPU.
.
No. All THEN and ELSE branches must be implicitly castable to a single data type. Use explicit CAST() when needed.
Minorly. PostgreSQL evaluates sequentially, so order conditions by likelihood. Indexes are unaffected.