ROW_NUMBER() in SQL
Assigns a unique sequential integer to rows within a result set partition.
Syntax
Return type
ROW_NUMBER() Function Example
What is ROW_NUMBER() in SQL?
The ROW_NUMBER()
function in SQL assigns a unique sequential integer to each row within a result set partition, starting at 1 for each partition. It is commonly used for ranking results, paginating query outputs, and generating row-based identifiers dynamically.
This function is supported in SQL Server, PostgreSQL, and Oracle, while MySQL uses window functions with ROW_NUMBER()
introduced in version 8.0.
The ROW_NUMBER()
function is widely used in pagination, duplicate handling, and organizing ranked datasets.
Parameters:
PARTITION BY (optional): Columns to partition the rows
ORDER BY (required): Columns that determine the row sequence
Example Use Cases:
-- Top N per group
-- Find duplicate records
-- Pagination
Notes:
Behavior: Always returns unique, sequential numbers
Performance Considerations: May require window function optimization
Version Info: Core window function available in most modern DBMS
Deprecated/Recommended Alternatives: None, standard functionality
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
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
PostgreSQL
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
SQL Server
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
SQLite
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
BigQuery
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
Snowflake
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
Athena
ROW_NUMBER()
ROW_NUMBER() OVER (ORDER BY col)
Includes NULL values
Related Functions:
RANK()
Assigns a rank to rows within a result set partition, with gaps in rank numbers when ties occur.
DENSE_RANK()
Assigns a rank to rows within a result set partition, with no gaps in rank numbers when ties occur.
LAG()
Accesses data from a previous row in the result set within a specified window partition.
LEAD()
Accesses data from a subsequent row in the result set within a specified window partition.