Kodewick
Start learning →
Buckets3 / 12

Buckets

Lesson 3 of 12 · Part 1 · Know your data · about 20 minutes

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:

main.sql
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);
Output
sizeorderssales
small46725
medium472552
large223146
3 rows

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.

orders
idamount
415
346
7164
54
895
CASE WHEN amount < 30 … END AS size
labelled
idamountsize
415small
346medium
7164large
54small
895medium
CASE first gives every order a label, then the orders are grouped by label
Choose one

An order of exactly 30 goes into which bucket?

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.

Choose oneA wrong guess is fine

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);
Change it

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);
Should print
size | orders
small | 46
medium | 24
large | 45

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:

main.sql
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;
Output
namespenttier
Kai556A
Alba549A
Felipe458B
Zeca405B
Rafa369B
Lara351B
6 rows

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.

Exercise 1

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.

It should print
tieruserstotal
A21105
B102985
C192333
3 rows
exercise1.sql
1WITH spending AS (2    SELECT user_id, SUM(amount) AS spent3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6)7SELECT8FROM spending;
Output
Press Run or Ctrl+Enter

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.

main.sql
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;
Output
categoryq1q2q3q4
food5274216178
home51345435765
office3252206194
tech26770815661282
4 rows

tech sells the most every quarter. home jumps the most in quarter 4, from 435 to 765.

by category and quarter
categoryquartersales
food152
food274
food3216
food4178
SUM(CASE WHEN QUARTER(…) = 1 THEN … ELSE 0 END) AS q1 …
pivot table
categoryq1q2q3q4
food5274216178
Rows into columns: each quarter becomes a column, and each category becomes one row
Fill inTap one to fill a blank; tap a blank to take it back

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;

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:

main.sql
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;
Output
cityorderscancelledcancel_pct
Lisbon31516.1
Porto15213.3
Madrid29310.3
Rio3139.7
São Paulo2328.7
5 rows

Lisbon has the highest cancel rate, 16.1%, almost twice São Paulo's. Worth asking why: is delivery to Lisbon slow?

Exercise 2

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.

It should print
quarterpaidcancelled
181
2182
3403
4499
4 rows
exercise2.sql
1SELECT QUARTER(order_date) AS quarter2FROM orders3GROUP BY quarter4ORDER BY quarter;
Output
Press Run or Ctrl+Enter

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 …):

Choose oneA wrong guess is fine

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;

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 … END gives every row a label. GROUP BY that label, and a continuous number becomes a few buckets.
  • WHEN is 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 use CASE.
  • 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), or COUNT(CASE WHEN … THEN 1 END) with no ELSE. COUNT with ELSE 0 counts every row.
Finished lesson 3?Lesson 3 of 12 · progress stays in this browser
Next · lesson 4 · 20 minRanking, furtherThe best sellers in each category, how much the top 25% of customers bring in, who the top 10% are: handle ties with RANK, DENSE_RANK and ROW_NUMBER, and split by share with NTILE and PERCENT_RANK.Next lesson →
The button marks this lesson done and opens the next.
Practise what this lesson taught#034CASE WHEN salary >= …Salary bandsBasic#032COUNT(CASE …)Orders by statusStarter#033SUM(action = …)Actions per dayBasicAll 50 SQL problems →