Window Ranking Functions: Choosing the Right One for Top-N Queries
SQL & DataModel answerLast updated
Explain how ROW_NUMBER, RANK, and DENSE_RANK behave differently when ties exist, and which to use depending on what "top N" actually means.
Window Ranking Functions: Choosing the Right One for Top-N Queries
SQL gives you three window functions for ranking rows: ROW_NUMBER, RANK, and DENSE_RANK. They look similar and are often used interchangeably, but they produce meaningfully different results the moment your data has tied values — and even when it doesn't, the right choice depends on what question you're actually trying to answer.
Your task: Explain how each function works, how they differ from one another in the presence and absence of ties, and which function (or combination) is appropriate for each of the following interpretations of "top 3":
- Return exactly 3 rows, one per result, with no duplicates even if scores are tied.
- Return all rows that fall within the first 3 competition ranks (e.g., gold/silver/bronze positions), including all tied rows at the boundary.
- Return all rows that have one of the 3 highest distinct score values, regardless of how many rows share those values.
You do not need to write a complete SQL query with a specific schema. Focus on the conceptual differences, the mechanics of each function, and the trade-offs involved in each choice. Call out common mistakes candidates make when using these functions.
Hints
Hint 1
Think about what happens to the rank counter after a tie in each function — does it skip numbers, repeat numbers, or neither?
Hint 2
For the 'exactly 3 rows' case, consider what additional clause or ordering guarantee you need to make the result deterministic when rows are tied.
Hint 3
DENSE_RANK and RANK both assign the same value to tied rows, but they diverge immediately after the tie — work through a concrete example like scores [100, 100, 90, 80] to see the difference.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
How the Three Functions Work
All three functions are window functions that assign a rank to each row within a partition, ordered by some column (typically a score or date). The difference is entirely in how they handle ties and how they advance the counter afterward.
ROW_NUMBER assigns a strictly unique, sequential integer to every row. No two rows ever share a number. If two rows are tied on the ORDER BY column, the function still assigns them different numbers — but which row gets which number is arbitrary unless you include a tiebreaker column in the ORDER BY clause.
RANK assigns the same number to all rows that are tied, then skips ahead. If two rows tie for position 2, both get rank 2, and the next row gets rank 4. The "gap" reflects the number of rows that shared the prior rank.
DENSE_RANK also assigns the same number to tied rows, but does not skip. Two rows tied at position 2 both get rank 2, and the next distinct value gets rank 3. The rank sequence is always contiguous.
A concrete example makes this clear. Given scores [100, 100, 90, 80]:
| Score | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 100 | 2 | 1 | 1 |
| 90 | 3 | 3 | 2 |
| 80 | 4 | 4 | 3 |
Matching the Function to the Business Question
"Return exactly 3 rows" → use ROW_NUMBER
Filter with WHERE row_number <= 3. You'll always get exactly 3 rows. The critical caveat: if tied rows exist at the boundary (e.g., two rows share the 3rd-place score), the result is non-deterministic unless your ORDER BY includes a unique tiebreaker like a primary key. Without one, repeated executions may return different rows. This is the most common mistake — using ROW_NUMBER without a tiebreaker and assuming the output is stable.
"Return all rows within the top 3 competition ranks" → use RANK
Filter with WHERE rank <= 3. If three rows tie for rank 1, all three are returned and rank 4 onward is excluded. The gap in rank numbers is intentional: it signals that positions 2 and 3 were "used up" by the tie. This matches leaderboard semantics where a four-way tie for first means nobody finishes second.
"Return all rows with one of the top 3 distinct score values" → use DENSE_RANK
Filter with WHERE dense_rank <= 3. This guarantees you see every row whose score belongs to the three highest unique score levels. With scores [100, 100, 90, 80], all four rows are returned because 80 is the 3rd distinct value. RANK would exclude the 80-row because its rank is 4 (due to the gap), which is the key behavioral difference between the two.
Common Mistakes
Treating ROW_NUMBER as a stable sort without a tiebreaker. SQL does not guarantee row order beyond what the ORDER BY specifies. If two rows have identical ORDER BY values, ROW_NUMBER can assign them either way. Always add a unique column (like an ID) as the final tiebreaker when you need determinism.
Confusing RANK and DENSE_RANK at the boundary. The difference only appears after a tie. Before any tie occurs, all three functions return the same values. Candidates often say "RANK and DENSE_RANK are the same" without realizing they diverge on the row immediately following tied rows.
Using RANK when the requirement is "top 3 score levels." If the data has many ties at rank 1, filtering rank <= 3 can still exclude rows that have the 3rd distinct score value. DENSE_RANK is the right tool there.
Forgetting that all three require a PARTITION BY clause in grouped contexts. If you're ranking within categories (e.g., top scores per department), omitting PARTITION BY causes the function to rank across the entire result set, which is almost never what you want.
When to Use Each
| Need | Function |
|---|---|
| Paginate results, always return exactly N rows | ROW_NUMBER (with tiebreaker) |
| Leaderboard with shared podium positions | RANK |
| Top N distinct score/value levels | DENSE_RANK |
The choice is driven by the semantic contract you're promising downstream: a fixed row count, a competition-style rank, or a value-level cutoff.