Menu
Coddy logo textTech

RANK & DENSE_RANK Functions

Part of the Fundamentals section of Coddy's SQL journey — lesson 65 of 72.

ROW_NUMBER() is one type of ranking function, and there are two more: RANK() and DENSE_RANK().

The RANK() function numbers rows like ROW_NUMBER(), but it gives identical numbers for the same rows and skips numbers. DENSE_RANK() is similar to RANK(), but it does not skip numbers.

For example:

idlevel
15
26
36
47
57
65
SELECT id, 
	ROW_NUMBER() OVER (ORDER BY level) as row_num,
	RANK() OVER (ORDER BY level) as row_rank,
	DENSE_RANK() OVER (ORDER BY level) as row_dense_rank
FROM table1

This will return:

idrow_numrow_rankrow_dense_rank
1111
6211
2332
3432
4553
5653

Explanation:

  • ROW_NUMBER(): Always unique: 1, 2, 3, 4, 5, 6
  • RANK():
    • level 5 (2 rows): both get rank 1
    • level 6 (2 rows): both get rank 3 (skips 2)
    • level 7 (2 rows): both get rank 5 (skips 4)
  • DENSE_RANK():
    • level 5 (2 rows): both get rank 1
    • level 6 (2 rows): both get rank 2 (no skip)
    • level 7 (2 rows): both get rank 3 (no skip)
challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>medals</strong>: <strong>region</strong>, <strong>medal_color</strong>, <strong>medal_count</strong>

Create a query that shows the region, total medal count (sum of all medals regardless of color), and two types of rankings:

  1. A regular_rank (with gaps) over the sum medals
  2. A dense_rank (without gaps) over the sum of medals

Order result by:

order by total_medals desc, region asc

Cheat sheet

SQL provides three ranking functions that behave differently with tied values:

  • ROW_NUMBER() - assigns unique sequential numbers
  • RANK() - assigns same rank to tied values and skips subsequent ranks
  • DENSE_RANK() - assigns same rank to tied values without skipping ranks

For example:

idlevel
15
26
36
47
57
65
SELECT id, 
	ROW_NUMBER() OVER (ORDER BY level) as row_num,
	RANK() OVER (ORDER BY level) as row_rank,
	DENSE_RANK() OVER (ORDER BY level) as row_dense_rank
FROM table1

This will return:

idrow_numrow_rankrow_dense_rank
1111
6211
2332
3432
4553
5653

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals