In this article we shall learn how to limit the numbers of rows returned by a query using OFFSET and FETCH clause introduced in SQL Server 2012. The following query is executed against AdventureWorks Database.
SELECT SalesOrderID,SalesOrderDetailID,OrderQty,SpecialOfferID FROM [Sales].[SalesOrderDetail] ORDER BY SalesOrderDetailID
The following is the query result set when the above T-SQL code is executed.
Observe that the data is displayed sorted by the column SalesOrderDetailID, which is very much clear from the ORDER BY clause at the end of the query. This query will display all records in that table as we have not included any filtering condition.
You might be aware that using TOP clause we can restrict the query result set to as many rows we want it to display. Instead of the top n records, if we wanted to return x number of records from the middle of the result set, sorted on a particular column, we would have to do some additional manipulations and retrieve them.
In SQL Server 2012, this can be achieved by using the OFFSET and FETCH clause at the end of the Select query, after ORDER BY clause. Let’s take a look at this sample query to understand this better..
SELECT SalesOrderID,SalesOrderDetailID,OrderQty,SpecialOfferID FROM [Sales].[SalesOrderDetail] ORDER BY SalesOrderDetailID OFFSET 5 ROW FETCH NEXT 10 ROW ONLY
The OFFSET clause sets how many rows needs to be skipped before displaying the result set. In this case we gave OFFSET 5 ROW, so the first 5 rows are skipped. FETCH NEXT x ROW ONLY, displays the next x records, if there are records inside the table. In our example script, we used 10 so 10 rows are displayed. If we mention 10000000 rows, and if there are only 1000 rows in the table, then only 995 rows will be displayed. A small clarification, the keywords ROW or ROWS both will work the same.
Note: Please note that this is correct as of SQL Server 2012 RC0.
Do you like this site? Like our FB page @ Facebook.com\LearnSQLWithBru so that, you know when there is a new blog post.