6.2 Ranking: ROW_NUMBER() vs RANK() vs DENSE_RANK() & Top-N Per Group
Master the #1 most-asked SQL interview pattern: exact differences between ROW_NUMBER(), RANK(), and DENSE_RANK() on ties, Top-3 salaries per department, and deduplicating dirty tables.
1. ROW_NUMBER() vs RANK() vs DENSE_RANK() — Memorize This Table!
Suppose 4 students have scores: 96, 92, 92, 88 (notice the tie at 92!). Look at how the 3 ranking functions behave:
| Student | Score | ROW_NUMBER() | RANK() | DENSE_RANK() |
|---|---|---|---|---|
| Meera | 96 | 1 | 1 | 1 |
| Aarav | 92 | 2 | 2 | 2 |
| Riya | 92 | 3 | 2 | 2 |
| Kabir | 88 | 4 | 4 (skips 3!) | 3 (no gap!) |
ROW_NUMBER(): Always assigns unique sequential integers1, 2, 3, 4— breaks ties arbitrarily unless you add a tie-breaker inORDER BY! Best for deduplication & strict pagination.RANK(): Olympic medal ranking — tied rows share the same rank (2, 2), and the next rank skips (4).DENSE_RANK(): Tied rows share the same rank (2, 2), and the next rank has no gap (3). Best for "2nd / 3rd highest distinct salary"!
2. The #1 FAANG SQL Interview Pattern: Top-N Per Group!
"Find the Top 2 highest-paid employees in each department (including ties)."
Pattern: CTE + DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) + outer WHERE rnk <= 2:
WITH ranked_employees AS (
SELECT
dept,
name,
salary,
DENSE_RANK() OVER (
PARTITION BY dept
ORDER BY salary DESC
) AS salary_rank
FROM employees
)
SELECT dept, name, salary, salary_rank
FROM ranked_employees
WHERE salary_rank <= 2
ORDER BY dept ASC, salary_rank ASC;
Watch ROW_NUMBER() vs DENSE_RANK() Execute Live
| dept | name | salary |
|---|---|---|
| Eng | Kabir | 160k |
| Eng | Aarav | 140k |
| Eng | Dev | 140k |
| Eng | Zoya | 110k |
| Sales | Riya | 100k |
3. Classic Production Pattern: Keep Only the Latest Record Per User (Deduplication)
Suppose an event log has multiple rows per user_id and you only want each user's most recent login:
WITH latest_logins AS (
SELECT
user_id,
ip_address,
logged_in_at,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY logged_in_at DESC
) AS rn
FROM login_events
)
SELECT user_id, ip_address, logged_in_at
FROM latest_logins
WHERE rn = 1;
4. Quick Check Your Understanding
Module 6.2 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.