ROW_NUMBER assigns a unique sequential number to rows based on the ordering defined in the window function.
It is useful for selecting the first, latest, highest, or lowest record from each group after joining data.
Find the latest order for every customer.
WITH RankedOrders AS (
SELECT
o.*,
ROW_NUMBER() OVER (
PARTITION BY o.CustomerID
ORDER BY o.OrderDate DESC
) AS rn
FROM Orders o
)
SELECT
c.CustomerName,
r.OrderID,
r.OrderDate
FROM Customers c
INNER JOIN RankedOrders r
ON c.CustomerID = r.CustomerID
WHERE r.rn = 1;
Used in latest-record selection, duplicate removal, customer analysis, and reporting.
- ROW_NUMBER creates unique sequence numbers.
- PARTITION BY separates groups.
- ORDER BY determines row sequence.
- It is useful for latest-record logic.
- CTEs can make the pattern easier to read.
Why use ROW_NUMBER with JOIN?
It can identify a specific row within each group before or after joining related information.
How can ROW_NUMBER find the latest record?
Partition by the entity and order by the date descending, then select the row where ROW_NUMBER equals 1.