Conditional Logic with CASE WHEN ... THEN ... ELSE ... END
Branch inside SELECT and aggregates using searched and simple CASE expressions.
In plain words
CASE checks rules from top to bottom and gives back the answer for the first rule that fits.
Think of it like…
A sorting machine at a post office: each parcel goes down the first chute whose rule it matches (heavy, international, fragile…), and anything that matches no rule goes to the default bin, or nowhere if there isn't one.
Where you’ve seen it
A monthly report with paid and refunded revenue side by side: SELECT date_trunc('month', created_at) AS month, SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid, SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunded FROM orders GROUP BY 1;
Words you’ll hear
- Searched CASE
- CASE WHEN condition THEN value …: each WHEN is a full condition.
- Simple CASE
- CASE expr WHEN value THEN …: compares expr for equality.
- ELSE
- The value when no WHEN matches. If it's missing, the result is NULL.
- Conditional aggregation
- SUM or COUNT over a CASE to compute several filtered metrics in one query.
Visual diagram
Theory & example queries
Searched vs simple CASE
A searched CASE evaluates each WHEN condition in order and returns the first matching THEN. Because it stops at the first match, overlapping ranges must be written from most specific to least: >= 1000 before >= 100.
A simple CASE compares one expression for equality: CASE status WHEN 'P' THEN 'Paid' WHEN 'R' THEN 'Refunded' ELSE 'Other' END. It can't test NULL, because status = NULL is never true; write CASE WHEN status IS NULL THEN … instead.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT id, CASE WHEN amount >= 1000 THEN 'large' WHEN amount >= 100 THEN 'medium' ELSE 'small' END AS sizeFROM orders;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| id | size |
|---|---|
| 101 | small |
| 102 | medium |
| 103 | large |
| 104 | medium |
Note: Representative classification for sample amounts of 49, 180, 1,250 and 600.
Key takeaway: The first true WHEN wins; a missing ELSE means NULL.
CASE inside aggregates
Wrapping CASE in an aggregate computes a filtered metric per group without extra queries or joins. SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) adds only paid amounts; COUNT(CASE WHEN status = 'paid' THEN 1 END) counts only paid rows, because the missing ELSE makes other rows NULL and COUNT skips NULLs.
PostgreSQL also supports the FILTER clause, COUNT(*) FILTER (WHERE status = 'paid'), which reads more clearly. CASE also works in ORDER BY for custom sort orders, but avoid it in WHERE on indexed columns, because wrapping a column in CASE prevents the index from being used.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT date_trunc('month', created_at) AS MONTH, COUNT( CASE WHEN status = 'paid' THEN 1 END ) AS paid, COUNT( CASE WHEN status = 'refunded' THEN 1 END ) AS refundedFROM ordersGROUP BY 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| month | paid | refunded |
|---|---|---|
| 2026-09-01 | 412 | 18 |
| 2026-10-01 | 487 | 24 |
| 2026-11-01 | 193 | 7 |
Note: Illustrative monthly counts; timestamp rendering differs by client and session time zone.
Key takeaway: SUM/COUNT over CASE gives several conditional metrics in one scan.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
List the rules
Write the conditions and their results in plain words first, and decide what should happen when nothing matches.
≥ 1000 → large · ≥ 100 → medium · else small
When to use it & trade-offs
What it is
CASE is SQL's if/else expression. A *searched* CASE (CASE WHEN amount > 1000 THEN 'large' … END) tests conditions in order and returns the value of the first one that's true. A *simple* CASE (CASE status WHEN 'P' THEN 'Paid' … END) compares one expression with a list of values. Without ELSE, unmatched rows get NULL.
Why it matters: CASE turns raw codes into labels, buckets numbers into ranges, and, inside aggregates, computes several conditional metrics in one pass. "Count paid and refunded orders per month in one query" is a very common interview task, and the answer is CASE inside SUM or COUNT.
When to reach for it
- Mapping codes to readable labels
- Bucketing numbers or dates into ranges
- Pivoting statuses into columns with conditional aggregation
When to avoid or be careful
- Overlapping conditions in the wrong order
- Simple CASE to test for NULL
- CASE around an indexed column in WHERE, which prevents index use
CASE vs FILTER vs separate queries
Strengths: Works in every SQL database, one scan of the table.
Watch out: Gets verbose with many metrics.
Strengths: Shorter and clearer than CASE.
Watch out: Not supported in MySQL or SQL Server.
Strengths: Each part is simple on its own.
Watch out: Several scans and joins for something one query can do.
Interview signals & numbers to know
When this topic comes up
- “Count paid and refunded orders in one query”
- “Categorise values into buckets”
- Pivot rows into columns
- Custom sort order
- if/else in SQL
Benchmarks & rules of thumb
- 1st true WHEN
- decides the result
- NULL
- result when nothing matches and there's no ELSE
- 1
- table scan for many conditional metrics
Common mistakes & follow-ups
Common interview mistakes
- Putting
WHEN amount >= 100beforeWHEN amount >= 1000, so nothing is ever labelled large. - Writing
CASE col WHEN NULL THEN …, which never matches. - Using
COUNT(CASE WHEN … THEN 1 ELSE 0 END), which counts every row because 0 isn't NULL. Use SUM, or drop the ELSE.
Likely interviewer follow-ups
- How would you show paid, pending and refunded order counts per month as three columns?
- What does CASE return when no condition matches and there's no ELSE?
- Why is COUNT(CASE WHEN x THEN 1 ELSE 0 END) wrong?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Conditional Logic with CASE WHEN ... THEN ... ELSE ... END with hands-on SQL practice and interview Q&A.