CASE WHEN & Conditional Logic
Branch logic in SELECT/aggregations to bucket, flag, and reshape business rules.
In plain words
CASE WHEN checks conditions one after another and gives the answer for the first one that is true.
Think of it like…
A sorting machine with gates in a fixed order: the first gate whose rule fits lets the item through, and anything that fits none lands in the "other" bin, so the order of the gates decides where overlapping items go.
Where you’ve seen it
A risk team buckets customers by tenure and spend: CASE WHEN tenure_months < 3 THEN 'new' WHEN spend_90d >= 50000 THEN 'high_value' WHEN spend_90d = 0 THEN 'dormant' ELSE 'regular' END. A customer with 2 months' tenure and ₹80,000 spend is 'new', because the tenure rule is first; swapping the order would label them 'high_value'. The team documents the priority order and adds test rows for each boundary (tenure = 3, spend = 50,000, spend NULL).
Words you’ll hear
- Searched CASE
- CASE WHEN condition …: each branch has its own boolean test.
- Simple CASE
- CASE column WHEN value THEN …: compares one expression with values.
- First match wins
- Evaluation stops at the first true condition, so order sets priority.
- Conditional aggregation
- Aggregates of CASE expressions that compute segment metrics in one GROUP BY.
Visual diagram
Theory & deep dive
Bucketing, flags and cleaning
Bucket continuous values with ranges in ascending order, relying on first-match so you only write the lower bound: CASE WHEN age < 25 THEN '18-24' WHEN age < 35 THEN '25-34' WHEN age < 50 THEN '35-49' ELSE '50+' END. Decide explicitly what happens to NULL: it matches no comparison and falls to ELSE, so add WHEN age IS NULL THEN 'unknown' first. Flags are CASE WHEN … THEN 1 ELSE 0 END (or just the boolean expression cast to int in some dialects), useful as model features and for counting.
For cleaning, map variants to canonical values: CASE WHEN lower(trim(status)) IN ('canceled', 'cancelled') THEN 'cancelled' ELSE lower(trim(status)) END. Put one-off mappings in a small lookup table when there are many, joined instead of a 60-line CASE. Keep return types consistent (all strings or all numbers); mixing types causes errors or silent casts.
CASE WHEN age IS NULL THEN 'unknown' WHEN age < 25 THEN '18-24' WHEN age < 35 THEN '25-34' WHEN age < 50 THEN '35-49' ELSE '50+' END AS age_band. In pandas: pd.cut(df.age, [0, 25, 35, 50, 200], right=False, labels=[...]) plus a fill for NaN.
Conditional aggregation and pandas equivalents
Put CASE inside an aggregate to compute segment metrics side by side: SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue, COUNT(DISTINCT CASE WHEN channel = 'email' THEN customer_id END) AS email_customers. For counting rows that meet a condition, use COUNT(CASE WHEN cond THEN 1 END) (no ELSE, so non-matching rows are NULL and not counted) or SUM(CASE WHEN cond THEN 1 ELSE 0 END). The bug to avoid is COUNT(CASE WHEN cond THEN 1 ELSE 0 END), which counts every row because 0 is not NULL. PostgreSQL and SQLite also offer COUNT(*) FILTER (WHERE cond).
A pivot-style summary is just conditional aggregation: one column per category (SUM(CASE WHEN month = 1 THEN amount END) AS jan, …). In pandas use pivot_table, np.where(cond, a, b) for two outcomes, np.select([c1, c2], [v1, v2], default=v3) for several (first match wins, like CASE) and Series.map for lookups. Test boundary values on a small DataFrame or a VALUES list so you know exactly where each band starts and ends.
SELECT channel, COUNT(*) AS orders, SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END)::float / COUNT(*) AS refund_rate FROM orders GROUP BY channel; The numerator uses SUM with ELSE 0, which is correct; the COUNT(…ELSE 0…) version would not be.
How it works, step by step
Step 1 of 41. Write the rules in priority order
List conditions in the order they should win and decide where NULL goes.
- Priority
- documented
When to use it & trade-offs
What it is
CASE WHEN condition THEN value … ELSE default END is SQL's if/elif/else. Conditions are checked top to bottom and the first true one wins, so order matters. In data science it does four jobs: bucketing a number into bands (CASE WHEN age < 25 THEN '18-24' …), creating flags (CASE WHEN refund_count > 0 THEN 1 ELSE 0 END), cleaning inconsistent labels, and conditional aggregation (SUM(CASE WHEN channel = 'paid' THEN 1 ELSE 0 END)) that computes many segment metrics in one pass. The pandas counterparts are np.where, np.select and pd.cut.
Why it matters: Feature engineering and reporting are full of business rules that become CASE expressions. Silent errors come from the order of branches, NULLs falling through to ELSE, and the COUNT(CASE … ELSE 0 END) bug that counts every row. A clear convention (explicit ELSE, NULL handling and unit tests on edge values) keeps derived columns trustworthy.
When to reach for it
- Segment and band definitions
- Binary flags for models
- Rates and pivots through conditional aggregation
When to avoid or be careful
- COUNT(CASE … ELSE 0 END)
- Overlapping branches whose order you haven't thought about
- Mixed return types across branches
Ways to derive categories
Strengths: Runs where the data is; works in aggregates.
Watch out: Long CASEs get hard to maintain.
Strengths: Maintainable; reusable.
Watch out: Needs a table and a join.
Strengths: Flexible; easy to unit test.
Watch out: Requires the data in memory.
Interview signals & numbers to know
When this topic comes up
- “Bucket customers by tenure and spend”
- “Compute conversion by channel in one query”
- “Why is the count equal to all rows?”
- Pivot-style summaries
- Feature flags
Benchmarks & rules of thumb
- first match
- wins in CASE
- NULL
- result with no matching branch and no ELSE
- 0
- is not NULL, so COUNT counts it
Common mistakes & follow-ups
Common interview mistakes
- Putting a broad condition first so more specific branches never run.
- Forgetting NULL handling so missing ages land in the '50+' bucket.
- Counting with
COUNT(CASE WHEN … THEN 1 ELSE 0 END)and getting the total row count.
Likely interviewer follow-ups
- How does CASE evaluate conditions?
- How would you compute refund rate by channel in one query?
- How is np.select related to CASE WHEN?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply CASE WHEN & Conditional Logic with data science interview Q&A and hands-on practice.