Ranking and top N per group
Overview
“Our top three products.” “Each customer’s most recent order.” “The best-selling item in every category.” “Remove duplicate rows, keeping the newest.” All of these are ranking problems, and they’re solved with a family of window functions that number rows in an order you choose.
Ordering inside the window
The window functions in the previous lesson ignored row order — a sum is the same whatever order you add things. Ranking functions need an order, given by ORDER BY inside the OVER (…):
SELECT name, price,
row_number() OVER (ORDER BY price DESC) AS position
FROM products
ORDER BY position
LIMIT 5; name | price | position
-------------------+-------+----------
Burr Grinder | 89.00 | 1
Electric Kettle | 59.90 | 2
Glass Teapot | 32.00 | 3
Gift Card | 25.00 | 4
Pour-Over Dripper | 24.00 | 5
(5 rows)row_number() numbers the rows 1, 2, 3… in the window’s order. The ORDER BY inside OVER decides the numbering; the query’s own ORDER BY decides how the result is displayed. They’re independent, though they’re often the same.
Three ways to rank
The functions differ in how they treat ties — rows with the same value in the ordering column. Bean & Leaf has no products at the same price, so let’s pretend the Pour-Over Dripper has been repriced to 25.00, the same as the gift card. A CTE with a CASE does the pretending without changing the table:
WITH p AS (
SELECT name, CASE WHEN name = 'Pour-Over Dripper' THEN 25.00 ELSE price END AS price
FROM products
)
SELECT name, price,
row_number() OVER (ORDER BY price DESC, name) AS row_number,
rank() OVER (ORDER BY price DESC) AS rank,
dense_rank() OVER (ORDER BY price DESC) AS dense_rank
FROM p
ORDER BY price DESC, name
LIMIT 6; name | price | row_number | rank | dense_rank
------------------------+-------+------------+------+------------
Burr Grinder | 89.00 | 1 | 1 | 1
Electric Kettle | 59.90 | 2 | 2 | 2
Glass Teapot | 32.00 | 3 | 3 | 3
Gift Card | 25.00 | 4 | 4 | 4
Pour-Over Dripper | 25.00 | 5 | 4 | 4
Darjeeling First Flush | 18.00 | 6 | 6 | 5
(6 rows)| Function | Ties | After a tie | Use when |
|---|---|---|---|
row_number() |
different numbers | continues 5, 6… | you need exactly N rows, or to pick one row per group |
rank() |
same rank | skips (4, 4, 6) | “places” in a competition: two joint 4th, no 5th |
dense_rank() |
same rank | no gap (4, 4, 5) | “the 2nd highest price”, counting distinct values |
row_number() has to put tied rows in some order. Without a tie-breaker, that order is arbitrary and can change between runs — that’s why the query above orders by price DESC, name. Always add a tie-breaker (often the primary key) when you use row_number() to pick rows.
Ranking within groups
Add PARTITION BY and the numbering restarts for each 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
WHERE category_id IS NOT NULL
ORDER BY category_id, rank_in_category; category_id | name | price | rank_in_category
-------------+------------------------+-------+------------------
1 | Ethiopian Yirgacheffe | 14.50 | 1
1 | Colombian Supremo | 12.00 | 2
1 | Decaf House Blend | 11.25 | 3
2 | Darjeeling First Flush | 18.00 | 1
2 | Jasmine Green | 12.75 | 2
2 | Assam Breakfast | 9.50 | 3
2 | Chamomile Calm | 8.00 | 4
3 | Burr Grinder | 89.00 | 1
3 | Electric Kettle | 59.90 | 2
3 | Glass Teapot | 32.00 | 3
3 | Pour-Over Dripper | 24.00 | 4
(11 rows)Top N per group
This is one of the most asked-for SQL patterns: the top N rows within each group. Since window functions can’t go in WHERE, number the rows in a CTE and filter outside it. The best-selling product (by units) in each category:
WITH sales AS (
SELECT p.category_id, p.name, sum(oi.quantity) AS units
FROM order_items AS oi
JOIN products AS p ON p.id = oi.product_id
WHERE p.category_id IS NOT NULL
GROUP BY p.category_id, p.name
),
ranked AS (
SELECT category_id, name, units,
rank() OVER (PARTITION BY category_id ORDER BY units DESC) AS r
FROM sales
)
SELECT category_id, name, units
FROM ranked
WHERE r = 1
ORDER BY category_id, name; category_id | name | units
-------------+-----------------------+-------
1 | Ethiopian Yirgacheffe | 12
2 | Assam Breakfast | 8
2 | Jasmine Green | 8
3 | Burr Grinder | 3
3 | Electric Kettle | 3
3 | Pour-Over Dripper | 3
(6 rows)Two teas tie on 8 units and three equipment products on 3, so rank() lets them share first place — that’s usually the honest answer for a “best seller” report. With row_number(), you’d get exactly one per category, chosen by the tie-breaker. Pick the function that matches what the business means by “top”.
The latest row per group
Another classic: each customer’s most recent order. Number each customer’s orders from newest to oldest and keep number 1:
WITH numbered AS (
SELECT o.*,
row_number() OVER (PARTITION BY customer_id ORDER BY ordered_at DESC) AS n
FROM orders AS o
)
SELECT customer_id, id AS order_id, ordered_at::date AS day, status
FROM numbered
WHERE n = 1
ORDER BY customer_id; customer_id | order_id | day | status
-------------+----------+------------+-----------
1 | 23 | 2026-11-20 | pending
2 | 21 | 2026-10-27 | paid
3 | 19 | 2026-09-19 | delivered
4 | 24 | 2026-11-29 | pending
5 | 16 | 2026-07-08 | delivered
6 | 22 | 2026-11-08 | paid
7 | 18 | 2026-09-01 | shipped
8 | 20 | 2026-10-03 | shipped
(8 rows)Change n = 1 to n <= 2 for the last two orders each. The same pattern removes duplicates: partition by the columns that define a duplicate, order by whatever decides which copy to keep, and delete or ignore everything with n > 1.
PostgreSQL also has a compact shortcut for “first row per group”, DISTINCT ON:
SELECT DISTINCT ON (customer_id)
customer_id, id AS order_id, ordered_at::date AS day, status
FROM orders
ORDER BY customer_id, ordered_at DESC; customer_id | order_id | day | status
-------------+----------+------------+-----------
1 | 23 | 2026-11-20 | pending
2 | 21 | 2026-10-27 | paid
3 | 19 | 2026-09-19 | delivered
4 | 24 | 2026-11-29 | pending
5 | 16 | 2026-07-08 | delivered
6 | 22 | 2026-11-08 | paid
7 | 18 | 2026-09-01 | shipped
8 | 20 | 2026-10-03 | shipped
(8 rows)DISTINCT ON (customer_id) keeps the first row for each customer, where “first” is defined by the ORDER BY — which must start with the same column. It’s PostgreSQL-only; the row_number() version works everywhere.
Splitting into buckets: NTILE
ntile(n) divides the ordered rows into n roughly equal buckets — handy for quartiles or “top third / middle / bottom” segments:
SELECT name, price,
ntile(3) OVER (ORDER BY price DESC) AS price_third
FROM products
ORDER BY price DESC; name | price | price_third
------------------------+-------+-------------
Burr Grinder | 89.00 | 1
Electric Kettle | 59.90 | 1
Glass Teapot | 32.00 | 1
Gift Card | 25.00 | 1
Pour-Over Dripper | 24.00 | 2
Darjeeling First Flush | 18.00 | 2
Ethiopian Yirgacheffe | 14.50 | 2
Jasmine Green | 12.75 | 2
Colombian Supremo | 12.00 | 3
Decaf House Blend | 11.25 | 3
Assam Breakfast | 9.50 | 3
Chamomile Calm | 8.00 | 3
(12 rows)Twelve products, three buckets of four. Related functions percent_rank() and cume_dist() give a row’s relative position as a fraction between 0 and 1.
Tip: to rank by “most first”, remember
DESCinside theOVER.rank() OVER (ORDER BY revenue)gives rank 1 to the smallest revenue — a surprisingly common slip.
The two priciest products in each category
For each category, find its two most expensive products. Use a CTE that adds ROW_NUMBER() numbered within each category_id from the highest price down (break ties by name), then keep only rows numbered 1 or 2. Return category_id, name, price and the number as position, for products that have a category, sorted by category_id and position.
WITH ranked AS (
SELECT category_id, name, price
FROM products
WHERE category_id IS NOT NULL
)
SELECT * FROM ranked;WITH ranked AS (
SELECT category_id, name, price,
row_number() OVER (PARTITION BY category_id
ORDER BY price DESC, name) AS position
FROM products
WHERE category_id IS NOT NULL
)
SELECT category_id, name, price, position
FROM ranked
WHERE position <= 2
ORDER BY category_id, position;Summary
- ORDER BY inside OVER (…) decides the order in which the window function numbers the rows; it's separate from the query's ORDER BY.
- row_number() gives 1, 2, 3… with no ties; rank() gives ties the same rank and then skips; dense_rank() gives ties the same rank without gaps.
- Add a tie-breaker column so row_number() is deterministic.
- Top N per group: number rows with PARTITION BY group ORDER BY measure in a CTE, then filter WHERE n <= N.
- Latest row per group: row_number() … ORDER BY date DESC, keep n = 1 (or use PostgreSQL's DISTINCT ON).