wasAsked.

Dense rank

HCA Healthcare · Role not specified · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

DENSE_RANK() is a window function that assigns a rank to each row within a partition based on an ORDER BY, where tied rows get the same rank and the next rank continues without gaps. Syntax DENSE_RANK() OVER ( [PARTITION BY column, ...] ORDER BY column [ASC | DESC], ... ) Example data — Salaries: 90000, 80000, 80000, 70000 SELECT Name, Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS DenseRank, RANK() OVER (ORDER BY Salary DESC) AS Rank, ROW_NUMBER() OVER (ORDER BY Salary DESC) AS RowNum FROM Employees; Results: - 90000: DenseRank 1, Rank 1, RowNum 1 - 80000: DenseRank 2, Rank 2, RowNum 2 - 80000: DenseRank 2, Rank 2, RowNum 3 - 70000: DenseRank 3, Rank 4, RowNum 4 So DENSE_RANK has no gaps (1, 2, 2, 3), RANK leaves gaps after ties (1, 2, 2, 4), and ROW_NUMBER gives unique numbers regardless of ties. Common use cases Nth highest salary (handles ties correctly): WITH Ranked AS ( SELECT *, DENSE_RANK() OVER (ORDER BY Salary DESC) AS dr FROM Employees ) SELECT * FROM Ranked WHERE dr = 2; -- everyone with the second highest salary Top 3 salaries per department: WITH Ranked AS ( SELECT DepartmentId, Name, Salary, DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS dr FROM Employees ) SELECT * FROM Ranked WHERE dr <= 3; Points to mention - Window functions cannot be used directly in WHERE, because WHERE is evaluated before the SELECT list; wrap them in a CTE or subquery. - PARTITION BY restarts ranking for each group; without it, the whole result set is one partition. - Ties are determined by the ORDER BY columns only. - Performance: an index supporting PARTITION BY and ORDER BY columns (for example (DepartmentId, Salary DESC)) helps avoid expensive sorts.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics