CASE WHEN performs conditional logic, returning different values based on evaluated expressions within a query.
CASE WHEN lets you embed IF-ELSE logic inside SQL statements, replacing nested queries or client-side code. It produces calculated columns, categorizes data, and drives conditional aggregations.
Write CASE, list WHEN condition THEN result pairs, add an optional ELSE fallback, and close with END. The expression returns the result whose condition evaluates to TRUE.
Chain additional WHEN clauses. SQL Server evaluates them top-down and stops at the first TRUE match, so order matters. Place the most specific conditions first.
Select Orders.total_amount and wrap it in CASE to label each order as 'High', 'Medium', or 'Low'. This provides readable buckets without altering stored data.
Return numeric values in CASE so you can sort rows by custom priority. This is handy for pushing flagged or VIP records to the top of result sets.
Searched CASE compares full boolean conditions (WHEN total_amount > 500). Simple CASE compares a single expression to multiple literals (CASE status WHEN 'open' THEN …).
Using CASE in WHERE often leads to scans because each row must evaluate every branch. Instead, split the query with UNION ALL or use separate predicates.
Keep CASE determinate and non-volatile, avoid scalar functions inside, and align data types across THEN results. Always include ELSE to prevent NULL surprises.
Yes, place an inner CASE inside a THEN or ELSE clause, but keep nesting shallow to preserve readability.
CASE is computed row-by-row but remains lightweight. Performance issues arise only when it disables index use or calls expensive functions.
ELSE is optional, yet recommended. Without it, unmatched rows return NULL, which may break aggregates or client code.