Click here to Skip to main content
12,757,220 members (39,684 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 27 Dec 2011

Efficient paging using SQL script

, 28 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Hi, what about such solution?DECLARE @pageNumber INTDECLARE @rowsOnPage INTSET @rowsOnPage=5SET @pageNumber=2DECLARE @totalItemsToSelect INTSET @totalItemsToSelect=@rowsOnPage * @pageNumberSELECT TOP (@rowsOnPage) * FROM MainTrans WHERE ID IN( SELECT TOP...
Hi, what about such solution?

DECLARE @pageNumber INT

SET @rowsOnPage=5
SET @pageNumber=2

DECLARE @totalItemsToSelect INT
SET @totalItemsToSelect=@rowsOnPage * @pageNumber

SELECT TOP (@rowsOnPage) * FROM MainTrans WHERE ID IN
    SELECT TOP (@totalItemsToSelect) ID FROM MainTrans ORDER BY ID DESC

it looks much shorter.


P.S. of course this solution works only if you have identity column. in my opinion identity column is a must for paging, moreover this approach works for any database not only for MS SQL


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

You may also be interested in...


Comments and Discussions

GeneralReason for my vote of 4 I think this script works well, but ... Pin
Robby Tendean28-Dec-11 17:12
memberRobby Tendean28-Dec-11 17:12 
GeneralReason for my vote of 3 The alternative is pretty solid if y... Pin
Helluin28-Dec-11 7:01
memberHelluin28-Dec-11 7:01 
GeneralActually: 1. TOP does not work on Oracle (at least versions ... Pin
Pablo Aliskevicius28-Dec-11 5:38
memberPablo Aliskevicius28-Dec-11 5:38 
1. TOP does not work on Oracle (at least versions 8 through 10, the ones I worked with).
2. The IDENTITY field is usually meaningless. For instance, in Robby's example, some user is paging by a date column; let's say that column is the birth date of a person; there is no guarantee that the records were created on a 'first born, first entered' order.
The ROWNUMBER function seems to be a lesser evil: another option would be getting all the relevant records into the client, and paging there.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 28 Dec 2011
Article Copyright 2011 by NeoPunk
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid