CASE — SQL's If/Then for Labels & Buckets
Label every row with CASE, put the tests in the right order and always write the ELSE. Then use CASE inside SUM to count shipped, cancelled and open orders side by side, and work out what percentage of orders were cancelled.
This article is part of the Learn SQL hands-on course series.
Prerequisite — this is a hands-on lesson. Reading it is not enough. Run every query yourself in CloudBeaver, against the Northwind Company sample database on PostgreSQL — and solve the koans yourself on DuckDB, the same Northwind Company data.
Not set up yet? It only takes a couple of minutes:
A label for every order
Your invoicing question is still open, Leo — we'll get there. First, a job from the shipping team: they want every order labelled light, medium or heavy — freight under 25 is light, under 60 is medium, anything more is heavy. How would you do this?
In the last series I'd have run three queries, one WHERE per band, and put the answers together by hand. And even then I'd have three counts — not a label on each order.
CASE is SQL's if-then. It checks each WHEN from the top: under 25 is light, under 60 is medium, and ELSE catches everything left over. One new column, worked out row by row.
SELECT "OrderID", "Freight",
CASE
WHEN "Freight" < 25 THEN 'light'
WHEN "Freight" < 60 THEN 'medium'
ELSE 'heavy'
END AS "Band"
FROM "Orders"
ORDER BY "OrderID"
LIMIT 6;So it's an expression, like the ones from the aliases lesson — it just chooses its value instead of calculating it.
Order 1 is on 38.4 — so it's medium, because it isn't under 25.
one order, one question at a time
| Test | Gives | |
|---|---|---|
WHEN | "Freight" < 25 | 'light' |
WHEN | "Freight" < 60 | 'medium' |
ELSE | 'heavy' |
The first yes wins. Everything under it is never even asked.
Right — and look how it got there. The first WHEN asked "under 25?" — no. The second asked "under 60?" — yes, so CASE stopped and answered medium. Order 5 stopped at the very first one, and order 2, on 114.85, fell through both to the ELSE.
So it reads top to bottom and takes the first yes.
Now you want only the heavy ones — so you reach for the label you just made. And CloudBeaver refuses it.
SELECT "OrderID",
CASE
WHEN "Freight" > 50 THEN 'heavy'
END AS "Label"
FROM "Orders"
WHERE "Label" = 'heavy';SQL Error [42703]: ERROR: column "Label" does not exist
Position: 115But the label is right there — I just wrote it. Why won't the WHERE see it?
Because of the running order from the aliases lesson. The database reads FROM and WHERE before it has run the SELECT — so at the moment the WHERE looks, "Label" does not exist yet. The name is given later, in the part that runs last.
So I build the label where the WHERE can reach it — first, in a subquery — and filter outside.
Count the bands, in the order you want
Now count them. The same CASE, and GROUP BY "Band" makes one group per label it produced — sorted by the smallest freight in each band, so light comes first.
SELECT CASE
WHEN "Freight" < 25 THEN 'light'
WHEN "Freight" < 60 THEN 'medium'
ELSE 'heavy'
END AS "Band",
count(*) AS "Orders"
FROM "Orders"
GROUP BY "Band"
ORDER BY min("Freight");Wait, Mnemo — the WHERE couldn't see my label. So how can the GROUP BY?
Good eye, Leo. GROUP BY runs before the SELECT too — PostgreSQL just lets it borrow the name, as a favour. SQL Server doesn't: there you repeat the whole CASE, or build the label in a subquery.
All 10000 orders, three bands: 2334 light, 3941 medium, 3725 heavy. That's the whole report the shipping team asked for.
One query over five years of orders, and I never wrote a band twice. I'd have spent the afternoon on that in the last series.
The shipping team wants the heaviest freight first. A plain ORDER BY "Band" won't do it — alphabetically it's heavy, light, medium, with light stuck in the middle. So write the order you want, as a CASE.
SELECT "Band", count(*) AS "Orders"
FROM (SELECT CASE
WHEN "Freight" < 25 THEN 'light'
WHEN "Freight" < 60 THEN 'medium'
ELSE 'heavy' END AS "Band"
FROM "Orders") AS t
GROUP BY "Band"
ORDER BY CASE WHEN "Band" = 'heavy' THEN 1
WHEN "Band" = 'medium' THEN 2 ELSE 3 END;ORDER BY a CASE that gives each band a number — heavy 1, medium 2, light 3. And the label is built in a subquery first, so that CASE can reach it.
The query on the left: before — no subquery, simpler ORDER BY
SELECT CASE
WHEN "Freight" < 25 THEN 'light'
WHEN "Freight" < 60 THEN 'medium'
ELSE 'heavy'
END AS "Band",
count(*) AS "Orders"
FROM "Orders"
GROUP BY "Band"
ORDER BY min("Freight"); -- DESC reverses the orderThe query on the right: now — subquery + ORDER BY CASE: general, ANSI
SELECT "Band", count(*) AS "Orders"
FROM (SELECT CASE
WHEN "Freight" < 25 THEN 'light'
WHEN "Freight" < 60 THEN 'medium'
ELSE 'heavy' END AS "Band"
FROM "Orders") AS t
GROUP BY "Band"
ORDER BY CASE WHEN "Band" = 'heavy' THEN 1
WHEN "Band" = 'medium' THEN 2 ELSE 3 END;Hold on, Mnemosyne — wait. The query on the left looks simpler: it sorts light first, by min("Freight"). Heavy first is just that order, reversed. Wouldn't adding DESC there do it?
Yes — and I'm glad you saw it. DESC would work, for us. But that query leans on PostgreSQL's favour, GROUP BY "Band" — and SQL Server refuses it: invalid column name Band.
So it only works where PostgreSQL does me the favour. Is that the only catch?
No — and the second one is easy to miss: it isn't explicit. We want to sort by Band, but we sort by the minimum freight — a trick that works only because freight happens to run in the same order as the bands. If the team wanted medium first, then heavy, then light, no column sorts that way.
So the query on the right is a bit longer — but it's standard, it sorts by Band itself, and it can give any order — medium, heavy, light too, if that's what they want.
| The query on the left | The query on the right |
|---|---|
| ✓ it works on PostgreSQL, DuckDB, MySQL | ✓ standard: it runs on every engine |
| ✗ not standard: SQL Server refuses it | ✓ explicit and general: it sorts by the label itself |
| ✗ not explicit or general: needs a column already sorted |
The first true WHEN wins
Those bands are right, Leo — and CASE will let you break them without a single warning. Swap the first two WHENs — medium above light.
SELECT CASE
WHEN "Freight" < 60 THEN 'medium'
WHEN "Freight" < 25 THEN 'light'
ELSE 'heavy'
END AS "Band",
count(*) AS "Orders"
FROM "Orders"
GROUP BY "Band"
ORDER BY min("Freight");Same two tests, same three labels. How can the order of the lines matter?
No light orders at all — and medium jumped from 3941 to 6275. Where do you think they went?
But the 2334 light orders are still in the table. Their freight didn't change.
the same two tests — in the other order
| Test | Gives | Count | |
|---|---|---|---|
WHEN | "Freight" < 60 | 'medium' | 6275 |
WHEN | "Freight" < 25 | 'light' | never reached |
ELSE | 'heavy' | 3725 |
2334 light + 3941 medium = 6275. The narrow test is still there — nothing ever gets to it.
Under 25 is also under 60. The first WHEN now asks "under 60?", every light order says yes, and CASE stops right there. The light test is never even asked.
So the narrow test goes first. Otherwise a wide one catches everything before it gets a chance.
No ELSE means NULL
Here's a second trap — a quieter one. Finance only cares about heavy orders — freight over 50 — so you write one WHEN and no ELSE at all.
SELECT CASE
WHEN "Freight" > 50 THEN 'heavy'
END AS "Label",
count(*) AS "Orders"
FROM "Orders"
GROUP BY "Label"
ORDER BY "Label" NULLS LAST;Then every other order just has no label. That sounds harmless.
4654 heavy — and 5346 orders labelled NULL.
NULL? I never wrote NULL anywhere.
one gate — and no floor under it
| Test | Gives | Count | |
|---|---|---|---|
WHEN | "Freight" > 50 | 'heavy' | 4654 |
| (no ELSE) | NULL | 5346 |
Nothing catches 38.4. A CASE that runs out of WHENs hands back NULL.
You didn't have to, Leo. A CASE with no ELSE returns NULL for every row no WHEN matched.
The empty cells from the lesson on missing values. And those don't behave like a value.
Then I'll count the orders that are NOT heavy. The label lives in a subquery, so the WHERE can see it.
SELECT count(*) AS "Not heavy"
FROM (SELECT CASE
WHEN "Freight" > 50
THEN 'heavy'
END AS "Label"
FROM "Orders") AS t
WHERE "Label" <> 'heavy';Zero.
…Zero? Hang on, Mnemosyne — there are 5346 of them. We just counted them.
And every one of them is labelled NULL. NULL isn't unequal to 'heavy' — the comparison is unknown, and WHERE keeps only true. So all 5346 fell straight through.
So write the ELSE. Give every other order a real label — here, 'standard' — and the same filter finds 5346.
SELECT count(*) AS "Not heavy"
FROM (SELECT CASE
WHEN "Freight" > 50
THEN 'heavy'
ELSE 'standard'
END AS "Label"
FROM "Orders") AS t
WHERE "Label" <> 'heavy';the same gate — with a floor
| Test | Gives | Count | |
|---|---|---|---|
WHEN | "Freight" > 50 | 'heavy' | 4654 |
ELSE | 'standard' | 5346 |
One line, and the hole is a rung. The 5346 come back with a label on them.
One line. And the orders I couldn't see come straight back.
Could the ELSE just be 0, Mnemosyne? A number for 'not heavy'?
SELECT "OrderID",
CASE
WHEN "Freight" > 50 THEN 'heavy'
ELSE 0
END AS "Label"
FROM "Orders";SQL Error [22P02]: ERROR: invalid input syntax for type integer: "heavy"
Position: 65Try it — CloudBeaver refuses. The 0 made PostgreSQL decide the whole column is a number, so now 'heavy' is the line it can't read.
So a CASE gives back one column, with one type — every THEN and the ELSE have to agree. Words with words, numbers with numbers.
Exactly, Leo. That's why the ELSE said 'standard', not 0.
The short form, and when to join instead
CASE has a shorter form, too. When every WHEN compares the same column with a value, write the column once: CASE "ShipVia" WHEN 1 THEN 'Speedy Express' and so on. Which couriers go in, Leo?
SELECT CASE "ShipVia"
WHEN 1 THEN 'Speedy Express'
WHEN 2 THEN 'United Package'
WHEN 3 THEN 'Federal Shipping'
END AS "Shipper",
count(*) AS "Orders"
FROM "Orders"
GROUP BY "Shipper"
ORDER BY "Shipper";Speedy Express, United Package, Federal Shipping — the three from the first series.
511 orders with no courier? And no error.
Northwind Company has a fourth courier: ShipVia 4, Northern Freight Lines. Your CASE didn't name it, and there's no ELSE — so its orders came back NULL.
But the courier names are already in a table, Mnemosyne. Wouldn't I just join to "Shippers"?
Yes — join. All four couriers, the 511 included. And when a courier is added or renamed, the table changes and your query doesn't have to.
So CASE is for labels nobody stored — like light, medium and heavy.
Exactly. If the label already lives in a table, read it from the table.
COALESCE is a CASE
And you've already written one without knowing it. In the lesson on missing values you used COALESCE — it's a CASE: when the value is NULL, use the stand-in, otherwise use the value.
SELECT "CompanyName", "Country",
COALESCE("Region", '(none)')
AS "With COALESCE",
CASE
WHEN "Region" IS NULL THEN '(none)'
ELSE "Region"
END AS "With CASE"
FROM "Customers"
WHERE "Country" IN ('Canada', 'Poland')
ORDER BY "CustomerID";Identical columns — so COALESCE is that CASE, abbreviated. But why not the short form here, Mnemo: CASE "Region" WHEN NULL?
Because the short form tests with =, and = NULL is never true — not even for a NULL. That WHEN would never fire, and Poland would come back NULL. For NULL, always write IS NULL.
Your turn, Leo.
Label every order: online, or offline.
Web and EDI orders are online. You should get 6234 offline and 3766 online.
▶ Continue once you've run it.
SELECT CASE WHEN "Channel" IN (___) THEN 'online'
ELSE 'offline' END AS "Channel type",
count(*) AS "Orders"
FROM "Orders" GROUP BY "Channel type";CASE inside SUM: three counts side by side
Here's the trick that makes CASE worth the whole lesson: count shipped, cancelled and open orders side by side. Every order has a Status, one of those three. For each sales channel: how many orders, and how many of each — one row per channel.
SELECT "Channel",
count(*) AS "Orders",
SUM(CASE WHEN "Status" = 'Shipped'
THEN 1 ELSE 0 END) AS "Shipped",
SUM(CASE WHEN "Status" = 'Cancelled'
THEN 1 ELSE 0 END) AS "Cancelled",
SUM(CASE WHEN "Status" = 'Open'
THEN 1 ELSE 0 END) AS "Open"
FROM "Orders"
GROUP BY "Channel"
ORDER BY "Orders" DESC;Three counts with three different WHEREs… but one query only gets one WHERE.
Sales rep: 3749 orders — 3669 shipped, 61 cancelled, 19 open. Every channel on one row.
But how did SUM count anything, Mnemo? It adds numbers.
Each CASE turns an order in its status into a 1, and every other order into a 0. SUM adds the ones. That's a count — without a WHERE.
And the three columns add back up to the orders. One column per status, all in the same GROUP BY.
You'll also see it written with count — and this time the missing ELSE is on purpose. Every other order gets NULL, count skips NULLs, and Sales rep still says 61 cancelled.
SELECT "Channel",
count(*) AS "Orders",
count(CASE WHEN "Status" = 'Shipped'
THEN 1 END) AS "Shipped",
count(CASE WHEN "Status" = 'Cancelled'
THEN 1 END) AS "Cancelled",
count(CASE WHEN "Status" = 'Open'
THEN 1 END) AS "Open"
FROM "Orders"
GROUP BY "Channel"
ORDER BY "Orders" DESC;So there, the missing ELSE was the trap — and here, it's the trick. It depends on whether I meant the NULLs.
Cancelled %: a division that comes back as 0
Sales rep has the most cancelled orders — and by far the most orders. So the fair comparison is a percentage: the cancelled count divided by count(*). What do you expect for Sales rep?
SELECT "Channel",
count(*) AS "Orders",
SUM(CASE WHEN "Status" = 'Cancelled'
THEN 1 ELSE 0 END) AS "Cancelled",
SUM(CASE WHEN "Status" = 'Cancelled'
THEN 1 ELSE 0 END) / count(*) AS "Share"
FROM "Orders"
GROUP BY "Channel"
ORDER BY "Orders" DESC;61 out of 3749. Small — but not nothing.
Zero? Sales rep has 61 cancelled right there in the next column. That isn't zero.
On PostgreSQL — what CloudBeaver runs — a whole number divided by a whole number is a whole number. 61 ÷ 3749 is 0.016 and a bit, and the fraction is thrown away. Every channel: 0. No error.
And if I'd tried it in DuckDB first, Mnemo?
0.016 and a string of digits, for Sales rep. DuckDB keeps the fraction. Same query, two answers — so write it the way that's right on both.
Multiply by 100.0 before you divide. The decimal point makes the whole calculation decimal, on every database — and ROUND to one place gives a percentage a person can read.
SELECT "Channel",
count(*) AS "Orders",
SUM(CASE WHEN "Status" = 'Cancelled'
THEN 1 ELSE 0 END) AS "Cancelled",
ROUND(100.0 * SUM(CASE WHEN "Status" = 'Cancelled'
THEN 1 ELSE 0 END) / count(*), 1) AS "Cancelled %"
FROM "Orders"
GROUP BY "Channel"
ORDER BY "Orders" DESC;So the .0 is doing the real work. And multiplying first — before the division gets a chance to throw anything away.
Real percentages. And look — Sales rep had the most cancellations, and the lowest percentage: 1.6.
And EDI had the fewest, 22 — and the highest percentage, 2.2. The count said one channel; the percentage says the other.
So EDI is where orders get cancelled.
Careful, Leo — read it against the whole company first: 1.8. EDI is 22 of 1001; four fewer and it reads 1.8 too. A percentage always goes next to its count.
Case file: one courier stands out
And now your question, Leo — the one from the subqueries lesson: in 2024, orders grew and invoicing fell. An order is invoiced once its ship date is recorded. So per courier, for 2024: how many orders are marked Shipped but have no ship date?
SELECT s."CompanyName" AS "Courier",
count(*) AS "Orders",
SUM(CASE WHEN o."Status" = 'Shipped' AND o."ShippedDate" IS NULL
THEN 1 ELSE 0 END) AS "Shipped, no date",
ROUND(100.0 * SUM(CASE WHEN o."Status" = 'Shipped' AND o."ShippedDate" IS NULL
THEN 1 ELSE 0 END) / count(*), 1) AS "Share %"
FROM "Orders" o
JOIN "Shippers" s ON s."ShipperID" = o."ShipVia"
WHERE o."OrderDate" >= DATE '2024-01-01'
AND o."OrderDate" < DATE '2025-01-01'
GROUP BY s."CompanyName"
ORDER BY s."CompanyName";Two tests in one WHEN, and the percentage beside its count. Nothing I haven't just written.
Speedy Express: 178 of its 1768 orders are marked Shipped with no ship date. 10.1.
And the other three couriers: zero. Not one of their 630 orders.
So it isn't everywhere. It's one courier.
That's what the columns say — and all they say. Not why, and not whether those orders arrived. SQL tells us where to look; people confirm it.
What to take away, and what is next
Four rules, Leo. The first true WHEN wins, so put the narrow tests first. Write the ELSE, unless you mean the NULLs. The WHERE can't see a label the SELECT made — build it in a subquery. And a CASE that gives 1 or 0, inside a SUM, counts each status in its own column.
The first two stop a report that's quietly wrong. The third gets me past the first error everybody hits — and the fourth builds the report everybody asks for.
Your turn, Leo.
▶ Walk the path to enlightenment.
cd c:/DataPallas/db/datazeus
.\zeus.bat koans learnsql series2 _05- a label for every product: finish the CASE
- the first true WHEN wins: write the tests in the right order
- no ELSE means NULL: count only what the CASE labelled
- …and nine more, ending with two you write yourself
…/learnsql/series2/_05/CaseExpressionsKoans.groovy
That was CASE, Leo. A label worked out row by row: the first true WHEN wins, a row nobody matched gets NULL, and inside a SUM it counts any status you name, side by side. Next lesson: dates and times.
Good — now we know which courier has the orders marked Shipped with no ship date: Speedy Express. Next I want to know since when it started.
That's all, folks!
- Subqueries — one query's result inside another
- CASE — SQL's if/then for labels & buckets (this lesson)
- Dates & Times — ranges and boundaries
- Multi-Table JOINs & Grain — rows dropped or multiplied
- CTEs (WITH) — a long query, in named steps
- VIEWs, CREATE TABLE AS & Temp Tables — query or answer
- EXISTS & Correlated Subqueries — and the NOT IN trap
- Self-JOINs & Hierarchies — rows in the same table
- Window Functions I: OVER, PARTITION BY & ROW_NUMBER
- String Functions, LIKE & Regex — clean up messy data
- Window Functions II: LAG/LEAD, Running Totals & Frames
- UNION, INTERSECT, EXCEPT — stack and reconcile lists
- GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
- INSERT, UPDATE, DELETE & Transactions — safely
- UPSERT & MERGE — insert or update, safely re-run
- Median and Percentiles — WITHIN GROUP, not AVG
- Subqueries + CTEs + Window Functions — a real case
Found this to be a little gem? Help others find it too — someone out there is stuck trying to learn SQL right now. The button opens Reddit with the link and title already filled in, so you just pick a community and post.
Share on Reddit