CASE WHEN lets you return different values based on Boolean conditions inside SELECT, UPDATE, ORDER BY, and HAVING clauses.
CASE WHEN evaluates each listed condition in order and returns the first matching result. If no condition is met, ELSE supplies a fallback. This avoids multiple sub-queries or joins for simple conditional logic.
Start with CASE
, add one or more WHEN condition THEN value
pairs, finish with optional ELSE value
, and close with END
. Embed it anywhere an expression is allowed.
Use the expression in SELECT lists, ORDER BY sorting, GROUP BY aggregations, HAVING filters, UPDATE/DELETE SET clauses, and even inside stored routines.
Yes—nest them for multi-level logic or chain multiple conditions in a single CASE block. Keep readability high by limiting depth to two levels.
IF() handles a single condition, returning one of two values. CASE WHEN supports many conditions, is ANSI-SQL compliant, and integrates cleanly with GROUP BY and ORDER BY.
Evaluate mutually exclusive conditions first, keep expressions deterministic, alias the result column, and index columns referenced in conditions for speed.
No. It usually executes faster because it eliminates additional scans, but complex expressions may still require indexes.
Yes. Combine CASE WHEN with SET to update rows differently based on conditions.
Both forms work. Omit the expression after CASE for searched CASE, or supply a column/expression for simple CASE.