CASE WHEN for
Categories
Learn how to use SQL's CASE WHEN expression to transform raw data into meaningful derived categories directly inside your queries.
What is CASE WHEN?
The CASE WHEN expression is SQL's way of adding if/then/else logic directly inside a query. It evaluates conditions in order and returns a value for the first condition that is true.
Why Derive Categories?
Raw data often contains continuous values (scores, prices, ages) that are hard to summarize. Derived categories let you bucket those values into meaningful groups for analysis and reporting.
The Grading Analogy
A teacher converts numeric scores into letter grades. The score column stays numeric, but the grade column is a new, derived category based on rules.
The Syntax Blueprint
How SQL Evaluates CASE
CASE WHEN vs IF/ELSE
Some databases offer an IF() function. Here is how it compares to CASE WHEN:
| CASE WHEN | IF() | |
|---|---|---|
| Standard SQL | ✓ Yes, all databases | ✕ MySQL/SQLite only |
| Multiple branches | ✓ Unlimited WHEN clauses | ~ Requires nested IFs |
| Readability (3+ branches) | ✓ Clear and structured | ✕ Hard to read when nested |
| Use in GROUP BY | ✓ Works natively | ✓ Works natively |
How to Apply CASE WHEN
Example 1: Grade Buckets
Assign letter grades from a students table with a score column:
Example 2: Revenue Tiers
Classify orders by total_amount into revenue tiers:
Example 3: CASE + GROUP BY
Count employees by experience category from an employees table:
Visualizing the Output
Advanced: Multi-Column Conditions
CASE WHEN conditions can reference multiple columns and use AND/OR logic:
Common Mistakes
CASE WHEN Cheat Sheet
| Concept | Details |
|---|---|
| Purpose | Create derived categories from raw values |
| Evaluation | Top-down: first true condition wins |
| Required keywords | CASE, WHEN, THEN, END |
| Optional keyword | ELSE (strongly recommended) |
| Works with | SELECT, GROUP BY, ORDER BY, WHERE |
| Portability | ✓ ANSI SQL standard: all databases |
| Naming result | Use AS alias_name after END |
Question 1 of 5
What keyword must end every CASE WHEN expression?
Question 2 of 5
If a row does not match any WHEN condition and there is no ELSE clause, what value is returned?
Question 3 of 5
Consider this query fragment:
CASE
WHEN score \( \geq \) 60 THEN 'Pass'
WHEN score \( \geq \) 90 THEN 'Honors'
ELSE 'Fail'
END AS result
A student has a score of 95.
What value does result contain for this student?
Question 4 of 5
You want to count how many orders are in each revenue tier (High, Medium, Low). Which clause do you combine with CASE WHEN?
Question 5 of 5
Consider this query:
SELECT product,
CASE
WHEN price \( > \) 100 AND stock \( < \) 10 THEN 'Premium-Scarce'
WHEN price \( > \) 100 THEN 'Premium'
WHEN stock \( < \) 10 THEN 'Low-Stock'
ELSE 'Standard'
END AS status
FROM products;
A product has price = 150 and stock = 5.
What status does this product receive?