Curriculum
In this tutorial, you’ll learn how to use the SQL Server’s OFFSET and FETCH clauses to limit the number of records that can be returned from the query.
OFFSET and FETCH clauses are the optional parameters that can be used along with the ORDER BY clause in SQL Server. These two clauses allow you to limit the number of records that needs to be returned when the query is executed.
The below syntax demonstrates the usage if the OFFSET and FETCH clauses in SQL Server.
SELECT express FROM Table ORDER BY column_list [ASC |DESC] OFFSET offset_row_count {ROW | ROWS} FETCH {FIRST | NEXT} fetch_row_count {ROW | ROWS} ONLY
Note :
Let’s use the Person table from the AdventureWorks database to explore these two clauses.
The below query returns all the FirstNames from the Person table and sorts by their FirstName.
SELECT FirstName FROM [Person].[Person] ORDER BY FirstName
If you need to skip the first 10 records from the Person table and return the rest, you will need to use the OFFSET clause as shown in the below query.
SELECT FirstName FROM [Person].[Person] ORDER BY FirstName OFFSET 10 ROWS;
If you need to skip the first 10 records from the Perso Table and select the next 20 person records, you can use both OFFSET and FETCH clause as shown in the below query.
SELECT FirstName FROM [Person].[Person] ORDER BY FirstName OFFSET 10 ROWS FETCH NEXT 20 ROWS ONLY;