In SQL, the CASE WHEN expression provides conditional IF...THEN...ELSE logic inside a SELECT statement (as well as in WHERE, ORDER BY, and GROUP BY clauses). SQL evaluates WHEN conditions top-to-bottom and returns the value from the first condition that evaluates to true, or the ELSE value if no condition matches.
1. Searched CASE WHEN (General Boolean Conditions)
Use searched CASE WHEN when checking ranges, comparisons, NULLs, or multiple columns. This is the most flexible form and mirrors IF / ELSE IF / ELSE.
SELECT
order_id,
total_amount,
CASE
WHEN total_amount IS NULL THEN 'Unknown'
WHEN total_amount >= 1000 THEN 'High Value'
WHEN total_amount >= 250 THEN 'Medium Value'
ELSE 'Standard'
END AS order_tier
FROM orders;
- Conditions are evaluated in order: a row with
total_amount = 1500matches>= 1000first and stops there. - Always include an
ELSEbranch when you want a fallback value; withoutELSE, unmatched rows returnNULL.
2. Simple CASE Expression (Comparing One Column to Exact Values)
Use simple CASE <expression> WHEN <value> when testing a single expression for equality against specific constants.
SELECT
ticket_id,
status_code,
CASE status_code
WHEN 'O' THEN 'Open'
WHEN 'P' THEN 'In Progress'
WHEN 'C' THEN 'Closed'
ELSE 'Other'
END AS status_label
FROM support_tickets;
Note: Avoid using simple
CASE status_code WHEN NULL THEN ...to check forNULL; use searchedCASE WHEN status_code IS NULL THEN ...instead.
3. Conditional Aggregation (COUNT / SUM with CASE WHEN)
Placing CASE WHEN inside aggregate functions lets you compute multiple conditional totals or counts in a single scan of a table.
SELECT
department_id,
COUNT(*) AS total_employees,
COUNT(CASE WHEN status = 'ACTIVE' THEN 1 END) AS active_count,
SUM(CASE WHEN status = 'ACTIVE' THEN salary ELSE 0 END) AS active_payroll
FROM employees
GROUP BY department_id;
COUNT(CASE WHEN ... THEN 1 END)ignoresNULLs, so rows where the condition is false are not counted.SUM(CASE WHEN ... THEN amount ELSE 0 END)safely adds0for non-matching rows.
4. CASE WHEN Inside ORDER BY or WHERE
You can also use CASE WHEN to customize sorting order or apply conditional filters.
SELECT
task_id,
title,
priority
FROM tasks
ORDER BY
CASE priority
WHEN 'URGENT' THEN 1
WHEN 'HIGH' THEN 2
WHEN 'MEDIUM' THEN 3
WHEN 'LOW' THEN 4
ELSE 5
END ASC,
created_at DESC;
Best Practices for CASE WHEN
- Order conditions from most specific to broadest: Put narrow thresholds or special cases above wider ranges so earlier rules do not mask later ones.
- Keep return types compatible: Ensure branches return compatible data types (for example, all strings or all numbers) to avoid type-casting errors.
- Give the column a clear alias: Add
AS column_nameafterENDso output columns are easy to read and query downstream.
