Tuesday, September 14, 2004

SQL Server Custom Paging

You can use a query of the following form to retrieve records by row number from Microsoft SQL Server:

SELECT *
FROM (SELECT TOP {0} *
FROM (SELECT TOP {1} *
FROM {2}
ORDER BY {3}) AS t1
ORDER BY {3} DESC) AS t2
ORDER BY {3}

Replace:
{0} with the page size (the number of records displayed on each page),
{1} with the page size * page number (1-based),
{2} with the name of the table you wish to query, and
{3} with a field name.

The following example retrieves rows 41-50 from the "Products" table of the Northwind database:

SELECT *
FROM (SELECT TOP 10 *
FROM (SELECT TOP 50 *
FROM Products
ORDER BY ProductID) AS t1
ORDER BY ProductID DESC) AS t2
ORDER BY ProductID

You can combine this query technique with custom paging to make DataGrid paging more efficient. With default paging, you must initialize the data source with all records displayed on all pages. With custom paging, you can initialize the data source with just those records that pertain to the current page.

3 comments:

Dr. Amith Ellur said...

I believe LIMIT works with My SQL/Oracle, anyways it's non standard, so it's not going to work when you switch databases

Dr. Amith Ellur said...

Again this doesn't work with SQL Server in specific, but i will have them as reference for people who work on mysql/oracle.

Thanks!

Anonymous said...

Clever SQL!

My only issue is that the last page will include the exact page size, which will repeat data from previous page.