DENSE_RANK() in SQL
Assigns a rank to rows within a result set partition, with no gaps in rank numbers when ties occur.
Syntax
Return type
DENSE_RANK() Function Example
What is DENSE_RANK() in SQL?
The DENSE_RANK()
function in SQL assigns a rank to each row within a result set partition, ensuring that tied values receive the same rank but without gaps in the ranking sequence. Unlike RANK()
, which skips numbers after ties, DENSE_RANK()
assigns the next consecutive rank.
This function is useful for ranking data in competitions, performance metrics, and percentile-based analysis. It is supported in SQL Server, PostgreSQL, Oracle, and MySQL 8.0+ as a window function.
DENSE_RANK()
is widely used in grading systems, sales leaderboards, and percentile-based reporting.
Parameters:
PARTITION BY (optional): Columns to partition the rows
ORDER BY (required): Columns that determine the ranking order
Example Use Cases:
-- Student grade rankings
-- Sales rankings by region
-- Product rankings by category
Notes:
Behavior: Equal values receive same rank, next rank is consecutive
Performance Considerations: May require window function optimization
Version Info: Core window function available in most modern DBMS
Deprecated/Recommended Alternatives: Consider RANK() if gaps desired
Error Handling:
Error: Syntax error if ORDER BY is omitted
Recommendation: Always include ORDER BY clause
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked together
PostgreSQL
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked last by default
SQL Server
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked last by default
SQLite
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked together
BigQuery
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked together
Snowflake
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked last by default
Athena
DENSE_RANK()
DENSE_RANK() OVER (ORDER BY col)
NULLs ranked last by default