KatInterview

Window Ranking Functions: Choosing the Right One for Top-N Queries

SQL & DataModel answer
MediumModel answerSQL & Datawindow-functionsrankingties

Last 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":

  1. Return exactly 3 rows, one per result, with no duplicates even if scores are tied.
  2. Return all rows that fall within the first 3 competition ranks (e.g., gold/silver/bronze positions), including all tied rows at the boundary.
  3. 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.