Buckets
Buckets: CASE WHEN amount < 30 THEN … WHEN … ELSE … END, then group by it. WHEN is checked from top to bottom, so put the smaller condition first. Rows to columns: SUM(CASE WHEN quarter = 1 THEN amount ELSE 0 END). Counting by condition: SUM(CASE WHEN … THEN 1 ELSE 0 END).
After the monthly numbers, the boss has another question: "Do we get more big orders or more small ones? Who are our big customers?" An amount is a continuous number. To answer questions like these, you first cut it into a few buckets.
A bucket for every order
In this step you use CASE to give every order a label: under 30 is small, 30 to 99 is medium, and 100 or more is large. Once every order has its label, group by the label:
1SELECT CASE2 WHEN amount < 30 THEN 'small'3 WHEN amount < 100 THEN 'medium'4 ELSE 'large'5 END AS size,6 COUNT(*) AS orders,7 SUM(amount) AS sales8FROM orders9WHERE status = 'paid'10GROUP BY size11ORDER BY MIN(amount);
| size | orders | sales |
|---|---|---|
| small | 46 | 725 |
| medium | 47 | 2552 |
| large | 22 | 3146 |
There are only 22 large orders, less than a fifth of all orders, yet they brought in 3146: about half of the whole year's sales. There are 46 small orders, and together they come to just 725.
The last line, ORDER BY MIN(amount), is a little trick: it sorts by the smallest amount in each bucket, so small, medium and large come out in the right order. Sorting by size would sort alphabetically: large, medium, small.
| id | amount |
|---|---|
| 4 | 15 |
| 3 | 46 |
| 7 | 164 |
| 5 | 4 |
| 8 | 95 |
CASE WHEN amount < 30 … END AS size| id | amount | size |
|---|---|---|
| 4 | 15 | small |
| 3 | 46 | medium |
| 7 | 164 | large |
| 5 | 4 | small |
| 8 | 95 | medium |
An order of exactly 30 goes into which bucket?
30 < 30 is false, so the first WHEN doesn't match. 30 < 100 is true, so it's medium. When you make buckets, think about which side a number right on the edge belongs to, and say in your report whether you mean "under 30" or "30 or less".The order of WHEN
In this step you meet the most common CASE mistake. CASE checks the WHENs one by one from top to bottom, and stops at the first one that's true. It doesn't look at the rest. So the order of the conditions matters a lot.
What happens if the two WHENs swap places?
1SELECT CASE2 WHEN amount < 100 THEN 'medium'3 WHEN amount < 30 THEN 'small'4 ELSE 'large'5 END AS size,6 COUNT(*) AS orders7FROM orders8WHERE status = 'paid'9GROUP BY size10ORDER BY MIN(amount);
amount < 100 is checked first, it's true, so the order becomes medium, and amount < 30 never gets its turn. That's why small has no orders at all. When your buckets go from small to large, put the smaller condition first.The boss says anything from 50 up is a large order. Change only the number in the green box and see how many large orders there are.
1SELECT CASE2 WHEN amount < 30 THEN 'small'3 WHEN amount < THEN 'medium'4 ELSE 'large'5 END AS size,6 COUNT(*) AS orders7FROM orders8WHERE status = 'paid'9GROUP BY size10ORDER BY MIN(amount);
size | orders small | 46 medium | 24 large | 45
amount < 50 is false, meaning 50 or more, falls through to ELSE and becomes large. Move the edge and every bucket changes, so agree on the buckets with the boss first.Three tiers of customers
In this step you put people into buckets, not orders. First you work out how much each person spent in total, then you bucket that number. Two steps: a perfect fit for WITH:
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6)7SELECT u.name, s.spent,8 CASE9 WHEN s.spent >= 500 THEN 'A'10 WHEN s.spent >= 200 THEN 'B'11 ELSE 'C'12 END AS tier13FROM spending AS s14JOIN users AS u ON u.id = s.user_id15ORDER BY s.spent DESC16LIMIT 6;
| name | spent | tier |
|---|---|---|
| Kai | 556 | A |
| Alba | 549 | A |
| Felipe | 458 | B |
| Zeca | 405 | B |
| Rafa | 369 | B |
| Lara | 351 | B |
People who spent 500 or more are tier A, 200 or more is tier B, and everyone else is tier C. This time the buckets go from large to small, so the larger condition comes first.
How many people in each tier
✓Count how many people are in each tier and how much they spent in total. Three columns: tier, users and total, sorted by tier.
| tier | users | total |
|---|---|---|
| A | 2 | 1105 |
| B | 10 | 2985 |
| C | 19 | 2333 |
1WITH spending AS (2 SELECT user_id, SUM(amount) AS spent3 FROM orders4 WHERE status = 'paid'5 GROUP BY user_id6)7SELECT8FROM spending;
Tier A has only 2 people and tier B has 10, but those 12 people spent over 60% of the year's money. These are the customers to look after most.
Rows into columns
In this step you build a pivot table: one row per product category, one column per quarter. A plain GROUP BY category, quarter gives 16 rows, which are tiring to read. Turn the quarters from rows into columns, and you can compare them across at a glance.
The trick is one SUM(CASE …) per column: if a row belongs to quarter 1, add its money to q1; if not, add 0.
1SELECT p.category,2 SUM(CASE WHEN QUARTER(o.order_date) = 1 THEN oi.qty * oi.price ELSE 0 END) AS q1,3 SUM(CASE WHEN QUARTER(o.order_date) = 2 THEN oi.qty * oi.price ELSE 0 END) AS q2,4 SUM(CASE WHEN QUARTER(o.order_date) = 3 THEN oi.qty * oi.price ELSE 0 END) AS q3,5 SUM(CASE WHEN QUARTER(o.order_date) = 4 THEN oi.qty * oi.price ELSE 0 END) AS q46FROM orders AS o7JOIN order_items AS oi ON oi.order_id = o.id8JOIN products AS p ON p.id = oi.product_id9WHERE o.status = 'paid'10GROUP BY p.category11ORDER BY p.category;
| category | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| food | 52 | 74 | 216 | 178 |
| home | 51 | 345 | 435 | 765 |
| office | 32 | 52 | 206 | 194 |
| tech | 267 | 708 | 1566 | 1282 |
tech sells the most every quarter. home jumps the most in quarter 4, from 435 to 765.
| category | quarter | sales |
|---|---|---|
| food | 1 | 52 |
| food | 2 | 74 |
| food | 3 | 216 |
| food | 4 | 178 |
SUM(CASE WHEN QUARTER(…) = 1 THEN … ELSE 0 END) AS q1 …| category | q1 | q2 | q3 | q4 |
|---|---|---|---|---|
| food | 52 | 74 | 216 | 178 |
Complete this column: add only the amounts of paid orders to paid_sales, and add 0 for any other status.
1SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,2 SUM(CASE WHEN status = 'paid' THEN ELSE 0 END) AS paid_sales3FROM orders4WHERE order_date >= '2025-12-01'5GROUP BY month;
THEN, write what you want to add up. To add money, write amount. With 1, the total would be the number of orders, not the money.Counting by condition
In this step you use SUM(CASE …) to count: 1 when the condition is true, 0 when it isn't, and the total is how many rows match. This way one query can count several things at once:
1SELECT u.city,2 COUNT(*) AS orders,3 SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,4 ROUND(100 * SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) / COUNT(*), 1) AS cancel_pct5FROM orders AS o6JOIN users AS u ON u.id = o.user_id7WHERE o.status <> 'test'8 AND u.city IS NOT NULL9GROUP BY u.city10ORDER BY cancel_pct DESC;
| city | orders | cancelled | cancel_pct |
|---|---|---|---|
| Lisbon | 31 | 5 | 16.1 |
| Porto | 15 | 2 | 13.3 |
| Madrid | 29 | 3 | 10.3 |
| Rio | 31 | 3 | 9.7 |
| São Paulo | 23 | 2 | 8.7 |
Lisbon has the highest cancel rate, 16.1%, almost twice São Paulo's. Worth asking why: is delivery to Lisbon slow?
Paid and cancelled orders by quarter
✓Count the paid and the cancelled orders in each quarter. Three columns: quarter (use QUARTER(order_date)), paid and cancelled, sorted by quarter.
| quarter | paid | cancelled |
|---|---|---|
| 1 | 8 | 1 |
| 2 | 18 | 2 |
| 3 | 40 | 3 |
| 4 | 49 | 9 |
1SELECT QUARTER(order_date) AS quarter2FROM orders3GROUP BY quarter4ORDER BY quarter;
A COUNT trap
In this step you see a version that looks almost the same but gets the wrong answer. When counting cancelled orders, some people write COUNT(CASE …):
What are the two columns?
1SELECT COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS a,2 COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS b3FROM orders;
COUNT(…) counts how many values are not NULL, whether the value is 1 or 0. In a, every row is either 1 or 0, never NULL, so all 135 rows are counted. b has no ELSE, so when the condition is false, CASE gives NULL, which isn't counted. That's why b is right.Remember one simple rule: with SUM, write ELSE 0; with COUNT, leave out ELSE. Both work. Just don't mix them.
What you learned
CASE WHEN … THEN … ELSE … ENDgives every row a label.GROUP BYthat label, and a continuous number becomes a few buckets.WHENis checked from top to bottom and stops at the first true one. Going from small to large, put the smaller condition first; going from large to small, put the larger one first. Think about which side the numbers on the edge belong to.- Bucketing people takes two steps: work out each person's total with
WITH, then useCASE. - Rows into columns: one
SUM(CASE WHEN … THEN value ELSE 0 END)per column. - Counting by condition:
SUM(CASE WHEN … THEN 1 ELSE 0 END), orCOUNT(CASE WHEN … THEN 1 END)with noELSE.COUNTwithELSE 0counts every row.