Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 31/ 160
02. SQL & Data Engineering Basics

CASE WHEN & Conditional Logic

Branch logic in SELECT/aggregations to bucket, flag, and reshape business rules.

BeginnerCASE WHEN · Bucketing3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Age bands with an unknown bucket

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.

Key takeaway: Order branches deliberately, handle NULL explicitly, always write ELSE.

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.

Rates per segment in one query

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.

Key takeaway: CASE inside aggregates builds segment metrics; avoid COUNT with ELSE 0.

How it works, step by step

Step 1 of 4
Design

1. Write the rules in priority order

List conditions in the order they should win and decide where NULL goes.

NULL → 'unknown' · tenure < 3 → 'new' · …
Key numbers at this step
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

CASE WHEN in SQL
Best for: Rules evaluated in the warehouse

Strengths: Runs where the data is; works in aggregates.

Watch out: Long CASEs get hard to maintain.

Lookup table + join
Best for: Many value mappings

Strengths: Maintainable; reusable.

Watch out: Needs a table and a join.

np.select / pd.cut in pandas
Best for: Exploration and ML preprocessing in Python

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?
Interview tip: Show a customer matching two rules and explain which wins and why. It demonstrates you understand first-match semantics.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply CASE WHEN & Conditional Logic with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
LAG & LEAD Analytical Functions
Next topic
Date/Time & String Functions in SQL