Reading data with SELECT
TOP and OFFSET/FETCH
Limit result size and fetch a page using a stable order.
Lesson 10 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 may show only a few rows at a time. SQL Server offers TOP for a first slice and OFFSET/FETCH for later pages.
Run the example
SELECT CustomerID, FirstName
FROM dbo.Customers
ORDER BY CustomerID
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;Read it step by step
- ORDER BY CustomerID establishes a stable sequence from ID 1 through ID 20. CustomerID is unique, so no two rows tie.
- OFFSET 5 ROWS skips IDs 1 through 5 in that sequence.
- FETCH NEXT 5 ROWS ONLY returns the next five rows: IDs 6 through 10. OFFSET/FETCH is part of ORDER BY in SQL Server.
Check the result
| CustomerID | FirstName |
|---|---|
| 6 | Zara |
| 7 | Theo |
| 8 | Nina |
| 9 | Eli |
| 10 | Ada |
The result contains exactly five customers because this dataset has at least ten. For the first page, use OFFSET 0 and FETCH NEXT 5; for the third, use OFFSET 10. TOP (5) with the same ORDER BY returns the first page.
Practice
Return the first three Products by ascending ProductID using TOP. Which IDs appear?
Check your answer and expected result
Reveal answer
SELECT TOP (3) ProductID, ProductName FROM dbo.Products ORDER BY ProductID;| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 2 | USB-C Dock |
| 3 | Webcam |
ProductID values 1, 2, and 3 appear.
Your progress
Reveal the check answer or reach the end to complete this lesson.