CASE WHEN adds conditional logic to SQL statements, returning the first matching value or expression, much like an inline IF-ELSE.
CASE WHEN evaluates conditions in the order written and returns the result for the first true condition; if none match, the optional ELSE result is used. This lets you label, transform, or bucket data without altering source tables.
Start with CASE
, add one or more WHEN condition THEN result
pairs, optionally finish with ELSE default
, then close with END
.Embed the block inside SELECT, UPDATE, ORDER BY, or WHERE.
SELECT id, CASE WHEN total_amount > 500 THEN 'High' ELSE 'Regular' END AS order_tierFROM Orders;
Use it in SELECT to create derived columns, in ORDER BY to sort by custom rules, in UPDATE to change values conditionally, or in WHERE for advanced filtering.
Label each product’s stock status: SELECT name, CASE WHEN stock = 0 THEN 'Out of Stock' WHEN stock < 10 THEN 'Low' ELSE 'In Stock' END AS statusFROM Products;
Prioritize unfulfilled orders: SELECT * FROM OrdersORDER BY CASE WHEN total_amount IS NULL THEN 1 ELSE 0 END, order_date;
Order conditions from most to least specific.PostgreSQL checks top to bottom and stops at the first true match, so place narrow filters first to avoid unintended matches.
Keep blocks readable with line breaks, alias computed columns, always supply ELSE when NULL is unacceptable, and avoid deeply nested CASE statements—consider CTEs for clarity.
.
Yes. Wrap the CASE WHEN inside the comparison, but ensure it resolves to a boolean. Example: WHERE CASE WHEN total_amount > 100 THEN TRUE ELSE FALSE END
.
Generally no; it is processed within a single scan, often making queries faster than multiple UNIONs. Indexes still apply to referenced columns.
Yes, PostgreSQL supports nested CASE expressions, but readability suffers. Prefer CTEs or subqueries when logic becomes complex.