# Topic 18: CASE WHEN Statements
Conditional branching logic, simple vs searched CASE expressions, conditional aggregations, and pivoting.
1. Definition
CASE WHEN is a conditional expression in SQL that evaluates a series of conditions and returns a value when the first true condition is met, functioning like an IF-THEN-ELSE block.
2. Explain Like I'm 5
CASE WHEN is a sorting hat: if you are brave, you go to Gryffindor; else if you are smart, you go to Ravenclaw; otherwise, you go to Hufflepuff.
3. Animation & Visual Simulation
Interactive Engine TraceCASE WHEN Statements Visual Simulator
SELECT id, status,
CASE status
WHEN 'paid' THEN 'Invoice Settled'
WHEN 'pending' THEN 'Action Required'
ELSE 'Unknown State'
END AS display_status
FROM invoices;Active InputStep 1: Input & Parsing Stage
Initiating CASE WHEN Statements
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
Categorizing customer orders into tiered loyalty categories based on lifetime spend.
| name | lifetime_spend | tier |
|---|---|---|
| Alice | $12,000 | Platinum |
| Bob | $3,500 | Gold |
| Charlie | $200 | Standard |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectSELECT name, lifetime_spend,
CASE
WHEN lifetime_spend >= 10000 THEN 'Platinum'
WHEN lifetime_spend >= 2500 THEN 'Gold'
WHEN lifetime_spend >= 500 THEN 'Silver'
ELSE 'Standard'
END AS customer_tier
FROM customers;SELECT department, COUNT(*) AS total_employees, SUM(CASE WHEN salary > 100000 THEN 1 ELSE 0 END) AS high_earners FROM employees GROUP BY department;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Sequential Evaluation | CASE stops evaluating as soon as the first condition evaluates to TRUE. |
| ELSE Default | If no WHEN matches and no ELSE clause is provided, the CASE expression returns NULL. |
| Uniform Return Types | All return expressions across all WHEN and ELSE branches must share compatible data types. |
| Short-circuit branch evaluation | CASE evaluates conditions sequentially; the first branch that evaluates to TRUE returns immediately. |
| Data type consistency across branches | All THEN and ELSE result expressions must coerce to a single compatible data type. |
7. Deep Dive: Conditional Aggregations vs FILTER Clause
SUM(CASE WHEN ...) is the standard ANSI technique for conditional aggregation. PostgreSQL also supports the modern FILTER (WHERE ...) clause, which is even cleaner and easier to read.
-- Standard SQL (Universal): SELECT SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) FROM orders; -- Modern PostgreSQL FILTER syntax: SELECT SUM(amount) FILTER (WHERE status = 'completed') FROM orders;
8. Advantages & Disadvantages
Advantages
- •Brings procedural if-else branching logic cleanly into declarative SQL.
- •Powers complex multi-metric reporting in a single table scan.
Disadvantages & Trade-offs
- •Deeply nested CASE statements can harm query readability.
9. Common Interview Questions
Q1.What is the difference between a Simple CASE expression and a Searched CASE expression?
A Simple CASE compares a single base expression against values using equality: CASE status WHEN 1 THEN 'active' WHEN 2 THEN 'paused' END. A Searched CASE evaluates arbitrary boolean expressions in each branch: CASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' END. Searched CASE is vastly more flexible.
Q2.How do you use conditional aggregation (CASE inside SUM/COUNT) to pivot rows into columns?
Conditional aggregation wraps CASE WHEN inside aggregate functions. It allows transforming long-format category rows into wide-format reporting columns in a single table pass without dynamic SQL or extension modules.
SELECT
department_id,
COUNT(*) AS total_employees,
COUNT(CASE WHEN gender = 'F' THEN 1 END) AS female_count,
COUNT(CASE WHEN gender = 'M' THEN 1 END) AS male_count,
SUM(CASE WHEN status = 'active' THEN salary ELSE 0 END) AS active_payroll
FROM employees
GROUP BY department_id;Q3.What happens if no WHEN condition matches and there is no ELSE clause in CASE?
If no WHEN condition evaluates to TRUE and an ELSE clause is omitted, the CASE expression evaluates to NULL by default. It never throws an exception. In production, always supply an explicit ELSE clause to prevent silent NULL injection into mathematical formulas.
Q4.Can a CASE expression be used to safely guard against division by zero?
Yes. Because CASE WHEN evaluates branches sequentially and short-circuits upon the first match, placing the zero-check in the first WHEN condition guarantees safety: SELECT CASE WHEN count = 0 THEN 0 ELSE total / count END FROM metrics; The engine will never evaluate the ELSE branch when count = 0.
Q5.Can you create an index on a CASE expression in PostgreSQL?
Yes. PostgreSQL supports expression indexes. You can index the result of a deterministic CASE expression: CREATE INDEX idx_users_vip ON users ((CASE WHEN total_spent > 10000 THEN 1 ELSE 0 END)); Queries filtering on that exact CASE expression will use the index seek.
10. Interview-Ready Answer
“CASE WHEN provides conditional branching in SQL. Beyond labeling rows, its most powerful production application is conditional aggregation, allowing developers to calculate multiple metrics across categories in a single query pass.”
11. Quick Test
What does a CASE expression return if no WHEN condition evaluates to TRUE and no ELSE clause is defined?