The SQL CASE Expression
CASE is SQL's if/else. It checks WHEN tests from the top, returns the THEN value of the first one that is true, and skips the rest. If none is true, you get the ELSE value, or NULL when there is no ELSE.
SELECT name, spend,
CASE
WHEN spend IS NULL THEN 'unknown'
WHEN spend >= 1000 THEN 'high'
WHEN spend >= 300 THEN 'mid'
ELSE 'low'
END AS band
FROM customers;Run this once in an empty practice database. The code on this page uses these two tables. Day counts are as of August 23, 2026.
CREATE TABLE customers (
name VARCHAR(10), spend INT, region VARCHAR(5),
days_since_signup INT, days_since_order INT
);
INSERT INTO customers VALUES
('Alvarez',1400,'East',9,3),
('Brennan',1250,'West',566,5),
('Cho',90,'East',14,14),
('Diaz',620,'West',276,174),
('Ellis',2100,'East',813,193),
('Fowler',310,NULL,22,7),
('Grant',180,'West',343,115),
('Hale',1050,'East',3,2),
('Iyer',460,'West',475,11),
('Jansen',NULL,'East',412,220);
CREATE TABLE credits (performer VARCHAR(50));
INSERT INTO credits VALUES
('2 Chainz Featuring Drake'),
('Elvis Presley With The Jordanaires'),
('2Pac Duet With Mopreme'),
('Patti Austin A Duet With James Ingram');The steps
How CASE decidesThe first true WHEN wins
Each row goes down the list. The first test that is true gives the value. This form is called a searched CASE.
SELECT name, spend,
CASE
WHEN spend >= 1000 THEN 'high'
WHEN spend >= 300 THEN 'mid'
ELSE 'low'
END AS band
FROM customers
ORDER BY name;| name | spend | band |
|---|---|---|
| Alvarez | 1400 | high |
| Brennan | 1250 | high |
| Cho | 90 | low |
| Diaz | 620 | mid |
| … | … | … |
| Jansen | NULL | low |
Alvarez's 1400 also passes spend >= 300, but that test is never checked. Jansen has no spend, fails both tests and lands in ELSE. Step 4 fixes that.
Remove the ELSE and every row that matches nothing gets NULL:
SELECT name, spend,
CASE WHEN spend >= 1000 THEN 'high' END AS band
FROM customers
ORDER BY name;Four rows say high. The other six are NULL.
A row matches no WHEN and the CASE has no ELSE. What does it return?
Order is logicSpecific tests above general ones
Because the first match wins, a general test placed first can hide a specific one. Which label never appears here?
SELECT band, COUNT(*) AS customers
FROM (
SELECT CASE
WHEN spend >= 100 THEN 'over 100'
WHEN spend >= 500 THEN 'over 500'
ELSE 'small'
END AS band
FROM customers
) b
GROUP BY band
ORDER BY band;| band | customers |
|---|---|
| over 100 | 8 |
| small | 2 |
over 500 never appears. Everyone over 500 is also over 100, so the first test takes them all. The query runs with no error. The fix is to put spend >= 500 first.
A cleaning example
The credits table holds chart credits. The goal is the main artist: the text before a joining word such as "Featuring" or "With". A first try:
SELECT performer,
CASE
WHEN INSTR(performer, ' Featuring ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' Featuring ') - 1)
WHEN INSTR(performer, ' With ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' With ') - 1)
ELSE performer
END AS primary_artist
FROM credits;INSTR finds where text starts. SUBSTR keeps everything before it. Two results are wrong:
| performer | primary_artist |
|---|---|
| 2Pac Duet With Mopreme | 2Pac Duet |
| Patti Austin A Duet With James Ingram | Patti Austin A Duet |
" With " also matches inside " Duet With " and " A Duet With ". Add the longer joiners above it, most specific first:
SELECT performer,
CASE
WHEN INSTR(performer, ' A Duet With ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' A Duet With ') - 1)
WHEN INSTR(performer, ' Duet With ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' Duet With ') - 1)
WHEN INSTR(performer, ' Featuring ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' Featuring ') - 1)
WHEN INSTR(performer, ' With ') > 0
THEN SUBSTR(performer, 1, INSTR(performer, ' With ') - 1)
ELSE performer
END AS primary_artist
FROM credits;| performer | primary_artist |
|---|---|
| 2 Chainz Featuring Drake | 2 Chainz |
| Elvis Presley With The Jordanaires | Elvis Presley |
| 2Pac Duet With Mopreme | 2Pac |
| Patti Austin A Duet With James Ingram | Patti Austin |
INSTR works in SQLite, MySQL, DuckDB and Oracle. In PostgreSQL, write STRPOS in its place (tested). SQL Server uses CHARINDEX and SUBSTRING (docs only).Two tests can both match a row. Where does the more specific one go?
The short formOne column, equality only
When every test compares the same column to a value, put the column after CASE. This is called a simple CASE.
SELECT name, region,
CASE region
WHEN 'East' THEN 'Team A'
WHEN 'West' THEN 'Team B'
ELSE 'Unassigned'
END AS team
FROM customers
ORDER BY name;It means the same as WHEN region = 'East' on each line. Fowler has no region, so Fowler gets Unassigned.
The short form only checks equality. For >, LIKE, IS NULL or two columns, use the searched form from step 1.
You need spend >= 1000 in a test. Which form works?
The NULL trapWHEN col = NULL never fires
Jansen has no spend. Compare the two tests:
SELECT name,
CASE WHEN spend = NULL THEN 'missing' ELSE 'has spend' END AS wrong,
CASE WHEN spend IS NULL THEN 'missing' ELSE 'has spend' END AS right_way
FROM customers
WHERE name IN ('Iyer', 'Jansen')
ORDER BY name;| name | wrong | right_way |
|---|---|---|
| Iyer | has spend | has spend |
| Jansen | has spend | missing |
spend = NULL is unknown, not true, so the test never fires. The short form has the same problem: CASE spend WHEN NULL is an equality test too. NULL in SQL explains why.
Make the NULL test the first line, with its own label:
SELECT name, spend,
CASE
WHEN spend IS NULL THEN 'unknown'
WHEN spend >= 1000 THEN 'high'
WHEN spend >= 300 THEN 'mid'
ELSE 'low'
END AS band
FROM customers
WHERE name IN ('Cho', 'Jansen')
ORDER BY name;| name | spend | band |
|---|---|---|
| Cho | 90 | low |
| Jansen | NULL | unknown |
Before, Jansen read as a low spender. Now the report says the spend is unknown.
Which test catches a missing spend?
Where CASE can goSELECT, ORDER BY, GROUP BY, SUM
CASE returns a value, so it can go where a column can: SELECT, WHERE, ORDER BY, GROUP BY, inside SUM or COUNT, and in UPDATE … SET.
Sort in a business order
SELECT name, region
FROM customers
ORDER BY CASE region
WHEN 'West' THEN 1
WHEN 'East' THEN 2
ELSE 3
END,
name;The four West customers come first, then the five East, then Fowler. The numbers are only sort keys.
Group by a band
SELECT CASE WHEN spend >= 1000 THEN 'high' ELSE 'other' END AS band,
COUNT(*) AS customers
FROM customers
GROUP BY CASE WHEN spend >= 1000 THEN 'high' ELSE 'other' END
ORDER BY band;| band | customers |
|---|---|
| high | 4 |
| other | 6 |
Count several things in one query
SELECT COUNT(*) AS customers,
SUM(CASE WHEN region = 'East' THEN 1 ELSE 0 END) AS east,
SUM(CASE WHEN region = 'West' THEN 1 ELSE 0 END) AS west,
COUNT(CASE WHEN spend >= 1000 THEN 1 END) AS high_spend
FROM customers;| customers | east | west | high_spend |
|---|---|---|---|
| 10 | 5 | 4 | 4 |
COUNT works without ELSE because unmatched rows become NULL, and COUNT skips NULLs.
Filter on the result
WHERE band = 'high' in the same query works in SQLite and DuckDB but fails in PostgreSQL and MySQL. A CTE works in all four:
WITH banded AS (
SELECT name,
CASE WHEN spend >= 1000 THEN 'high' ELSE 'other' END AS band
FROM customers
)
SELECT name
FROM banded
WHERE band = 'high'
ORDER BY name;| name |
|---|
| Alvarez |
| Brennan |
| Ellis |
| Hale |
Why does COUNT(CASE WHEN … THEN 1 END) count only matches?
Overlapping rulesOne customer, two segments
Three segment rules: new = signed up in the last 30 days, vip = spend of 1000 or more, at risk = no order in over 90 days. Hale signed up 3 days ago and has spent 1050. Which segment does Hale get?
SELECT name, spend,
CASE
WHEN days_since_signup <= 30 THEN 'new'
WHEN spend >= 1000 THEN 'vip'
WHEN days_since_order > 90 THEN 'at risk'
ELSE 'active'
END AS segment
FROM customers
ORDER BY name;Hale is new, only because that line comes first. Hale is also a VIP. Two rules that can both be true for one row are called overlapping.
Move one line, change the report
Put the VIP line first and rerun. Alvarez and Hale move from new to vip:
| segment | new first | vip first |
|---|---|---|
| new | 4 | 2 |
| vip | 2 | 4 |
| at risk | 3 | 3 |
| active | 1 | 1 |
| Total | 10 | 10 |
The total is 10 both times, so a total check won't catch it. Only the split moves.
Use one flag per rule
Ellis has spent 2100 and last ordered 193 days ago. In both orders Ellis is labeled vip, so the report never shows that Ellis is also at risk. Flags keep every fact:
SELECT name,
CASE WHEN days_since_signup <= 30 THEN 1 ELSE 0 END AS is_new,
CASE WHEN spend >= 1000 THEN 1 ELSE 0 END AS is_vip,
CASE WHEN days_since_order > 90 THEN 1 ELSE 0 END AS is_at_risk
FROM customers
ORDER BY name;| name | is_new | is_vip | is_at_risk |
|---|---|---|---|
| Alvarez | 1 | 1 | 0 |
| Brennan | 0 | 1 | 0 |
| Cho | 1 | 0 | 0 |
| Diaz | 0 | 0 | 1 |
| Ellis | 0 | 1 | 1 |
| Fowler | 1 | 0 | 0 |
| Grant | 0 | 0 | 1 |
| Hale | 1 | 1 | 0 |
| Iyer | 0 | 0 | 0 |
| Jansen | 0 | 0 | 1 |
Three rows have two 1s: Alvarez, Ellis and Hale. Those are the rows where the line order decided the label. Count them:
SELECT COUNT(*) AS overlaps
FROM (
SELECT CASE WHEN days_since_signup <= 30 THEN 1 ELSE 0 END
+ CASE WHEN spend >= 1000 THEN 1 ELSE 0 END
+ CASE WHEN days_since_order > 90 THEN 1 ELSE 0 END AS rules_met
FROM customers
) f
WHERE rules_met > 1;| overlaps |
|---|
| 3 |
If the count is above 0, the line order is a business decision. Agree it with whoever owns the numbers, then write it down above the CASE:
-- Priority is on purpose: a customer who is both
-- new and VIP counts as new for their first 30 days.
-- (Example note: who agreed it, and when.)The comment format is in commenting SQL so it teaches.
You swap two overlapping WHEN lines. What can change?
Test any CASEThree checks and edge cases
- Count rows per label. A label with 0 rows is either a rule nobody meets or a line an earlier test makes unreachable (step 2).
- Count overlaps with flags. Above 0 means line order decides results (step 6).
- Preview input next to output. Read the original value beside the
CASEresult before you build on it. That is how the "2Pac Duet" error showed up.
Edge cases
Bands with BETWEEN share an edge. BETWEEN 0 AND 10 and BETWEEN 10 AND 20 both include 10, so 10 goes to whichever line comes first. Use one open end per band:
SELECT name, spend,
CASE
WHEN spend IS NULL THEN 'unknown'
WHEN spend < 500 THEN 'small'
WHEN spend < 1000 THEN 'mid'
ELSE 'large'
END AS band
FROM customers
ORDER BY spend;Four customers are small, one is mid, four are large and Jansen is unknown. Where Jansen sorts depends on the database.
Write the ELSE. Without it, unmatched rows become NULL and show up as a blank group. Something readable, such as ELSE 'unclassified', is easier to spot.
CASE can't skip an aggregate. PostgreSQL and SQL Server work out SUM, MIN and similar inside a CASE before the WHEN tests. A division by zero inside one can still fail (tested in PostgreSQL; SQL Server per Microsoft docs). To avoid dividing by zero, use total / NULLIF(n, 0), which gives NULL instead.
Thresholds in many queries. If several queries share the same bands, keep the cutoffs in a small table and join to it, so a change happens in one place.
A label in your CASE has 0 rows. What should you check first?
Cheat sheetOne table
| Task | Do this |
|---|---|
| Different tests per line | CASE WHEN … THEN … |
| One column, equal values | CASE col WHEN 'a' THEN … |
| Two tests can match | Specific line first |
| Catch missing values | WHEN col IS NULL, first |
| Never | WHEN col = NULL |
| No ELSE | Unmatched rows are NULL |
| Business sort order | ORDER BY CASE … |
| Count matches | COUNT(CASE …), no ELSE |
| Filter on the result | Use a CTE |
| Rules overlap | One flag per rule |
| Divide safely | x / NULLIF(n, 0) |
Try this next
Open a CASE you use often. Count rows per label, then build one flag per rule and count the rows with more than one flag.
SQL Kit
Practice SELECT, WHERE, JOIN and GROUP BY in your browser. Nothing to install.
SQL for Analysts
Reads queries line by line in plain words.
Related guidesSegments, NULLs and SQL basics
- Analyst Prep Kit
- SQL Foundations
- GROUP BY and HAVING
- SQL CTEs
- Window Functions
- Tableau Relationships
- Tableau Sets
- SQL Drill
- What Is Data Analysis?
- How to Comment in SQL
- Commenting SQL
- Set Up a SQL Database
- Which Database to Install
- Handle Large Datasets
- Git for Analysts
- SQL + Python
- Exploratory Data Analysis
- Documenting Limitations
- Data-Driven Thresholds
- Defining Metrics
- Entity Resolution
- Technical Tenacity
- SQL JOINs
- COUNT in SQL
- SQL Aliases
- SQL Kit
- Portfolio Projects
- All guides
Version 2.0