Stop 08 · Window FunctionsTopics · 4/9

RANK vs DENSE_RANK

Part of the SQL Roadmap

In short

When two students score the same marks, who is second? Your answer changes the whole list. RANK and DENSE_RANK are two fair ways to handle ties, and picking the right one matters.

Both give tied rows the same rank. RANK then skips numbers (1, 1, 3) while DENSE_RANK does not (1, 1, 2).

The jaadu pins paper cards onto a school corkboard, placing two cards side by side on the same step of a staircase drawing while classmates crowd around.

Think of it like this

The merit list on the notice board

A Jaipur school pins its merit list. Two students tie at 92 and both are listed 2nd. Is the next student 3rd or 4th? RANK says 4th, because three people scored higher. DENSE_RANK says 3rd, because only two distinct scores are higher. Both are correct, they just answer different questions.

Watch it happen

Same marks, three numbering styles

95
0
92
1
92
2
88
3
85
4

1/4Five students sorted by marks, highest first. Two are tied at 92.

The big ideas

What you need to know

Ties share a number

Both RANK and DENSE_RANK give equal values the same rank. Only ROW_NUMBER forces them apart.

RANK leaves gaps

After a two-way tie at 2, RANK jumps to 4. It's like sports rankings.

DENSE_RANK has no gaps

After a tie at 2, DENSE_RANK goes to 3. Great for 'top 3 price levels' style questions.

Ask what 'top 3' means

Top 3 students, or top 3 scores? The answer tells you which function to use.

See it in code

Walk through the code

sql
1SELECT2  student_name,3  marks,4  ROW_NUMBER() OVER (ORDER BY marks DESC) AS row_num,5  RANK()       OVER (ORDER BY marks DESC) AS rnk,6  DENSE_RANK() OVER (ORDER BY marks DESC) AS dense_rnk7FROM exam_results8WHERE exam = 'Class 12 Physics'9ORDER BY marks DESC;

1/4Unique numbers, ties broken arbitrarily.

All three side by side so you can see the difference on tied marks. The same syntax works in PostgreSQL, MySQL 8+ and SQL Server.

Save yourself the pain

Common mistakes

Oops

Using RANK for "the top 3 price levels" and getting only two levels back because of a skipped number.

Do this instead

Use DENSE_RANK when you mean the top 3 distinct values.

Oops

Naming a column rank without thinking.

Do this instead

RANK is a keyword in some databases. Use names like rnk or marks_rank to stay safe.

Your mission

Rank your own class

~15 min

Quick check

Marks are 90, 90 and 85. What does RANK() give the student with 85?

Go deeper

  1. 1Rank students by marks with ROW_NUMBER, RANK and DENSE_RANK side by side.
  2. 2Decide which one fits 'top 3 distinct scores' questions.
  3. 3Practise explaining the difference in one sentence for interviews.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge