Ranking
Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 2:00 on Tuesday afternoon, and merchandising wants the two best-selling products in each category for the home page by five. Your first try ends in LIMIT 2 and returns two products for the whole shop. Your second try returns three products for Fashion, because two of them sold exactly 20 units. Which answer is right?
You'll learn to
- Number rows with ROW_NUMBER, RANK and DENSE_RANK, and predict ties
- Return the top N rows of every group
- Explain why a window function cannot go in WHERE
- Say what a window costs: one sort per window
Learn
GROUP BY squashes. A window keeps rows.
Your first try used GROUP BY and LIMIT. The trouble is that GROUP BY squashes rows: many go in, one per group comes out. You cannot ask "which product is second in Fashion?" once Fashion is a single row.
You need something else: keep every product, and write its place within its own category next to it.
That is a window function. It keeps every row and adds a column worked out over a set of related rows, its window.
RANK() OVER (PARTITION BY category ORDER BY units DESC) reads like this. Split the rows into one window per category (PARTITION BY). Sort each window by units, highest first (ORDER BY). Give each row its place. Without PARTITION BY, the whole table is one window.
The three Books products, grouped and ranked
Two boxes side by side: GROUP BY turns the three Books products into one row with 29 units, while a window function keeps all three rows and adds a rank to each.
Compare the two boxes: the same three rows go in, but only the window on the right still knows which product is which.
One tie, three answers
Three functions hand out places. They agree until two rows tie.
Sort the 20 products by price. The Desk Lamp and the Cookbook both cost $24.99, and they sit in rows 9 and 10.
ROW_NUMBERnever repeats. One of them gets 9 and the other 10, and nothing says which.RANKgives both 9, then skips to 11. Think of sports medals: two golds, then no silver.DENSE_RANKgives both 9 and carries on at 10, with no gap.
Three ways to number rows
SELECT name, price,
ROW_NUMBER() OVER (ORDER BY price) AS row_number,
RANK() OVER (ORDER BY price) AS rank,
DENSE_RANK() OVER (ORDER BY price) AS dense_rank
FROM products
ORDER BY price, product_id;
Scroll to the Desk Lamp and the Cookbook: both cost $24.99. Then look at the Yoga Mat, one row down.
Pick the one the question needs
The question decides the function.
- Use
ROW_NUMBERwhen you need exactly N rows: one row per key (the next lesson), or pages of results. Always add a tie-breaker to itsORDER BY, such asORDER BY units DESC, product_id. Without one, tied rows can swap places between runs. - Use
RANKwhen ties should share a place and you want everyone who reached the top N, even if that is more than N rows. - Use
DENSE_RANKfor "the Nth highest value". The second-highest price is whatever has dense rank 2, however many products share the top price.
So Nora sends you back to merchandising with one question: if two products tie for second place, do you want both?
What happens at a tie
| name | price | ROWNUMBER | RANK | DENSERANK |
|---|---|---|---|---|
| Canvas Tote | 22.00 | 8 | 8 | 8 |
| Desk Lamp | 24.99 | 9 | 9 | 9 |
| Cookbook | 24.99 | 10 | 9 | 9 |
| Yoga Mat | 29.50 | 11 | 11 | 10 |
Read across the Yoga Mat row: 11, 11, 10. ROW_NUMBER counted rows, RANK skipped a place after the tie, and DENSE_RANK did not.
Remember: ROW_NUMBER gives exactly N rows, RANK shares a place and skips, DENSE_RANK shares a place with no gap. Ask about ties before you choose.
The top two in every category
Merchandising answers: show both when there is a tie. So you use RANK.
The pattern has two steps. First, work out the rank inside each category. Second, filter on that rank.
Units sold come from order_items, so one CTE totals them per product. A second CTE ranks the products within each category. The outer query keeps rnk <= 2.
Step through it for two categories before you run it on all of them.
Top two per category, on Fashion and Books
Products of the Fashion and Books categories are split into two windows, sorted by units sold, ranked, and filtered to rank 2 or better; Fashion keeps three rows because two products tie on 20 units.
Partition.
PARTITION BY categorysplits the rows into one window per category. Inside a window the rows are in no order yet.Order.
ORDER BY units DESCsorts each window on its own, best seller first.Rank.
RANK()writes each row's place in its own window. The Linen Shirt and the Canvas Tote both sold 20, so they share place 2, and place 3 is skipped.Filter. The outer query keeps
rnk <= 2. Books keeps two rows. Fashion keeps three, because of the tie.
Each press of Next step is one clause of the query below: PARTITION BY, ORDER BY, RANK(), then the outer WHERE.
The two best sellers per category
WITH units AS (
SELECT p.category, p.product_id, p.name, SUM(i.qty) AS units
FROM order_items i
JOIN products p ON p.product_id = i.product_id
GROUP BY p.category, p.product_id, p.name
),
ranked AS (
SELECT *,
RANK() OVER (PARTITION BY category ORDER BY units DESC) AS rnk
FROM units
)
SELECT category, name, units, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY category, rnk, name;
Fifteen rows. Two per category, three for Fashion and for Home (ties for second place), and one for the gift card, whose NULL category forms a window of its own.
The trap: ROW_NUMBER without a tie-breaker is a coin toss. When two rows tie on the ORDER BY, the database may return them in either order, and that can change between runs or after a table is rewritten. Tests pass on Monday and fail on Thursday. Add a unique column at the end: ORDER BY units DESC, product_id.
Try it: the rank straight in WHERE
SELECT name, price
FROM products
WHERE ROW_NUMBER() OVER (ORDER BY price DESC) = 1;
The rank sits in a CTE above. Why not put it straight in WHERE? Run this. Postgres stops with an error: window functions are not allowed in WHERE.
Why the rank needs a subquery
That error has a plain cause. SQL works out a query in a fixed order: FROM, WHERE, GROUP BY, HAVING, then the window functions, then SELECT, ORDER BY and LIMIT. Window functions are computed after WHERE has finished. Inside WHERE the rank does not exist yet, and Postgres stops with an error.
So the inner query computes the rank and the outer query filters it. Snowflake, BigQuery, Databricks and DuckDB add a shortcut called QUALIFY: a filter that runs after the window functions. Postgres does not have it.
The same top-N in DuckDB, with QUALIFY
import duckdb
rows = duckdb.sql("""
SELECT p.category, p.name, SUM(i.qty) AS units
FROM 'data/order_items.csv' i
JOIN 'data/products.csv' p ON p.product_id = i.product_id
WHERE p.category IS NOT NULL
GROUP BY p.category, p.name
QUALIFY RANK() OVER (PARTITION BY p.category ORDER BY SUM(i.qty) DESC) = 1
ORDER BY p.category
""").fetchall()
for category, name, units in rows:
print(category, name, units)
QUALIFY filters on the window result without a subquery. You will write it often in Databricks and Snowflake, so know both forms.
Under the hood: sort once, walk once
How does Postgres work out a rank? The way you would on paper: sort the list, walk down it once, and write a place next to each line. A line with the same score as the one above gets the same place.
Postgres puts a Sort on the PARTITION BY columns followed by the ORDER BY columns. Then a step called WindowAgg walks the sorted rows once. A new window starts when the partition key changes. RANK only compares each row with the one before it, so it needs almost no memory beyond the sort. Rows that are equal on the ORDER BY are called peers.
Since Postgres 15 a filter like rnk <= 2 is pushed into the WindowAgg as a Run Condition: once a window's rank passes 2, the rest of that window is skipped.
A window in the plan, and two windows
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT category, name, price, rnk
FROM (
SELECT category, name, price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS rnk
FROM products
) ranked
WHERE rnk <= 2;
-- two different windows: two sorts
EXPLAIN (COSTS OFF)
SELECT name,
ROW_NUMBER() OVER (ORDER BY price) AS cheapest_first,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS in_category
FROM products;
The first plan shows Run Condition: (rank() OVER w1 <= 2) inside the WindowAgg, above a Sort on category, price DESC. The second query asks for two different windows, so its plan stacks two WindowAgg steps, each over its own Sort. Functions with the same OVER (...) share one.
Two windows, two sorts
A plan tree read from the bottom: a sequential scan of products, a sort by category and price descending, the first window, a second sort by price, and the second window on top.
Read it from the bottom up: scan, sort, first window, sort again, second window. On 20 products nobody notices. On 200 million events, each extra window order is another full sort.
Top N overall needs no full sort
Your first try, ORDER BY ... LIMIT 2, was the wrong query for this request. It is still worth a look, because Postgres runs it cleverly.
Under a Limit, Postgres does not sort everything. It keeps a small pile of the best N rows seen so far, called a heap, and drops every other row as it reads. EXPLAIN calls this a top-N heapsort. Memory is N rows, whatever the table size.
On 100,000 generated orders, LIMIT 10 sorted in Memory: 17kB. Without the limit, the same sort did not fit in the default work_mem of 4 MB and went to disk.
Top N per group has no such shortcut. Every row is sorted, and the Run Condition then cuts each window short.
LIMIT changes the sort
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, amount
FROM big_orders
ORDER BY amount DESC, order_id
LIMIT 10;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, amount
FROM big_orders
ORDER BY amount DESC, order_id;
SET work_mem = '16MB';
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT order_id, amount
FROM big_orders
ORDER BY amount DESC, order_id;
Three Sort Method lines: top-N heapsort, external merge and quicksort. A sort that does not fit writes sorted runs to temporary files and merges them, which is why its size on disk differs from its size in memory.
Sorting 100,000 orders
Bars compare the memory of a top-10 heapsort, 17 kB, with a full in-memory sort, 5,173 kB, and the temporary files of the same sort when it spills, 2,064 kB.
Compare the first bar with the other two: ten rows in a heap, against every row in memory or on disk. Measured in this browser's Postgres; a 64-bit server needs more bytes per row, but the shape is the same.
Numbers to remember
| What | Number or name | What it means |
|---|---|---|
| LIMIT 10 on 100,000 rows | top-N heapsort Memory: 17kB | Only the best 10 rows are ever kept |
| The full sort at the default workmem of 4 MB | external merge Disk: 2064kB | It did not fit, so sorted runs went to temporary files |
| The full sort kept in memory | 5,173 kB, with workmem = 16MB | quicksort: what the same rows need in memory |
| Run Condition | Since Postgres 15 | A filter such as rnk <= 2 stops each window early. Before that, every row was numbered and most were thrown away |
| One OVER (...) | One Sort and one WindowAgg | Each different window adds another full sort. An index in the same order can deliver the rows sorted, and the Sort disappears (Lesson 2.4) |
| QUALIFY | Snowflake, BigQuery, Databricks, DuckDB | A filter that runs after the window functions. Postgres has none: use a CTE or a subquery |
| The same pattern in PySpark | Window.partitionBy("category").orderBy(F.desc("units")) with F.rank() | You write this twin in Module 11 |
What changed at SwiftKart
Merchandising gets its list before five: fifteen rows, two per category, and three where two products tie for second place. They asked for both products in a tie, so RANK was the right function, and the three Fashion rows are not a bug.
You also know what the answer costs: one sort per window, and a cheap shortcut when the question is the top N of a whole table.
ROW_NUMBER has one more job, and it is the most common one in pipelines. The landing table for orders holds 150 rows for 80 orders, because the same order arrives night after night. Lesson 2.4 keeps only the latest row of each.
In one line
ROW_NUMBER gives exactly N rows (add a tie-breaker), RANK shares a place and skips, DENSE_RANK shares with no gap; rank in a CTE and filter outside, because windows run after WHERE.
Interview corner
What is the difference between ROW_NUMBER, RANK and DENSE_RANK?
All three number rows in window order. ROW_NUMBER always gives 1, 2, 3 even on ties, so ties are broken arbitrarily unless you add a tie-breaker. RANK gives tied rows the same number and then skips (1, 1, 3); DENSE_RANK gives tied rows the same number with no gap (1, 1, 2).
How do you find the second-highest salary in each department?
Rank inside a CTE with DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) and keep rank 2 in the outer query. DENSE_RANK handles a tie at the top correctly; I would confirm with the interviewer whether they want the second distinct salary or the second person.
Why can't you use a window function in WHERE?
Because SQL evaluates WHERE before window functions are computed, so the value does not exist yet. Compute it in a subquery or CTE and filter outside. Engines such as Snowflake, BigQuery, Databricks and DuckDB offer QUALIFY, which filters after the windows.
What does a window function cost, and how do you make a top-N-per-group query cheaper?
The cost is the sort: the planner sorts by the PARTITION BY and ORDER BY columns, then a WindowAgg walks the rows once, so a 200-million-row table is sorted in full, spilling to disk past work_mem. Each different window spec adds another sort. To make it cheaper: share one window spec, give the query an index on (partition columns, order columns) so the rows arrive sorted, and filter first. Postgres 15 and later push rnk <= N into the WindowAgg as a run condition; a whole-table top N with ORDER BY ... LIMIT is cheaper still, a bounded heap of N rows.