How to use ROW_NUMBER Function in SQL Server
By Tan Lee Published on Feb 16, 2024 452
The numbering starts from 1 for the first row, based on the ordering specified in the ORDER BY
clause.
Syntax of the ROW_NUMBER() function:
ROW_NUMBER() OVER ( [PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ... )
For example:
SELECT ROW_NUMBER() OVER (ORDER BY FirstName) as Order, FirstName, LastName, City FROM Customers
Result
Order | FirstName | LastName | City |
1 | Lucy | NULL | |
2 | Tom | NewYork |
The ROW_NUMBER() function is useful for pagination, It is a temporary value calculated when the query is run.
Partitioning Data with PARTITION BY
You can also use the PARTITION BY
clause to restart the row numbering for each partition of data. This is useful when you want to create separate row numbers for groups of records.
SELECT EmployeeID, FirstName, LastName, DepartmentID, ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY LastName ASC) AS RowNum FROM Employees
In this example:
- The row numbers are assigned for each department (
DepartmentID
), restarting the numbering for each department.
Filtering Rows Using ROW_NUMBER()
If you want to retrieve specific rows, such as getting only the first few rows for each partition (e.g., top 3 employees in each department), you can use the ROW_NUMBER()
function with a WHERE
clause.
WITH RankedEmployees AS ( SELECT EmployeeID, FirstName, LastName, DepartmentID, ROW_NUMBER() OVER (PARTITION BY DepartmentID ORDER BY LastName ASC) AS RowNum FROM Employees ) SELECT EmployeeID, FirstName, LastName, DepartmentID FROM RankedEmployees WHERE RowNum <= 3
In this example:
- We first rank employees by department (
PARTITION BY DepartmentID
), then filter to get only the top 3 employees (RowNum <= 3
) from each department.
- How to Download ODBC Driver for SQL Server
- How to Download SQL Server Management Studio (SSMS) Versions
- How to Query JSON in SQL Server
- How to modify JSON in SQL Server
- How to set time to 00:00:00 with GETDATE() in SQL
- How to find all the dependencies of a table in SQL Server
- How to Find Objects Referencing a Table in SQL Server
- Case sensitivity in SQL Server