Reference / SQL
DENSE_RANK()
Returns the rank of each row within a partition of a result set, without gaps in the ranking values for tied records.
Syntax
DENSE_RANK() OVER ([PARTITION BY partition_col] ORDER BY sort_col [ASC|DESC])Parameters
| Name | Type | Description |
|---|---|---|
| PARTITION BY | clause | Divides rows into groups. |
| ORDER BY | clause | Specifies the ranking order. |
Examples
Top 3 salaries per department
WITH ranked AS (
SELECT name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rank
FROM employees
)
SELECT * FROM ranked WHERE rank <= 3;Unlike RANK(), DENSE_RANK() does not skip rank numbers after duplicate values.