SQL · Module 9 · Lesson 21 min read

Ranking: ROW_NUMBER, RANK & DENSE_RANK

All ranking functions need ORDER BY inside OVER.

The three main ranking functions

For amounts 900, 800, 800, 700:

FunctionResultRule
row_number()1, 2, 3, 4always unique (ties broken arbitrarily)
rank()1, 2, 2, 4ties share a rank, then gaps
dense_rank()1, 2, 2, 3ties share a rank, no gaps

Which one?

  • row_number – pick exactly one row per group (latest, biggest), pagination, deduplication
  • rank – sports-style leaderboards ("joint 2nd, then 4th")
  • dense_rank – "the 2nd highest value" questions (interview classic)

⚠️ With row_number and ties, add a tie-breaker to make it deterministic: ORDER BY amount DESC, id

PARTITION BY = ranking within groups

row_number() OVER (PARTITION BY user_id ORDER BY amount DESC) → numbering restarts at 1 for each user.

Other ranking functions

  • ntile(4) – split rows into 4 roughly equal buckets (quartiles)
  • percent_rank() – relative rank from 0 to 1
  • cume_dist() – the fraction of rows ≤ this one

Top-N per group pattern ⭐

SQL
WITH ranked AS (
  SELECT *, row_number() OVER (PARTITION BY user_id ORDER BY amount DESC) AS rn
  FROM expenses
)
SELECT * FROM ranked WHERE rn <= 3;

(You can't use rn in WHERE in the same query — hence the CTE.)

Example

SQL
-- Compare the three functions on tied values
SELECT title, amount,
       row_number() OVER (ORDER BY amount DESC) AS row_num,
       rank()       OVER (ORDER BY amount DESC) AS rnk,
       dense_rank() OVER (ORDER BY amount DESC) AS dense
FROM expenses
WHERE amount BETWEEN 1200 AND 1700
ORDER BY amount DESC;
--  Electricity bill 1620 | 1 | 1 | 1
--  Internet bill    1500 | 2 | 2 | 2
--  Internet bill    1500 | 3 | 2 | 2   ← tie
--  Electricity bill 1350 | 4 | 4 | 3   ← rank() skips 3, dense_rank() doesn't
--  Dinner           1250 | 5 | 5 | 4
--  Bike service     1200 | 6 | 6 | 5

-- Leaderboard: users ranked by total spending
SELECT u.name, sum(e.amount) AS total,
       rank() OVER (ORDER BY sum(e.amount) DESC) AS position
FROM expenses e JOIN users u ON u.id = e.user_id
GROUP BY u.name;

-- Top 2 expenses per user ⭐
WITH ranked AS (
  SELECT user_id, title, amount,
         row_number() OVER (PARTITION BY user_id ORDER BY amount DESC, id) AS rn
  FROM expenses
)
SELECT user_id, rn, title, amount
FROM ranked
WHERE rn <= 2
ORDER BY user_id, rn;

-- Latest expense per user
SELECT user_id, title, spent_on FROM (
  SELECT *, row_number() OVER (PARTITION BY user_id ORDER BY spent_on DESC, id DESC) AS rn
  FROM expenses
) t WHERE rn = 1;

-- Quartiles: split expenses into 4 size buckets
SELECT title, amount, ntile(4) OVER (ORDER BY amount) AS quartile
FROM expenses
WHERE user_id = 1
ORDER BY amount;