Back to results for “Window Functions”
SQL Server › Window Functions

What does the ROW_NUMBER function do, and what is a common practical use case for it?

Beginner

Answer

ROW_NUMBER assigns a unique, sequential number to each row within a defined partition, based on a specified order, which is commonly used for tasks like identifying and removing duplicate records, or implementing pagination by numbering rows so you can easily retrieve a specific range, such as the next set of results for a page of a report.
SELECT OrderId, CustomerId, OrderDate,
  ROW_NUMBER() OVER (ORDER BY OrderDate DESC) AS RowNum
FROM Orders;
Real-world example A pagination feature in a reporting application uses ROW_NUMBER to number all orders by date, letting it easily retrieve exactly rows twenty one through forty for the second page of results.

Common follow-ups: What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?;Does ROW_NUMBER guarantee the same numbering every time if there are ties in the ORDER BY column?