Using FETCH and OFFSET to get N records in SQL Server

Published on August 20, 2016 by abundantcode

Filed under SQL Server

Last modified August 20, 2016

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4127 times

In SQL Server , you can use the OFFSET and FETCH and apply paging and retreive N records at a time. OFFSET AND FETCH clause are part of the ORDER BY clause and hence you must include the ORDER BY clause.

For example , you might want to skip the first 4 records and retrieve 5 records from the query , you could use the following

This query retrieves all the records from the Department table.

Use AdventureWorks2014
GO
SELECT * FROM HumanResources.Department

SNAGHTML8b23906

Now , we can use the below query to skip the first 4 records and get the next 5 records from the Department table.

Use AdventureWorks2014
GO
SELECT * FROM HumanResources.Department
ORDER BY Name
OFFSET 4 ROWS 
FETCH NEXT 5 ROWS ONLY;

image

Leave a Comment


x

You might be Interested in these Posts

C Program to find the G.C.D of a number using Recursive function

Problem Write a program in C to find the find the G.C.D of a number using recursion and display the ...

C Program to print a Half Pyramid using *

Problem Write a program in C to print Half pyramid using * as shown. * * * * * * * * * * ...

C Program to display Positive factors of a number

Problem Write a program in C to display all the positive factors of a number enter by the user. Ho...