Filtering and sorting
Deterministic paging
Build pages with a unique ordering key and understand shifting data.
Lesson 18 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. A page boundary is meaningful only if every row has a fixed position. City alone is not unique, so this query uses CustomerID to resolve ties before taking page two.
Run the example
SELECT CustomerID, FirstName, City
FROM dbo.Customers
ORDER BY City, CustomerID
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;Read it step by step
- ORDER BY City, CustomerID first groups cities alphabetically and then fixes order within each city by the unique CustomerID.
- OFFSET 5 ROWS skips the first five sorted customers: three in Birmingham and two in Bristol.
- FETCH NEXT 5 ROWS ONLY returns the next five: Cardiff, Leeds, and the first Leicester customer.
Check the result
| CustomerID | FirstName | City |
|---|---|---|
| 8 | Nina | Cardiff |
| 14 | Rosa | Cardiff |
| 5 | Ravi | Leeds |
| 12 | Mila | Leeds |
| 11 | Omar | Leicester |
For the unmodified v1.0.0 dataset, this page always contains the same five customer IDs. It is different from page two ordered only by CustomerID, which contains IDs 6 through 10. Page numbering depends on the exact ORDER BY.
Practice
Page through Customers by CustomerID in groups of five. Write the query for page three and name its IDs.
Check your answer and expected result
Reveal answer
SELECT CustomerID, FirstName FROM dbo.Customers ORDER BY CustomerID OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;| CustomerID | FirstName |
|---|---|
| 11 | Omar |
| 12 | Mila |
| 13 | Sam |
| 14 | Rosa |
| 15 | Arjun |
IDs 11 through 15 appear.
Your progress
Reveal the check answer or reach the end to complete this lesson.