Kodewick
Start learning →
Ranking, further4 / 12

Ranking, further

Lesson 4 of 12 · Part 2 · Window functions at work · about 20 minutes

Top N per category: compute RANK() OVER (PARTITION BY category ORDER BY …) inside WITH, then WHERE rank <= N outside. With ties, RANK may give a few extra rows, while ROW_NUMBER always gives exactly N. NTILE(4) splits rows into four groups. PERCENT_RANK() is a relative position from 0 to 1.

You met ROW_NUMBER and RANK in the beginner course. This lesson puts them to work on questions a boss really asks: "What are the best sellers in each category?" "How much do the top quarter of customers bring in?" "Who are the top 10% of customers?"

How ties are ranked

In this step you see how the three ranking functions differ when there's a tie. First work out how much each person spent, then rank them three ways, and look only at the middle places:

main.sql
1WITH spending AS (2    SELECT user_id, SUM(amount) AS spent3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6),7ranked AS (8    SELECT user_id, spent,9        ROW_NUMBER() OVER (ORDER BY spent DESC, user_id) AS row_num,10        RANK() OVER (ORDER BY spent DESC) AS rnk,11        DENSE_RANK() OVER (ORDER BY spent DESC) AS dense12    FROM spending13)14SELECT *15FROM ranked16WHERE row_num BETWEEN 15 AND 1917ORDER BY row_num;
Output
user_idspentrow_numrnkdense
31178151515
9172161616
14171171717
23171181717
5162191918
5 rows

Users 14 and 23 both spent 171:

  • ROW_NUMBER ignores ties: one gets 17, the other 18. Who comes first depends on the second thing in ORDER BY, user_id.
  • RANK gives both of them 17, and the next person jumps to 19, just like in a race where two people tie for first and the next one is third.
  • DENSE_RANK also gives both 17, but the next person is 18: no places are skipped.
ranked
user_idspentrow_numrnkdense
9172161616
14171171717
23171181717
5162191918
Both spent 171: the places the three functions give
Choose one

The boss asks, "Who's in 18th place for spending?" Which function always gives a place 18 in the result?

The top few in each category

In this step you solve the most common ranking question: the best-selling products in each category. First rank by category inside WITH, then pick the ones in place 1 outside:

main.sql
1WITH product_sales AS (2    SELECT p.category, p.name, SUM(oi.qty) AS qty3    FROM orders AS o4    JOIN order_items AS oi ON oi.order_id = o.id5    JOIN products AS p ON p.id = oi.product_id6    WHERE o.status = 'paid'7    GROUP BY p.category, p.name8),9ranked AS (10    SELECT category, name, qty,11        RANK() OVER (PARTITION BY category ORDER BY qty DESC) AS r12    FROM product_sales13)14SELECT category, name, qty15FROM ranked16WHERE r = 117ORDER BY category, name;
Output
categorynameqty
foodCoffee beans10
foodTea box10
homeCushion37
officeDesk calendar24
officeNotebook24
techSpeaker26
6 rows

4 categories, but 6 rows: in food, Coffee beans and Tea box both sold 10, and in office, Desk calendar and Notebook both sold 24, so they tie for first. That's what's good about RANK: a tie never makes one of them quietly disappear. With ROW_NUMBER, each category always gets exactly one row, but which of the two tied products stays depends on the second sort condition you give. If you don't give one, the database picks, and it might pick differently each time you run the query.

Exercise 1

Top two by sales in each category

Rank the products in each category by sales (qty * price added up) and find the top two in each category. Four columns: category, name, sales and r (the place), sorted by category, then place.

It should print
categorynamesalesr
foodCoffee beans3001
foodTea box2202
homeCushion6661
homeDesk lamp6302
officeDesk calendar2881
officeNotebook1442
techHeadphones16801
techSpeaker15602
8 rows
exercise1.sql
1WITH product_sales AS (2    SELECT p.category, p.name, SUM(oi.qty * oi.price) AS sales3    FROM orders AS o4    JOIN order_items AS oi ON oi.order_id = o.id5    JOIN products AS p ON p.id = oi.product_id6    WHERE o.status = 'paid'7    GROUP BY p.category, p.name8)9SELECT category, name, sales10FROM product_sales;
Output
Press Run or Ctrl+Enter

A rank can't go straight into WHERE

In this step you see an error everybody runs into sooner or later. Why do we always wrap the query in an extra WITH? Try putting the rank straight into WHERE:

main.sql
1SELECT name, price, RANK() OVER (ORDER BY price DESC) AS r2FROM products3WHERE RANK() OVER (ORDER BY price DESC) <= 3;
Output
ERROR 3593 (HY000): You cannot use the window function 'rank' in this context.'

An error. The reason is the order a query runs in: WHERE picks the rows first, and only after that does SELECT work out the ranks. While WHERE is doing its job, the ranks don't exist yet. So you work out the rank first, in a WITH (or a subquery), where it becomes a column, and then the WHERE outside can use it.

Put in orderDrag, or use the arrows

Put these lines in order to make a query that runs: the 3 most expensive products.

  1. )
  2. SELECT name, price
  3. SELECT name, price, RANK() OVER (ORDER BY price DESC) AS r
  4. FROM products
  5. WHERE r <= 3
  6. FROM ranked
  7. ORDER BY r;
  8. WITH ranked AS (
Should print
name | price
Headphones | 80
Speaker | 60
Desk lamp | 35

Four equal groups

In this step you split people by share. NTILE(4) splits the sorted rows into 4 groups, as evenly as it can, and gives each row a group number from 1 to 4. The quarter who spent the most is group 1:

main.sql
1WITH spending AS (2    SELECT user_id, SUM(amount) AS spent3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6),7quartered AS (8    SELECT user_id, spent,9        NTILE(4) OVER (ORDER BY spent DESC, user_id) AS quarter10    FROM spending11)12SELECT quarter, COUNT(*) AS users, SUM(spent) AS total13FROM quartered14GROUP BY quarter15ORDER BY quarter;
Output
quarteruserstotal
183248
281580
381135
47460
4 rows

31 people bought something, which can't be split into 4 equal groups, so the groups are 8, 8, 8 and 7: the extra people go one per group, starting from group 1. The 8 people in group 1 spent 3248, more than half of the whole year. The last 7 people spent only 460 between them.

Choose one

If you split 10 rows with NTILE(3), how many rows does each group get?

The top few percent

In this step you find the top 10% of customers. PERCENT_RANK() gives each row a number from 0 to 1: first place is 0, last place is 1, and the places in between are spread evenly. The formula is (rank - 1) / (rows - 1).

main.sql
1WITH spending AS (2    SELECT user_id, SUM(amount) AS spent3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6),7ranked AS (8    SELECT user_id, spent,9        PERCENT_RANK() OVER (ORDER BY spent DESC) AS pr10    FROM spending11)12SELECT u.name, r.spent, ROUND(r.pr, 2) AS pr13FROM ranked AS r14JOIN users AS u ON u.id = r.user_id15WHERE r.pr <= 0.116ORDER BY r.spent DESC;
Output
namespentpr
Kai5560
Alba5490.03
Felipe4580.07
Zeca4050.1
4 rows

Both NTILE and PERCENT_RANK can split by share. The difference: NTILE only cares about making the groups the same size, so two tied people can land in different groups. PERCENT_RANK uses the places from RANK, so tied people get the same number and always end up on the same side.

Change it

Change only the number in the green box to find the top 20% of customers by spending.

1WITH spending AS (2    SELECT user_id, SUM(amount) AS spent3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6),7ranked AS (8    SELECT user_id, spent,9        PERCENT_RANK() OVER (ORDER BY spent DESC) AS pr10    FROM spending11)12SELECT user_id, spent13FROM ranked14WHERE pr <= 15ORDER BY spent DESC;
Should print
user_id | spent
11 | 556
26 | 549
6 | 458
25 | 405
17 | 369
12 | 351
3 | 292

What you learned

  • With ties: ROW_NUMBER forces an order (give it a second sort condition); RANK gives tied rows the same place and skips the places after; DENSE_RANK gives tied rows the same place and skips nothing.
  • Top N per category: put RANK() OVER (PARTITION BY category ORDER BY …) in a WITH, then WHERE rank <= N outside. With RANK, ties can add a few extra rows.
  • A window function can't go in WHERE (ERROR 3593), because WHERE runs before SELECT.
  • NTILE(n) splits the rows into n groups as evenly as it can; the extra rows go one each, starting from group 1.
  • PERCENT_RANK() is a relative position from 0 to 1, and <= 0.1 means the top 10%. Tied people always end up on the same side.
Practise what this lesson taught#002ROW_NUMBER() + rn <= 2Top two in each departmentStarter#004GROUP BY + ROW_NUMBER()Best seller in each categoryMini challenge#038PERCENT_RANK()Top quarter salariesBasicAll 50 SQL problems →