wasAsked.

Difference between ROW_NUMBER() and DENSE_RANK()?

Impetus · Role not specified · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

Both are ranking window functions, but they treat ties differently. ROW_NUMBER() - Assigns a unique sequential number to every row in the partition: 1, 2, 3, 4... - Rows with equal ORDER BY values still get different numbers; which tied row gets which number is arbitrary unless you add a tie-breaker column. DENSE_RANK() - Rows with equal ORDER BY values get the same rank. - The next distinct value gets the next consecutive rank, with no gaps: 1, 2, 2, 3. Example: scores 100, 95, 95, 90 SELECT Player, Score, ROW_NUMBER() OVER (ORDER BY Score DESC) AS RowNum, DENSE_RANK() OVER (ORDER BY Score DESC) AS DenseRnk FROM Scores; - 100: RowNum 1, DenseRnk 1 - 95: RowNum 2, DenseRnk 2 - 95: RowNum 3, DenseRnk 2 - 90: RowNum 4, DenseRnk 3 (RANK() would give 1, 2, 2, 4 — ties share a rank and the next rank skips.) When to use ROW_NUMBER - Removing duplicates: keep rn = 1 per group and delete the rest. - Pagination (WHERE rn BETWEEN 21 AND 40), though OFFSET/FETCH is more common now. - Picking exactly one row per group, such as the latest order per customer: WITH Latest AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY OrderDate DESC, OrderId DESC) AS rn FROM Orders ) SELECT * FROM Latest WHERE rn = 1; When to use DENSE_RANK - Nth highest value problems where ties should count as one position (second highest salary, including everyone tied at that salary). - Top-N distinct values per group, such as the top 3 price levels per category. - Leaderboards where tied players share a position and the next position follows immediately. Key points - Both require ORDER BY in the OVER clause; PARTITION BY is optional and restarts numbering per group. - Add a unique tie-breaker to ROW_NUMBER's ORDER BY when deterministic results matter. - Filter on these functions in an outer query or CTE, since window functions cannot appear in WHERE.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics