Skip to the solution
MediumDSA12 min read

What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?

740 views

The problem

Question presented to candidate: "Walk me through ROW_NUMBER, RANK and DENSE_RANK. If I have scores 95, 90, 90, 85, what does each one return, and why?"

What a strong answer should cover:

  • All three are ranking window functions that number rows inside each partition by the window ORDER BY; they differ only in how they treat ties (rows with equal sort values, called peers)
  • ROW_NUMBER gives every row a distinct number (1, 2, 3, 4) and breaks ties arbitrarily unless the ORDER BY is unique
  • RANK gives peers the same number and then skips (1, 2, 2, 4): rank = 1 + number of rows strictly ahead
  • DENSE_RANK gives peers the same number with no gap (1, 2, 2, 3): dense rank = 1 + number of distinct values strictly ahead
  • PARTITION BY restarts the numbering per group; NULL placement in the sort differs by engine (PostgreSQL puts NULL first in DESC, SQLite last), so say NULLS LAST

Code / implementation expected: Yes β€” one query putting the three side by side over data with ties.

Schema used by the examples:

  • window
  • ranking

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the query and run it against the tables for this question.

SQLThe three functions side by side over class A (ties at 90 and 85)
SQLPARTITION BY class restarts the numbering in each class
SQLWhat RANK and DENSE_RANK count: rows ahead vs distinct values ahead
PostgreSQL: a NULL score ranks first in DESC order unless you say NULLS LAST
SELECT student, score,
       RANK() OVER (ORDER BY score DESC) AS rank_default,
       RANK() OVER (ORDER BY score DESC NULLS LAST) AS rank_nulls_last
FROM exam_scores
WHERE class = 'B'
ORDER BY rank_nulls_last, student;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 39 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextMedium

What is a CTE (Common Table Expression)?

Continue