Window functions
ROW_NUMBER
Number rows within each city using a stable tie-breaker.
Lesson 59 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Number rows within each city using a stable tie-breaker.
Run the example
sql
SELECT TOP (8) CustomerID, City,
ROW_NUMBER() OVER (PARTITION BY City ORDER BY CustomerID) AS CityRow
FROM dbo.Customers
ORDER BY City, CustomerID;Read it step by step
- PARTITION BY City restarts numbering for each city.
- ORDER BY CustomerID inside OVER determines the row numbers with a unique key.
- The final ORDER BY arranges the visible result; TOP (8) applies after numbering.
Check the result
| CustomerID | City | CityRow |
|---|---|---|
| 3 | Birmingham | 1 |
| 9 | Birmingham | 2 |
| 19 | Birmingham | 3 |
| 6 | Bristol | 1 |
| 13 | Bristol | 2 |
| 8 | Cardiff | 1 |
| 14 | Cardiff | 2 |
| 5 | Leeds | 1 |
CityRow restarts at 1 for each city.
Practice
Number products within each CategoryID by ProductID and show Products 1–5.
Check your answer and expected result
Reveal answer
sql
SELECT TOP (5) ProductID, CategoryID,
ROW_NUMBER() OVER (PARTITION BY CategoryID ORDER BY ProductID) AS CategoryRow
FROM dbo.Products
ORDER BY ProductID;| ProductID | CategoryID | CategoryRow |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
The numbering restarts when CategoryID changes.
Your progress
Reveal the check answer or reach the end to complete this lesson.