ROW_NUMBER()

This function numbers the output of a result set.

Signature

ROW_NUMBER ( )
    OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )

Examples

SELECT product, amount, ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn FROM dbo.orders;
product                                  amount       rn
---------------------------------------- ------------ --------------------
monitor                                        438.00                    1
monitor                                        219.00                    2
keyboard                                        99.00                    3
keyboard                                        49.50                    4
mouse                                           27.75                    5
cable                                           15.00                    6
SELECT 
  name, recovery_model_desc
FROM sys.databases 
WHERE database_id < 5
ORDER BY name ASC;
master|SIMPLE
model|FULL
msdb|SIMPLE
tempdb|SIMPLE
SELECT 
  ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#,
  name, recovery_model_desc
FROM sys.databases 
WHERE database_id < 5;
1|master|SIMPLE
2|model|FULL
3|msdb|SIMPLE
4|tempdb|SIMPLE

Run against SQL Server 16.0.4265.3 on 2026-09-13. This is the output we got, not the documentation’s.

Available on

  • SQL Server 2017 and later
  • Azure SQL Database
  • Azure SQL Managed Instance
  • Azure Synapse Analytics
  • Analytics Platform System (PDW)
  • Microsoft Fabric warehouse
  • Fabric SQL database

Signature and description adapted from the Microsoft SQL documentation, used under the CC BY 4.0. SQL Server and Azure are trademarks of the Microsoft group of companies. This page is not affiliated with Microsoft.