Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in SQL Server

How do i limit the result of a query (in my case about 60K rows) and select only from the X row to the Y row?

If I use ROW_NUMBER() I don't like my query because it involves 2 select queries .. one to return the rows and one to select the portion I need

Update:

Here's the query I use now:

SELECT  *
FROM    (
        SELECT  row_number() OVER (ORDER BY E.LastChangeDate DESC) AS row, E.*, U.[DisplayName] AS EntryCreatorDisplayName, U.[Email] AS EntryCreatorEmail
        FROM    entries e
        INNER JOIN
                users u
        ON      e.fk_user= u.id
        WHERE   e.EntryRank = 2
                AND u.Administrator = 1
        ) as TableWithRows
WHERE   (row >= 31 AND row <= 60)
like image 414
Paul Avatar asked Feb 06 '26 05:02

Paul


1 Answers

WITH    q AS
        (
        SELECT  TOP (@Y) m.*, ROW_NUMBER() OVER (ORDER BY mycol) AS rn
        FROM    mytable m
        ORDER BY
                mycol
        )
SELECT  *
FROM    q
WHERE   rn >= @X

In SQL Server 2000:

SELECT  *
FROM    (
        SELECT  TOP (@Y - @X) *
        FROM    (
                SELECT  TOP (@X) *
                FROM    mytable
                ORDER BY
                        mycol
                ) q
        ORDER BY
                mycol DESC
        ) q2
ORDER BY
        mycol
like image 63
Quassnoi Avatar answered Feb 09 '26 04:02

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!