Part 07 / Topic 2 of 8
Ranking
Four functions assign positions within a window, differing only in how they treat ties. Watch all three on tied prices (a tiny inline table makes the tie obvious):
SELECT name, price,
ROW_NUMBER() OVER (ORDER BY price DESC) AS row_num,
RANK() OVER (ORDER BY price DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY price DESC) AS dense_rnk
FROM (VALUES ('A', 100), ('B', 90), ('C', 90), ('D', 80)) AS t(name, price);
name | price | row_num | rnk | dense_rnk
------+-------+---------+-----+-----------
A | 100 | 1 | 1 | 1
B | 90 | 2 | 2 | 2
C | 90 | 3 | 2 | 2
D | 80 | 4 | 4 | 3
(4 rows)
ROW_NUMBER— unique positions, ties broken arbitrarily: 1, 2, 3, 4.RANK— ties share a position, then a gap: 1, 2, 2, 4 (nothing is 3rd when two are 2nd).DENSE_RANK— ties share, no gap: 1, 2, 2, 3.
Add PARTITION BY and the ranking restarts per group — each product's price rank within its category:
SELECT category_id, name, price,
RANK() OVER (PARTITION BY category_id ORDER BY price DESC) AS rank_in_category
FROM products
ORDER BY category_id, rank_in_category;
category_id | name | price | rank_in_category
-------------+--------------------+---------+------------------
1 | USB-C Cable | 15.00 | 1
2 | Postgres Deep Dive | 55.00 | 1
2 | SQL for Beginners | 35.00 | 2
3 | Desk Lamp | 45.00 | 1
4 | Laptop Pro 14 | 1200.00 | 1
4 | Laptop Air 13 | 950.00 | 2
5 | Phone X | 799.00 | 1
5 | Phone Lite | 399.00 | 2
6 | Coffee Maker | 120.00 | 1
6 | Chef Knife | 80.00 | 2
(10 rows)
NTILE(n) deals rows into n near-equal buckets (quartiles: NTILE(4)) — handy for "top 25% of customers" segmentation, which the Stage 2 project uses.
🧪 Quick quiz — answer from memory, then check.
- For prices 100, 90, 90, 80 descending, what does RANK() return?
- You need exactly one winner per category, ties or not. Which function?
Show the answers
- 1, 2, 2, 4 — ties share, then a gap. (DENSE_RANK: 1, 2, 2, 3; ROW_NUMBER: 1, 2, 3, 4.)
- ROW_NUMBER — it never ties, so
= 1yields exactly one row per partition.
Exercise 2: The tie trio
What to do: Over the scores 50, 40, 40, 30 (build them with VALUES), predict all three ranking columns on paper — then run and check.
Sample output:
player | score | row_num | rnk | dense_rnk
--------+-------+---------+-----+-----------
P1 | 50 | 1 | 1 | 1
P2 | 40 | 2 | 2 | 2
P3 | 40 | 3 | 2 | 2
P4 | 30 | 4 | 4 | 3
(4 rows)
💡 Hint: the gap after RANK's tie (no 3) is the whole lesson.
Show the solution to Exercise 2
-- Exercise 2: The tie trio
-- Scores 50, 40, 40, 30: predicted ROW_NUMBER 1,2,3,4 / RANK 1,2,2,4 /
-- DENSE_RANK 1,2,2,3 — then proven.
SELECT player, score,
ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num,
RANK() OVER (ORDER BY score DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rnk
FROM (VALUES ('P1', 50), ('P2', 40), ('P3', 40), ('P4', 30)) AS t(player, score);