SQL ROW_NUMBER, RANK and DENSE_RANK
ROW_NUMBER, RANK and DENSE_RANK number rows in an order you choose. They differ only in how they handle ties, which matters for questions like “second-highest salary”.
Updated December 1, 2026
Syntax
ROW_NUMBER() OVER (PARTITION BY group_column ORDER BY sort_column)
See the difference on ties
Ravi and Sofia both earn $120,000. ROW_NUMBER still gives them different numbers (6 and 7). RANK ties them at 6 and skips 7, so Ben is 8th. DENSE_RANK ties them at 6 without a gap, so Ben is 7th.
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
ORDER BY salary DESC, name;
| name | salary | row_num | rnk | dense_rnk |
|---|---|---|---|---|
| Omar Haddad | 215000 | 1 | 1 | 1 |
| Maya Chen | 210000 | 2 | 2 | 2 |
| Jack Miller | 160000 | 3 | 3 | 3 |
| Lena Park | 150000 | 4 | 4 | 4 |
| Diego Alvarez | 130000 | 5 | 5 | 5 |
| Ravi Patel | 120000 | 6 | 6 | 6 |
| Sofia Rossi | 120000 | 7 | 6 | 6 |
| Ben Okafor | 98000 | 8 | 8 | 7 |
Top item in each group
Number rows within each group with PARTITION BY, then keep row 1: the most expensive product in each category. This “top N per group” pattern comes up constantly at work and in interviews.
WITH ranked AS (
SELECT category, name, price,
ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
FROM products
)
SELECT category, name, price
FROM ranked
WHERE rn = 1
ORDER BY category;
| category | name | price |
|---|---|---|
| electronics | Monitor 27" | 249 |
| office | Office Chair | 199 |
| stationery | Notebook (3-pack) | 9 |
Common mistakes
- Filtering
WHERE ROW_NUMBER() ... = 1directly. Window functions can’t go inWHERE; use a CTE or subquery. - Using
ROW_NUMBERwhen ties should share a place. UseRANKorDENSE_RANK. - Forgetting a tie-breaker in
ORDER BY, so tied rows get numbers in an unpredictable order.
Practice ROW_NUMBER, RANK and DENSE_RANK interactively
Write real queries in your browser and get instant feedback in the lesson “ROW_NUMBER and RANK” (Unit 8). New learners can start free from the first lesson.
Frequently asked questions
How do I find the second-highest salary?
Use DENSE_RANK() OVER (ORDER BY salary DESC) in a CTE and keep rank 2. DENSE_RANK handles ties correctly, unlike LIMIT 1 OFFSET 1.
RANK vs DENSE_RANK?
After a tie for 4th, RANK jumps to 6 and DENSE_RANK continues at 5.