RANK() in SQL
Assigns a rank to rows within a result set partition, with gaps in rank numbers when ties occur.
Syntax
Return type
RANK() Function Example
What is RANK() in SQL?
The RANK()
function in SQL assigns a rank to each row within a result set partition, with gaps in rank numbers when ties occur. Unlike ROW_NUMBER()
, which always assigns unique sequential numbers, RANK()
gives the same rank to rows with identical values, leaving gaps in the ranking sequence.
This function is commonly used for ranking results in leaderboards, performance metrics, and statistical analysis. It is supported in SQL Server, PostgreSQL, and Oracle, and available in MySQL 8.0+ as a window function.
RANK()
is widely used in competition ranking, 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:
-- Top performers by department
-- Product ranking by sales
-- Student grades ranking
Notes:
Behavior: Equal values receive same rank, next rank skips
Performance Considerations: May require window function optimization
Version Info: Core window function available in most modern DBMS
Deprecated/Recommended Alternatives: Consider DENSE_RANK() if gaps undesired
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
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked together
PostgreSQL
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked last by default
SQL Server
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked last by default
SQLite
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked together
BigQuery
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked together
Snowflake
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked last by default
Athena
RANK()
RANK() OVER (ORDER BY col)
NULLs ranked last by default