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;
Result on the Acme Co. (company data) sample data (15 rows, first 8 shown)
namesalaryrow_numrnkdense_rnk
Omar Haddad215000111
Maya Chen210000222
Jack Miller160000333
Lena Park150000444
Diego Alvarez130000555
Ravi Patel120000666
Sofia Rossi120000766
Ben Okafor98000887

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;
Result on the Desk & Co. (online store) sample data (3 rows)
categorynameprice
electronicsMonitor 27"249
officeOffice Chair199
stationeryNotebook (3-pack)9

Common mistakes

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.

Related SQL tutorials