What would be the most efficient way to do a paging query in SQLServer 2000?
Where a "paging query" would be the equivalent of using the LIMIT statement in MySQL.
EDIT: Could a stored procedure be more efficient than any set based query in that case?
I think what you really have here is a compelling reason to upgrade to SQL 2005.
In SQL 2005 this can be done quickly and easily with:
If you're really stuck with SQL 2000 I'd worry - Microsoft aren't going to fully support it much longer given that it is now two generations back.
There isn't going to be one best way to do this I'm afraid - all solutions are kinda hacks.
@Petar Petrov's answer is probably the most consistent, however:
I think you're looking at a few hours tweaking with query analyser each time. A stored proc won't make much difference either way - the caching of the query plan is not likely to be the bottleneck.
The efficiency of the query really depends on how the underlying table is structured. If, say you have a primary key called ID which is an IDENTITY, and it's a clustered index, and you can assume that nobody's been doing IDENTITY_INSERTs on it, you can do a query like:
SELECT TOP XXX FROM table WHERE ID > @LastPagesID;
That will get you results as fast as possible. Everything else that's going to be really efficient is some variant on this -- maybe it's not an ID -- maybe what you're using to page is actually a date which you know to be unique, but you get the point... The IN () based queries shown here will probably work, but they won't touch the performance of a partial clustered or covering index scan.
Paging of Large Resultsets and the winner is using RowCount. Also there's a generalized version for more complex queries. But give credit to Jasmin Muharemovic :)
The article contains the entire source code.
Please read the "Update 2004-05-05" information. !
This is a generic SQL Server 2000 stored procedure that will perform pagination on any table. The stored procedure accepts the name of the table, the columns to output (defaults to all columns in the table), an optional WHERE condition, an optional sort order, the page number to retrieve and the number of rows per page.
Here's a few examples on how to use it using the Northwing database:
To confirm, this is not my work but is courtesy of http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=1055
Cheers, John
I think a nested
SELECT TOP n
query is probably the most efficient way to accomplish it.Replace
ThisPageRecordCount
with items per page andBeforeThisPageRecordCount
with(PageNumber - 1) * items-per-page
.Of course the better way in SQL Server 2005 is to use the
ROW_NUMBER()
function in a CTE.