01 / 20

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.

SQL

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.

Expression
Lives inside SELECT, ORDER BY, or WHERE clauses
Non-destructive
Original data stays unchanged: categories are derived on the fly

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.

Reporting
Group sales into "Low", "Medium", "High" tiers for dashboards
Aggregation
Use GROUP BY on the derived category to count or average per bucket
Clarity
Replace cryptic codes (1, 2, 3) with human-readable labels

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.

score 95 82 67 45 CASE WHEN grade A B D F Raw values → Derived categories

The Syntax Blueprint

CASE WHEN condition_1 THEN 'label_1' WHEN condition_2 THEN 'label_2' WHEN condition_3 THEN 'label_3' ELSE 'default_label' END AS category_name

How SQL Evaluates CASE

Start: read row WHEN cond_1 true? YES label_1 NO WHEN cond_2 true? YES label_2 NO → ELSE First match wins Rest skipped

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

1
Identify the source column. Which column holds the raw values you want to categorize?
2
Define your buckets. What labels do you need? Write them out before coding.
3
Set boundary conditions. Order conditions from most specific to least specific (top to bottom).
4
Add an ELSE clause. Always handle the "everything else" case to avoid NULLs.
5
Alias the result. Use AS category_name so your output column has a clear name.

Example 1: Grade Buckets

Assign letter grades from a students table with a score column:

SELECT name, score, CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' WHEN score >= 70 THEN 'C' WHEN score >= 60 THEN 'D' ELSE 'F' END AS grade FROM students;

Example 2: Revenue Tiers

Classify orders by total_amount into revenue tiers:

SELECT order_id, total_amount, CASE WHEN total_amount >= 1000 THEN 'High' WHEN total_amount >= 250 THEN 'Medium' ELSE 'Low' END AS revenue_tier FROM orders;

Example 3: CASE + GROUP BY

Count employees by experience category from an employees table:

SELECT CASE WHEN years_exp >= 10 THEN 'Senior' WHEN years_exp >= 3 THEN 'Mid-Level' ELSE 'Junior' END AS exp_level, COUNT(*) AS num_employees FROM employees GROUP BY exp_level;

Visualizing the Output

exp_level num_employees Senior 12 Mid-Level 35 Junior 18 Each row represents a derived category with its aggregate

Advanced: Multi-Column Conditions

CASE WHEN conditions can reference multiple columns and use AND/OR logic:

SELECT product, price, stock, 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 inventory_status FROM products;

Common Mistakes

✕ Wrong condition order
Putting broad conditions before specific ones causes specific labels to never trigger. Always go most specific first.
✕ Missing ELSE
Without ELSE, unmatched rows return NULL instead of a meaningful default category.
✕ Forgetting END
Every CASE must close with END. Omitting it causes a syntax error that can be hard to spot in long queries.

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

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

What status does this product receive?