Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

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
SQL topics
Lesson 25/ 160
02. Aggregations, Functions & Data Manipulation

Conditional Logic with CASE WHEN ... THEN ... ELSE ... END

Branch inside SELECT and aggregates using searched and simple CASE expressions.

BeginnerCASE · WHEN · ELSE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

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

Bucketing order sizesQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  CASE4    WHEN amount >= 1000 THEN 'large'5    WHEN amount >= 100 THEN 'medium'6    ELSE 'small'7  END AS size8FROM9  orders;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
idsize
101small
102medium
103large
104medium

Note: Representative classification for sample amounts of 49, 180, 1,250 and 600.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Paid vs refunded counts per monthQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  date_trunc('month', created_at) AS MONTH,3  COUNT(4    CASE5      WHEN status = 'paid' THEN 16    END7  ) AS paid,8  COUNT(9    CASE10      WHEN status = 'refunded' THEN 111    END12  ) AS refunded13FROM14  orders15GROUP BY16  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
monthpaidrefunded
2026-09-0141218
2026-10-0148724
2026-11-011937

Note: Illustrative monthly counts; timestamp rendering differs by client and session time zone.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: SUM/COUNT over CASE gives several conditional metrics in one scan.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Logic

List the rules

Write the conditions and their results in plain words first, and decide what should happen when nothing matches.

Focus at this step

≥ 1000 → large · ≥ 100 → medium · else small

What to watch at this step
Decide
the ELSE value
Tip: use ← → to move between steps

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

CASE inside SUM / COUNT
Best for: Several conditional metrics in one portable query

Strengths: Works in every SQL database, one scan of the table.

Watch out: Gets verbose with many metrics.

Aggregate FILTER (WHERE …)
Best for: The same thing in PostgreSQL, SQLite and DuckDB

Strengths: Shorter and clearer than CASE.

Watch out: Not supported in MySQL or SQL Server.

Separate queries joined together
Best for: Metrics that come from different tables

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 >= 100 before WHEN 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?
Interview tip: For pivot-style questions, write one SUM(CASE…) column and say "the rest follow the same pattern". It shows you know the technique without spending time on repetition.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Filtering Groups with HAVING (WHERE vs HAVING)
Next topic
Pivoting Data Using Conditional Aggregation (SUM(CASE WHEN ...))