Sub topic 5
Ranking rows: ROW_NUMBER, RANK and DENSE_RANK
This chapter assumes you can write SELECT, WHERE, ORDER BY and GROUP BY queries. It also assumes you can use a common table expression (CTE) and have read the earlier chapters on the OVER clause, PARTITION BY and window ORDER BY. The examples run on PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+ and Oracle. Only the CREATE TABLE types and a few NULL-handling details differ.
What a ranking function does
A ranking function assigns each row a number based on its position in the window's ORDER BY. Each row keeps its own output row, as with every window function. The three functions differ only in how they number rows that tie, meaning rows whose ORDER BY values are equal. SQL calls these rows peers.
ROW_NUMBER()gives every row a unique number. Ties are split arbitrarily.RANK()gives peers the same number, then skips numbers to account for them.DENSE_RANK()gives peers the same number and never skips.
All three take no arguments and cannot use a frame clause. A frame is the set of rows around the current row that an aggregate would read. Ranking depends only on partition and order.
Sample data
The examples use this table. Region East has a tie at 700, and region West has a three-way tie at 400.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(10),
salesperson VARCHAR(20),
amount INTEGER
);
INSERT INTO sales (id, region, salesperson, amount) VALUES
(1, 'East', 'Ana', 500),
(2, 'East', 'Ben', 700),
(3, 'East', 'Cara', 700),
(4, 'East', 'Dev', 300),
(5, 'West', 'Eli', 900),
(6, 'West', 'Fay', 400),
(7, 'West', 'Gus', 400),
(8, 'West', 'Hal', 400);Comparing the three functions
This query ranks all eight sales by amount, highest first.
SELECT
salesperson,
amount,
ROW_NUMBER() OVER (ORDER BY amount DESC, id) AS row_num,
RANK() OVER (ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY amount DESC) AS dense_rnk
FROM sales
ORDER BY amount DESC, id;| salesperson | amount | row_num | rnk | dense_rnk |
|---|---|---|---|---|
| Eli | 900 | 1 | 1 | 1 |
| Ben | 700 | 2 | 2 | 2 |
| Cara | 700 | 3 | 2 | 2 |
| Ana | 500 | 4 | 4 | 3 |
| Fay | 400 | 5 | 5 | 4 |
| Gus | 400 | 6 | 5 | 4 |
| Hal | 400 | 7 | 5 | 4 |
| Dev | 300 | 8 | 8 | 5 |
Two counting rules explain the output:
RANKequals 1 plus the number of rows that sort strictly before the current row. Ana has three rows ahead of her (Eli, Ben, Cara), so her rank is 4. Dev has seven rows ahead, so his rank is 8.DENSE_RANKequals 1 plus the number of distinctORDER BYvalues that sort before the current row. Ana has three distinct values ahead (900, 700, and the tie counts once), so... precisely, two distinct values (900 and 700) precede 500, so her dense rank is 3.
ROW_NUMBER ignores ties and just counts position.
The outer ORDER BY is separate from the ORDER BY inside OVER. The window's order decides the numbering. The outer order only decides how the result is displayed.
Choosing a function
Use these rules of thumb:
- Use
ROW_NUMBERwhen you need exactly N rows, when you want to pick one row per group, or when you need a unique key for a result set. - Use
RANKwhen the position should reflect how many rows are ahead. Two people tied for second place mean nobody is third. - Use
DENSE_RANKwhen you want "the second-highest value" regardless of how many rows hold the highest. For example, the second-highest salary is the row withDENSE_RANK() = 2. - Use
NTILEto split rows into equal-sized buckets rather than number them. It is covered in a later chapter withPERCENT_RANKandCUME_DIST.
Ranking within groups
Adding PARTITION BY restarts the numbering for each group.
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, id) AS row_num,
RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS dense_rnk
FROM sales
ORDER BY region, amount DESC, id;| region | salesperson | amount | row_num | rnk | dense_rnk |
|---|---|---|---|---|---|
| East | Ben | 700 | 1 | 1 | 1 |
| East | Cara | 700 | 2 | 1 | 1 |
| East | Ana | 500 | 3 | 3 | 2 |
| East | Dev | 300 | 4 | 4 | 3 |
| West | Eli | 900 | 1 | 1 | 1 |
| West | Fay | 400 | 2 | 2 | 2 |
| West | Gus | 400 | 3 | 2 | 2 |
| West | Hal | 400 | 4 | 2 | 2 |
Each region is numbered independently, and ties are only compared inside a partition. Ben's 700 in East has no effect on West.
Ties and determinism
ROW_NUMBER must give tied rows different numbers, but the standard does not say which row gets which. If you write ROW_NUMBER() OVER (ORDER BY amount DESC), Ben and Cara could swap numbers between runs. A changed plan, an added index or a different parallel worker count can all cause this. The query is valid, but its result is not stable.
Add a tie-breaker to the window ORDER BY, ideally a unique column such as the primary key:
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, id)RANK and DENSE_RANK do not have this problem for the rank number itself, because peers get the same value by definition. Adding a tie-breaker to them is a mistake. It makes the rows no longer peers, so RANK behaves like ROW_NUMBER.
Filtering on a rank
A window function cannot appear in WHERE, because WHERE runs before windows are computed. Compute the rank in a CTE or subquery, then filter in the outer query. This query returns the top two sales per region, with ties kept.
WITH ranked AS (
SELECT
region,
salesperson,
amount,
RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS rnk
FROM sales
)
SELECT region, salesperson, amount, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY region, rnk, salesperson;This returns Ben and Cara for East, and Eli, Fay, Gus and Hal for West. That is six rows, because RANK keeps every row tied at rank 2. Switching to ROW_NUMBER() ... ORDER BY amount DESC, id returns exactly four rows: Ben, Cara, Eli and Fay. Which result is correct depends on the question:
| Requirement | Function | Filter | Rows returned |
|---|---|---|---|
| Exactly two rows per region | `ROW_NUMBER` | `rn <= 2` | 4 |
| Everyone in the top two positions, ties included | `RANK` | `rnk <= 2` | 6 |
| Everyone with one of the top two distinct amounts | `DENSE_RANK` | `dense_rnk <= 2` | 7 |
For DENSE_RANK, East keeps 700 and 500 (three rows), and West keeps 900 and 400 (four rows).
Picking one row per group
ROW_NUMBER with a filter on 1 is the standard way to keep one row per group, such as the largest sale in each region. Here the tie-breaker decides which row wins when amounts are equal.
WITH ranked AS (
SELECT
region,
salesperson,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, id) AS rn
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn = 1;East returns Ben, because Ben's id of 2 is lower than Cara's 3. Choose the tie-breaker deliberately. If "latest wins" is the rule, order by the date descending and then by id descending.
NULLs and ordering
NULL values in the window ORDER BY are treated as peers of each other, so RANK gives all NULLs the same number. Where NULLs sort differs by database:
- PostgreSQL and Oracle treat NULL as larger than any value, so NULLs come first in a descending order.
- MySQL, SQL Server and SQLite treat NULL as smaller than any value, so NULLs come last in a descending order.
You can control placement with NULLS FIRST or NULLS LAST in PostgreSQL, Oracle and SQLite 3.30+. MySQL and SQL Server do not support it. There you can sort on an expression first, for example ORDER BY CASE WHEN amount IS NULL THEN 1 ELSE 0 END, amount DESC. Without this, a NULL amount could take rank 1 in PostgreSQL.
Common mistakes
- Filtering the rank in
WHERE. The database reports that window functions are not allowed there. Move the ranking into a CTE. - Omitting the window
ORDER BY. Some databases, including SQL Server, reject ranking functions without it. Others accept it and return arbitrary or all-equal numbers. - Expecting
ROW_NUMBERto be stable without a unique tie-breaker. - Using
RANKfor "top N rows" and getting more than N back because of ties. - Assuming the outer
ORDER BYaffects the numbering. It only sorts the final output.
Exercise
Using the sales table, write a query that returns the second-highest distinct amount in each region, along with every salesperson who has it. For the sample data, what rows does it return?
Show answer
Use DENSERANK so that ties on the top amount do not consume rank 2. WITH ranked AS ( SELECT region, salesperson, amount, DENSERANK() OVER (PARTITION BY region ORDER BY amount DESC) AS dr FROM sales ) SELECT region, salesperson, amount FROM ranked WHERE dr = 2; For the sample data this returns Ana (East, 500), and Fay, Gus and Hal (West, 400). RANK would return Ana with rank 3 and no East row for rank 2, because Ben and Cara both hold rank 1 and rank 2 is skipped.
Exercise
A query uses ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) to keep the top row per region. It returns Ben for East on Monday and Cara on Tuesday, with no data changes. Why, and how do you fix it?
Show answer
Ben and Cara both have amount 700, and ROW_NUMBER must separate them without any rule for which comes first. The database can choose either order, and a different plan or run can change it. Add a unique tie-breaker to the window ORDER BY, for example ORDER BY amount DESC, id, so the result is the same every time.