tags:

views:

411

answers:

5

In PostgreSQL there is the Limit and Offset keywords which will allow very easy pagination of result sets. What is the equivalent syntax for Sql Server?

A: 

See TOP and BETWEEN

BlueRaja - Danny Pflughoeft
BETWEEN is not an equivalent. It's used for WHERE conditions to filter based on row values.
Sam
..I realize that.
BlueRaja - Danny Pflughoeft
+11  A: 

The equivalent of LIMIT is SET ROWCOUNT, but if you want generic pagination it's better to write a query like this:

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).

Note: the @Offset parameter should use one-based indexing for this rather than the normal zero-based indexing.

Aaronaught
A: 

In SQL server you would use TOP together with ROW_NUMBER()

SQLMenace
+2  A: 

You can use ROW_NUMBER in a Common Table Expression to achieve this.

;WITH My_CTE AS
(
     SELECT
          col1,
          col2,
          ROW_NUMBER() OVER(ORDER BY col1) AS row_number
     FROM
          My_Table
     WHERE
          <<<whatever>>>
)
SELECT
     col1,
     col2
FROM
     My_CTE
WHERE
     row_number BETWEEN @start_row AND @end_row
Tom H.
A: 

I would recommend you to read this interesting article about SQL Server pagination.

Jose Chama