title | description | author | ms.author | ms.date | ms.service | ms.subservice | ms.topic | f1_keywords | helpviewer_keywords | dev_langs | monikerRange | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ROW_NUMBER (Transact-SQL) |
Transact-SQL reference for the ROW_NUMBER function. This function numbers the output of a result set. |
MikeRayMSFT |
mikeray |
09/11/2017 |
sql |
t-sql |
reference |
|
|
TSQL |
>= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current||=fabric |
ROW_NUMBER (Transact-SQL)
[!INCLUDE sql-asdb-asdbmi-asa-pdw-fabricse-fabricdw]
Numbers the output of a result set. More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
ROW_NUMBER
and RANK
are similar. ROW_NUMBER
numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK
provides the same numeric value for ties (for example 1, 2, 2, 4, 5).
[!NOTE]
ROW_NUMBER
is a temporary value calculated when the query is run. To persist numbers in a table, see IDENTITY Property and SEQUENCE.
:::image type=»icon» source=»../../includes/media/topic-link-icon.svg» border=»false»::: Transact-SQL syntax conventions
Syntax
ROW_NUMBER ( )
OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )
[!INCLUDEsql-server-tsql-previous-offline-documentation]
Arguments
PARTITION BY value_expression
Divides the result set produced by the FROM clause into partitions to which the ROW_NUMBER function is applied. value_expression specifies the column by which the result set is partitioned. If PARTITION BY
is not specified, the function treats all rows of the query result set as a single group. For more information, see OVER Clause (Transact-SQL).
order_by_clause
The ORDER BY
clause determines the sequence in which the rows are assigned their unique ROW_NUMBER
within a specified partition. It is required. For more information, see OVER Clause (Transact-SQL).
Return Types
bigint
General Remarks
There is no guarantee that the rows returned by a query using ROW_NUMBER()
will be ordered exactly the same with each execution unless the following conditions are true.
-
Values of the partitioned column are unique.
-
Values of the
ORDER BY
columns are unique. -
Combinations of values of the partition column and
ORDER BY
columns are unique.
ROW_NUMBER()
is nondeterministic. For more information, see Deterministic and Nondeterministic Functions.
Examples
A. Simple examples
The following query returns the four system tables in alphabetic order.
SELECT name, recovery_model_desc FROM sys.databases WHERE database_id < 5 ORDER BY name ASC;
[!INCLUDEssResult]
name | recovery_model_desc |
---|---|
master | SIMPLE |
model | FULL |
msdb | SIMPLE |
tempdb | SIMPLE |
To add a row number column in front of each row, add a column with the ROW_NUMBER
function, in this case named Row#
. You must move the ORDER BY
clause up to the OVER
clause.
SELECT ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.databases WHERE database_id < 5;
[!INCLUDEssResult]
Row# | name | recovery_model_desc |
---|---|---|
1 | master | SIMPLE |
2 | model | FULL |
3 | msdb | SIMPLE |
4 | tempdb | SIMPLE |
Adding a PARTITION BY
clause on the recovery_model_desc
column, will restart the numbering when the recovery_model_desc
value changes.
SELECT ROW_NUMBER() OVER(PARTITION BY recovery_model_desc ORDER BY name ASC) AS Row#, name, recovery_model_desc FROM sys.databases WHERE database_id < 5;
[!INCLUDEssResult]
Row# | name | recovery_model_desc |
---|---|---|
1 | model | FULL |
1 | master | SIMPLE |
2 | msdb | SIMPLE |
3 | tempdb | SIMPLE |
B. Returning the row number for salespeople
The following example calculates a row number for the salespeople in [!INCLUDEssSampleDBCoFull] based on their year-to-date sales ranking.
USE AdventureWorks2012; GO SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row, FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD" FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;
[!INCLUDEssResult]
Row FirstName LastName SalesYTD
--- ----------- ---------------------- -----------------
1 Linda Mitchell 4251368.54
2 Jae Pak 4116871.22
3 Michael Blythe 3763178.17
4 Jillian Carson 3189418.36
5 Ranjit Varkey Chudukatil 3121616.32
6 José Saraiva 2604540.71
7 Shu Ito 2458535.61
8 Tsvi Reiter 2315185.61
9 Rachel Valdez 1827066.71
10 Tete Mensa-Annan 1576562.19
11 David Campbell 1573012.93
12 Garrett Vargas 1453719.46
13 Lynn Tsoflias 1421810.92
14 Pamela Ansman-Wolfe 1352577.13
C. Returning a subset of rows
The following example calculates row numbers for all rows in the SalesOrderHeader
table in the order of the OrderDate
and returns only rows 50
to 60
inclusive.
USE AdventureWorks2012; GO WITH OrderedOrders AS ( SELECT SalesOrderID, OrderDate, ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber FROM Sales.SalesOrderHeader ) SELECT SalesOrderID, OrderDate, RowNumber FROM OrderedOrders WHERE RowNumber BETWEEN 50 AND 60;
D. Using ROW_NUMBER() with PARTITION
The following example uses the PARTITION BY
argument to partition the query result set by the column TerritoryName
. The ORDER BY
clause specified in the OVER
clause orders the rows in each partition by the column SalesYTD
. The ORDER BY
clause in the SELECT
statement orders the entire query result set by TerritoryName
.
USE AdventureWorks2012; GO SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2,1) AS SalesYTD, ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS Row FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0 ORDER BY TerritoryName;
[!INCLUDEssResult]
FirstName LastName TerritoryName SalesYTD Row
--------- -------------------- ------------------ ------------ ---
Lynn Tsoflias Australia 1421810.92 1
José Saraiva Canada 2604540.71 1
Garrett Vargas Canada 1453719.46 2
Jillian Carson Central 3189418.36 1
Ranjit Varkey Chudukatil France 3121616.32 1
Rachel Valdez Germany 1827066.71 1
Michael Blythe Northeast 3763178.17 1
Tete Mensa-Annan Northwest 1576562.19 1
David Campbell Northwest 1573012.93 2
Pamela Ansman-Wolfe Northwest 1352577.13 3
Tsvi Reiter Southeast 2315185.61 1
Linda Mitchell Southwest 4251368.54 1
Shu Ito Southwest 2458535.61 2
Jae Pak United Kingdom 4116871.22 1
Examples: [!INCLUDEssazuresynapse-md] and [!INCLUDEssPDW]
E. Returning the row number for salespeople
The following example returns the ROW_NUMBER
for sales representatives based on their assigned sales quota.
-- Uses AdventureWorks SELECT ROW_NUMBER() OVER(ORDER BY SUM(SalesAmountQuota) DESC) AS RowNumber, FirstName, LastName, CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota FROM dbo.DimEmployee AS e INNER JOIN dbo.FactSalesQuota AS sq ON e.EmployeeKey = sq.EmployeeKey WHERE e.SalesPersonFlag = 1 GROUP BY LastName, FirstName;
Here is a partial result set.
RowNumber FirstName LastName SalesQuota
--------- --------- ------------------ -------------
1 Jillian Carson 12,198,000.00
2 Linda Mitchell 11,786,000.00
3 Michael Blythe 11,162,000.00
4 Jae Pak 10,514,000.00
F. Using ROW_NUMBER() with PARTITION
The following example shows using the ROW_NUMBER
function with the PARTITION BY
argument. This causes the ROW_NUMBER
function to number the rows in each partition.
-- Uses AdventureWorks SELECT ROW_NUMBER() OVER(PARTITION BY SalesTerritoryKey ORDER BY SUM(SalesAmountQuota) DESC) AS RowNumber, LastName, SalesTerritoryKey AS Territory, CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota FROM dbo.DimEmployee AS e INNER JOIN dbo.FactSalesQuota AS sq ON e.EmployeeKey = sq.EmployeeKey WHERE e.SalesPersonFlag = 1 GROUP BY LastName, FirstName, SalesTerritoryKey;
Here is a partial result set.
RowNumber LastName Territory SalesQuota
--------- ------------------ --------- -------------
1 Campbell 1 4,025,000.00
2 Ansman-Wolfe 1 3,551,000.00
3 Mensa-Annan 1 2,275,000.00
1 Blythe 2 11,162,000.00
1 Carson 3 12,198,000.00
1 Mitchell 4 11,786,000.00
2 Ito 4 7,804,000.00
See Also
RANK (Transact-SQL)
DENSE_RANK (Transact-SQL)
NTILE (Transact-SQL)
Summary: in this tutorial, you will learn how to use the ROW_NUMBER()
to assign a sequential number to each row in a query result set.
SQL ROW_NUMBER()
Function Overview
The ROW_NUMBER()
is a window function that assigns a sequential integer number to each row in the query’s result set.
The following illustrates the syntax of the ROW_NUMBER()
function:
Code language: SQL (Structured Query Language) (sql)
ROW_NUMBER() OVER ( [PARTITION BY expr1, expr2,...] ORDER BY expr1 [ASC | DESC], expr2,... )
In this syntax,
- First, the
PARTITION BY
clause divides the result set returned from theFROM
clause into partitions. ThePARTITION BY
clause is optional. If you omit it, the whole result set is treated as a single partition. - Then, the
ORDER BY
clause sorts the rows in each partition. Because theROW_NUMBER()
is an order sensitive function, theORDER BY
clause is required. - Finally, each row in each partition is assigned a sequential integer number called a row number. The row number is reset whenever the partition boundary is crossed.
SQL ROW_NUMBER()
examples
We will use the employees
and departments
tables from the sample database for the demonstration:
A) Simple SQL ROW_NUMBER()
example
The following statement finds the first name, last name, and salary of all employees. In addition, it uses the ROW_NUMBER()
function to add sequential integer number to each row.
SELECT ROW_NUMBER() OVER ( ORDER BY salary ) row_num, first_name, last_name, salary FROM employees;
Code language: SQL (Structured Query Language) (sql)
The following picture shows the partial result set:
B) Using SQL ROW_NUMBER()
for pagination
The ROW_NUMBER()
function can be used for pagination. For example, if you want to display all employees on a table in an application by pages, which each page has ten records.
- First, use the
ROW_NUMBER()
function to assign each row a sequential integer number. - Second, filter rows by requested page. For example, the first page has the rows starting from one to 9, and the second page has the rows starting from 11 to 20, and so on.
The following statement returns the records of the second page, each page has ten records.
Code language: SQL (Structured Query Language) (sql)
-- pagination get page #2 SELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY salary) row_num, first_name, last_name, salary FROM employees ) t WHERE row_num > 10 AND row_num <=20;
The following shows the output:
If you want to use the common table expression (CTE) instead of the subquery, here is the query:
Code language: SQL (Structured Query Language) (sql)
WITH t AS( SELECT ROW_NUMBER() OVER ( ORDER BY salary ) row_num, first_name, last_name, salary FROM employees ) SELECT * FROM t WHERE row_num > 10 AND row_num <=20;
C) Using SQL ROW_NUMBER()
for finding nth highest value per group
The following example shows you how to find the employees whose have the highest salary in their departments:
Code language: SQL (Structured Query Language) (sql)
-- find the highest salary per department SELECT department_name, first_name, last_name, salary FROM ( SELECT department_name, `ROW_NUMBER()` OVER ( PARTITION BY department_name ORDER BY salary DESC) row_num, first_name, last_name, salary FROM employees e INNER JOIN departments d ON d.department_id = e.department_id ) t WHERE row_num = 1;
In the subquery:
- First, the
PARTITION BY
clause distributes the employees by departments. - Second, the
ORDER BY
clause sorts the employee in each department by salary in the descending order. - Third, the
ROW_NUMBER()
assigns each row a sequential integer number. It resets the number when the department changes.
The following shows the result set of the subquery:
In the outer query, we selected only the employee rows which have the row_num
with the value 1.
Here is the output of the whole query:
If you change the predicate in the WHERE
clause from 1 to 2, 3, and so on, you will get the employees who have the second highest salary, third highest salary, and so on.
In this tutorial, you have learned how to use the SQL ROW_NUMBER()
function to assign a sequential integer number to each row in the result set of a query.
Was this tutorial helpful ?
Can I run a select statement and get the row number if the items are sorted?
I have a table like this:
mysql> describe orders;
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| orderID | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| itemID | bigint(20) unsigned | NO | | NULL | |
+-------------+---------------------+------+-----+---------+----------------+
I can then run this query to get the number of orders by ID:
SELECT itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID ORDER BY ordercount DESC;
This gives me a count of each itemID
in the table like this:
+--------+------------+
| itemID | ordercount |
+--------+------------+
| 388 | 3 |
| 234 | 2 |
| 3432 | 1 |
| 693 | 1 |
| 3459 | 1 |
+--------+------------+
I want to get the row number as well, so I could tell that itemID=388
is the first row, 234
is second, etc (essentially the ranking of the orders, not just a raw count). I know I can do this in Java when I get the result set back, but I was wondering if there was a way to handle it purely in SQL.
Update
Setting the rank adds it to the result set, but not properly ordered:
mysql> SET @rank=0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
-> FROM orders
-> GROUP BY itemID ORDER BY rank DESC;
+------+--------+------------+
| rank | itemID | ordercount |
+------+--------+------------+
| 5 | 3459 | 1 |
| 4 | 234 | 2 |
| 3 | 693 | 1 |
| 2 | 3432 | 1 |
| 1 | 388 | 3 |
+------+--------+------------+
5 rows in set (0.00 sec)
Consider example table below
ProductDetailNo ProductDescription
224 Apples
225 Tomatoes
226 Potatoes
How do I list the row number for a selected row like below ?
RowNo ProductDetailNo Product Description
2 225 Tomatoes
Using row_number() in my query just returns 1 always for a single record no mater what the logical row is in the database.
Thanks, Damien.
asked Jan 5, 2012 at 7:02
5
try this
WITH MyTable AS
(
SELECT ProductDetailNo, ProductDescription,
ROW_NUMBER() OVER ( ORDER BY ProductDetailNo ) AS 'RowNumber'
FROM Product
)
SELECT RowNumber, ProductDetailNo
FROM MyTable
WHERE ProductDetailNo = 225
Hakan Fıstık
16.5k13 gold badges107 silver badges130 bronze badges
answered Jan 5, 2012 at 7:07
Shoaib ShaikhShoaib Shaikh
4,5651 gold badge26 silver badges35 bronze badges
6
Please Check This
WITH ArticleSearch AS
(
SELECT
ROW_NUMBER() OVER
(
ORDER BY tblProducts.ProductDetailNo
) AS RowNumber,
tblProducts.ProductDetailNo,
tblProducts.ProductDescription
FROM
tblProducts
)
SELECT
a.RowNumber AS SlNo,
a.ProductDetailNo,
a.ProductDescription
FROM
ArticleSearch a
WHERE
a.ProductDetailNo=225
answered Jan 5, 2012 at 7:22
Renju VinodRenju Vinod
2541 gold badge3 silver badges11 bronze badges
1
What about this one?
SELECT RowNo, ProductDetailNo, ProductDescription
FROM (SELECT ROW_NUMBER() as RowNo, ProductDetailNo, ProductDescription
FROM TheTable) as t
WHERE ProductDetailNo = 225;
answered Jan 5, 2012 at 7:09
Sergio TulentsevSergio Tulentsev
226k43 gold badges370 silver badges364 bronze badges
4
WITH productCTE
AS
(SELECT ROW_NUMBER() OVER(ORDER BY ProductDetailNo, ProductDescription) AS RowNo, ProductDetailNo, ProductDescription
FROM tbl_Products
)
SELECT * FROM productCTE
WHERE RowNo = 2
musefan
47.7k21 gold badges134 silver badges184 bronze badges
answered Jan 5, 2012 at 9:04
GopuGopu
559 bronze badges
The row number you receive is from number of the rows of result. i.e. if your result has just one tuple, the row no. will always be 1.
To get row number of the entire table, you should add a extra attribute, a RowNo with auto increment to your table.
Hope this helps, but possibly SQL has even better solution for you!
answered Jan 5, 2012 at 7:07
Vinayak GargVinayak Garg
6,51810 gold badges53 silver badges80 bronze badges
1
There is no inherent row number for a table row. ROW_NUMBER()
gives you the number of the row only within a specific result set. So it is the expected result that you always get 1
when the result set contains only 1 record. If you want a row number, your table schema should include something like an auto-incrementing IDENTITY
column.
answered Jan 5, 2012 at 7:09
bobbymcrbobbymcr
23.7k3 gold badges55 silver badges66 bronze badges
1
The MySQL ROW_NUMBER()
function returns the row number of the current row within the partition where the current row is located, starting from 1.
ROW_NUMBER()
Syntax
Here is the syntax of the MySQL ROW_NUMBER()
function:
ROW_NUMBER()
OVER (
[PARTITION BY partition_column_list]
[ORDER BY order_column_list]
)
Parameters
partition_column_list
-
List of columns for partitioning.
partition_column_list
-
List of columns for sorting.
Return value
The MySQL ROW_NUMBER()
function returns the row number of the current row within the partition where the current row is located, starting from 1.
ROW_NUMBER()
Examples
Preparing Data
Use the following CREATE TABLE
statement to create a table named student_grade
to store grades of students:
CREATE TABLE student_grade (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
class CHAR(1) NOT NULL,
subject VARCHAR(20) NOT NULL,
grade INT NOT NULL
);
This student_grade
table has 5 columns as following:
id
— The row ID, primary key.name
— The name of a student.class
— The class a student is in.subject
— The name of a subject.grade
— The grades for a subject and a student.
Insert some rows into the student_grade
table using the following INSERT
statement:
INSERT INTO student_grade
(name, class, subject, grade)
VALUES
('Tim', 'A', 'Math', 9),
('Tom', 'A', 'Math', 7),
('Jim', 'A', 'Math', 8),
('Tim', 'A', 'English', 7),
('Tom', 'A', 'English', 8),
('Jim', 'A', 'English', 7),
('Lucy', 'B', 'Math', 8),
('Jody', 'B', 'Math', 6),
('Susy', 'B', 'Math', 9),
('Lucy', 'B', 'English', 6),
('Jody', 'B', 'English', 7),
('Susy', 'B', 'English', 8);
Use the following SELECT
statement to show all rows in this table:
SELECT * FROM student_grade;
+----+------+-------+---------+-------+
| id | name | class | subject | grade |
+----+------+-------+---------+-------+
| 1 | Tim | A | Math | 9 |
| 2 | Tom | A | Math | 7 |
| 3 | Jim | A | Math | 8 |
| 4 | Tim | A | English | 7 |
| 5 | Tom | A | English | 8 |
| 6 | Jim | A | English | 7 |
| 7 | Lucy | B | Math | 8 |
| 8 | Jody | B | Math | 6 |
| 9 | Susy | B | Math | 9 |
| 10 | Lucy | B | English | 6 |
| 11 | Jody | B | English | 7 |
| 12 | Susy | B | English | 8 |
+----+------+-------+---------+-------+
12 rows in set (0.00 sec)
Example 1
To show the row number of each student in each subject in descending order of grade, use the following statement:
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY subject
ORDER BY grade DESC
) "row_number"
FROM student_grade;
+----+------+-------+---------+-------+------------+
| id | name | class | subject | grade | ROW_NUMBER |
+----+------+-------+---------+-------+------------+
| 5 | Tom | A | English | 8 | 1 |
| 12 | Susy | B | English | 8 | 2 |
| 4 | Tim | A | English | 7 | 3 |
| 6 | Jim | A | English | 7 | 4 |
| 11 | Jody | B | English | 7 | 5 |
| 10 | Lucy | B | English | 6 | 6 |
| 1 | Tim | A | Math | 9 | 1 |
| 9 | Susy | B | Math | 9 | 2 |
| 3 | Jim | A | Math | 8 | 3 |
| 7 | Lucy | B | Math | 8 | 4 |
| 2 | Tom | A | Math | 7 | 5 |
| 8 | Jody | B | Math | 6 | 6 |
+----+------+-------+---------+-------+------------+
12 rows in set (0.00 sec)
Note that the window function in the SQL statement above:
ROW_NUMBER() OVER (
PARTITION BY subject
ORDER BY grade DESC
)
In the OVER
clause,
- The
PARTITION BY subject
partitions all rows by subject - The
ORDER BY grade
sorts all rows within each partition in ascending order by grade. - The
ROW_NUMBER()
returns the row number of each row within its associated partition.
Example 2
To show the row number of each student in each class in descending order of total grade, use the following statement:
SELECT t.*,
ROW_NUMBER() OVER (
PARTITION BY class
ORDER BY t.sum_grade DESC
) "row_number"
FROM (
SELECT class,
name,
sum(grade) sum_grade
FROM student_grade
GROUP BY class, name
) t;
+-------+------+-----------+------------+
| class | name | sum_grade | ROW_NUMBER |
+-------+------+-----------+------------+
| A | Tim | 16 | 1 |
| A | Tom | 15 | 2 |
| A | Jim | 15 | 3 |
| B | Susy | 17 | 1 |
| B | Lucy | 14 | 2 |
| B | Jody | 13 | 3 |
+-------+------+-----------+------------+
6 rows in set (0.00 sec)
Notice this subquery in the above statement:
SELECT class,
name,
sum(grade) sum_grade
FROM student_grade
GROUP BY class, name
This subquery uses the GROUP BY
clause and the sum()
function sums up each student’s total grade by class and student.
+-------+------+-----------+
| class | name | sum_grade |
+-------+------+-----------+
| A | Tim | 16 |
| A | Tom | 15 |
| A | Jim | 15 |
| B | Lucy | 14 |
| B | Jody | 13 |
| B | Susy | 17 |
+-------+------+-----------+
6 rows in set (0.01 sec)
The main statement partitions all rows from this subquery by classes, then sort by total grade in descending order within each partition, and gets the row number of each row within its associated partition using ROW_NUMBER()
.