Optimized paging query implementation for Microsoft SQL Server 2005

Optimized paging query implementation for Microsoft SQL Server 2005

We did performance tests on several methods of paging implementation and found the fastest one:

DECLARE @PageNumber INT
DECLARE @PageSize INT
SET @PageNumber = 2
SET @PageSize = 10
SELECT TOP (@PageSize) * FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY FieldA) As RowID,
FieldB,FieldC,
TotalRows=COUNT(*) OVER()
FROM TheTable
) TmpTable
WHERE TmpTable.RowID > ((@PageNumber-1)*@PageSize)

One significant advantage of this implementation approach is that there is no need for a second query that returns the total count of the paged data. The total record count is returned as a column in the result set. This minimizes the number of queries that are needed to return a paged result set. If not needed, the “TotalRows” column can be removed from the query.

Comments

eggpoker 29-01-2011, 01:08

thanks for sharing

Reply
Arun Raj 26-06-2011, 10:50

Try this link: http://www.arunraj.co.in/index.php?option=com_content&view=article&id=2:paging-query&catid=3:aspnet&Itemid=8
This post has some paging queries and a C# function which will convert any query into a paging query by passing start value and rows per page value as arguments.

Reply

Leave a Reply