The ROW_NUMBER()
function in SQL Server is a window function that assigns a unique sequential integer to rows within a partition of a result set. The numbering starts at 1 for the first row in each partition. This function is often used for pagination, ranking, and ordering data.
Syntax
sql1ROW_NUMBER() OVER (PARTITION BY column1, column2, ... ORDER BY column3, column4, ...)
- PARTITION BY: Divides the result set into partitions to which the
ROW_NUMBER()
function is applied. If omitted, all rows are treated as a single partition. - ORDER BY: Specifies the order in which the rows are numbered.
Example
Let's consider a simple example using a hypothetical Employees
table:
sql1CREATE TABLE Employees ( 2 EmployeeID INT, 3 FirstName NVARCHAR(50), 4 LastName NVARCHAR(50), 5 Department NVARCHAR(50), 6 Salary DECIMAL(10, 2) 7); 8 9INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) 10VALUES 11(1, 'John', 'Doe', 'Sales', 60000), 12(2, 'Jane', 'Smith', 'Sales', 65000), 13(3, 'Sam', 'Brown', 'HR', 70000), 14(4, 'Lisa', 'White', 'HR', 72000), 15(5, 'Tom', 'Green', 'IT', 80000), 16(6, 'Anna', 'Black', 'IT', 75000);
Now, let's use the ROW_NUMBER()
function to assign a unique number to each employee within their department based on their salary in descending order:
sql1SELECT 2 EmployeeID, 3 FirstName, 4 LastName, 5 Department, 6 Salary, 7 ROW_NUMBER() OVER (PARTITION BY Department ORDER BY Salary DESC) AS RowNum 8FROM 9 Employees;
Result
The result of the above query would look like this:
EmployeeID | FirstName | LastName | Department | Salary | RowNum |
---|---|---|---|---|---|
2 | Jane | Smith | Sales | 65000 | 1 |
1 | John | Doe | Sales | 60000 | 2 |
4 | Lisa | White | HR | 72000 | 1 |
3 | Sam | Brown | HR | 70000 | 2 |
5 | Tom | Green | IT | 80000 | 1 |
6 | Anna | Black | IT | 75000 | 2 |
Benefits of Using ROW_NUMBER()
Pagination:
ROW_NUMBER()
is commonly used for implementing pagination in SQL queries. You can easily retrieve a specific range of rows (e.g., rows 11 to 20) by filtering on theRowNum
column.Ranking: It allows you to rank rows based on specific criteria (e.g., sales performance, scores) within partitions, making it useful for reporting and analytics.
Unique Row Identification: It provides a unique identifier for each row in the result set, which can be helpful for further processing or analysis.
Flexible Ordering: You can specify different ordering criteria for different partitions, allowing for complex data analysis scenarios.
Data Transformation: It can be used in conjunction with other window functions (like
SUM()
,AVG()
, etc.) to perform advanced data transformations and calculations.