SpinTheMic
Pro

SQL · Intermediate

What is the difference between ROW_NUMBER, RANK and DENSE_RANK?

By Anurag Pandey, Lead Data Engineer ·

The short answer

They differ only on ties. For scores 100, 90, 90, 80: ROW_NUMBER gives 1, 2, 3, 4; RANK gives 1, 2, 2, 4, leaving a gap; DENSE_RANK gives 1, 2, 2, 3, with no gap.

Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Say it like this

About 50 seconds out loud. Use it as a model, then put it in your own words.

All three are window functions that number rows in the order I give in the OVER clause, and they only differ when there are ties. Say four people scored 100, 90, 90 and 80. ROW_NUMBER gives every row a unique number: 1, 2, 3, 4. The two people on 90 get 2 and 3, and which one gets which isn't guaranteed unless I add a tie-breaker to the ORDER BY. RANK gives tied rows the same rank and then skips: 1, 2, 2, 4. DENSE_RANK also gives ties the same rank but doesn't skip: 1, 2, 2, 3. In practice, I use ROW_NUMBER to remove duplicates, keeping row number 1 per key. I use DENSE_RANK for questions like the second-highest salary, where ties should count as one value.

What interviewers look for

  • You use a concrete tie example and get the numbers right.
  • You know ROW_NUMBER is not deterministic on ties without a tie-breaker.
  • You give a real use for each, like deduplication or top-N.

Common mistakes

  • Mixing up which of RANK and DENSE_RANK leaves gaps.
  • Using ROW_NUMBER for top-N with ties and silently dropping tied rows.
  • Forgetting PARTITION BY when the ranking should restart per group.

Follow-up questions to expect

  1. 1How would you find the second-highest salary in each department?
  2. 2How would you remove duplicate rows but keep the latest one?
  3. 3What does NTILE do?
Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Checked against

All interview question guides