CASE WHEN
CASE WHEN is SQL's if-else. Used for bucketing, conditional aggregation, pivoting, and data transformation — appears in almost every real analytics query.
Classify employees as High, Mid, or Low earner based on salary.
SELECT name, salary,
CASE
WHEN salary > 80000 THEN 'High'
WHEN salary > 40000 THEN 'Mid'
ELSE 'Low'
END AS salary_band
FROM employees;CASE WHEN evaluates conditions top to bottom and returns the first match. ELSE handles any row that doesn't match earlier conditions. Without ELSE, unmatched rows return NULL.
Count employees in each salary band.
SELECT
SUM(CASE WHEN salary > 80000 THEN 1 ELSE 0 END) AS high,
SUM(CASE WHEN salary BETWEEN 40000 AND 80000 THEN 1 ELSE 0 END) AS mid,
SUM(CASE WHEN salary < 40000 THEN 1 ELSE 0 END) AS low
FROM employees;Conditional aggregation using CASE inside SUM. Returns one row with three columns instead of three rows — a pivot-style output used in MIS reporting.
Calculate total revenue split by weekday vs weekend orders.
SELECT
SUM(CASE WHEN DAYOFWEEK(order_date) IN (1,7) THEN amount ELSE 0 END) AS weekend_rev,
SUM(CASE WHEN DAYOFWEEK(order_date) NOT IN (1,7) THEN amount ELSE 0 END) AS weekday_rev
FROM orders;DAYOFWEEK returns 1=Sunday, 7=Saturday in MySQL. Conditional aggregation is the standard way to pivot/split data without multiple queries.
Assign a discount based on order amount: 10% if >5000, 5% if >2000, else 0.
SELECT order_id, amount,
CASE
WHEN amount > 5000 THEN amount * 0.10
WHEN amount > 2000 THEN amount * 0.05
ELSE 0
END AS discount
FROM orders;CASE WHEN works in any part of SELECT. Conditions are checked in order — since amount > 5000 is checked first, those rows won't also match amount > 2000.
Update a column conditionally (without actually UPDATE — using CASE in SELECT).
SELECT name,
CASE
WHEN department = 'Sales' THEN 'Customer Facing'
WHEN department IN ('IT', 'Engineering') THEN 'Tech'
ELSE 'Support'
END AS dept_category
FROM employees;CASE WHEN lets you reclassify or relabel values on the fly without changing the underlying data — useful for reporting where business needs different groupings than the data stores.
EVIKA ACADEMY · SQL FOR DATA ANALYTICS
Want to master SQL with live practice?
Join our SQL for Data Analytics course — live classes in Noida and online across India.
Book Free Demo Class →