Prep Kit
Guide · SQL basics

The SQL CASE Expression

By , implementation analyst · Updated

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.

Quick answer
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;

Uses the practice table below. Put the NULL test first and the most specific tests above the general ones.

Practice tables

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');

Runs in SQLite, PostgreSQL, MySQL and DuckDB. No database yet? Set one up.

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;
namespendband
Alvarez1400high
Brennan1250high
Cho90low
Diaz620mid
………
JansenNULLlow

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.

Quick check

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;
bandcustomers
over 1008
small2

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:

performerprimary_artist
2Pac Duet With Mopreme2Pac Duet
Patti Austin A Duet With James IngramPatti 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;
performerprimary_artist
2 Chainz Featuring Drake2 Chainz
Elvis Presley With The JordanairesElvis Presley
2Pac Duet With Mopreme2Pac
Patti Austin A Duet With James IngramPatti 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).
Quick check

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.

Quick check

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;
namewrongright_way
Iyerhas spendhas spend
Jansenhas spendmissing

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;
namespendband
Cho90low
JansenNULLunknown

Before, Jansen read as a low spender. Now the report says the spend is unknown.

Quick check

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;
bandcustomers
high4
other6

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;
customerseastwesthigh_spend
10544

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
Quick check

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:

segmentnew firstvip first
new42
vip24
at risk33
active11
Total1010

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;
nameis_newis_vipis_at_risk
Alvarez110
Brennan010
Cho100
Diaz001
Ellis011
Fowler100
Grant001
Hale110
Iyer000
Jansen001

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.

Quick check

You swap two overlapping WHEN lines. What can change?

Test any CASEThree checks and edge cases
  1. 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).
  2. Count overlaps with flags. Above 0 means line order decides results (step 6).
  3. Preview input next to output. Read the original value beside the CASE result 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.

Quick check

A label in your CASE has 0 rows. What should you check first?

Cheat sheetOne table
TaskDo this
Different tests per lineCASE WHEN … THEN …
One column, equal valuesCASE col WHEN 'a' THEN …
Two tests can matchSpecific line first
Catch missing valuesWHEN col IS NULL, first
NeverWHEN col = NULL
No ELSEUnmatched rows are NULL
Business sort orderORDER BY CASE …
Count matchesCOUNT(CASE …), no ELSE
Filter on the resultUse a CTE
Rules overlapOne flag per rule
Divide safelyx / 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.

Practice

SQL Kit

Practice SELECT, WHERE, JOIN and GROUP BY in your browser. Nothing to install.

Open the SQL Kit · SQL Drill

Free guide

SQL for Analysts

Reads queries line by line in plain words.

Download the free guide · Free SQL bundle

Related guidesSegments, NULLs and SQL basics