OFFSET & FETCH options in SQL 2012

by Valmik 26. April 2012 10:32
SQL 2012 has a new T-SQL that helps your SELCT query to implement the page solution. We have used combination of TOP and ORDER BY in the past to handle this, However, OFFSET & FETCH clauses has more benefits.
  
OFFSET: Allows you to set the record pointer to a specific row in a table
FETCH: Allows you to select number of rows you request in Fetch.
 
For OFFSET you will specify starting row and page size will be specified to FETCH.
Example:
  
SELECT * FROM TableName
ORDER BY Table_ID
OFFSET 3 ROWS
FETCH NEXT 5 ROWS ONLY
 
FETCH and OFFSET can be used with variables as well.
Below is example:
DECLARE @OFFSET INT=3, @FETCH INT=5
SELECT * FROM Table_Name
ORDER BY Table_ID
OFFSET @OFFSET ROWS
FETCH NEXT @FETCH ROWS ONLY

Tags:

Category

Recent Posts

Tag cloud