3

Possible Duplicate:
Equivalent of LIMIT and OFFSET for SQL Server?

this is a mysql query

SELECT email FROM emailTable LIMIT 9,20 WHERE id=3

how do you write it in SQL Server (2008)?

do I have to write

SELECT TOP 9,20 email FROM emailTable WHERE id=3

? Thank you for your help

Community
  • 1
  • 1
Bellash
  • 5,719
  • 3
  • 39
  • 72

3 Answers3

6

Try this:

SELECT * 
FROM 
( 
      SELECT *, 
        ROW_NUMBER() OVER (ORDER BY email) as rowNum 
      FROM tableName
) sub 
WHERE rowNum > 9 
  AND rowNum <= 9 + 20 
  AND id = 3

DEMO

Community
  • 1
  • 1
Mahmoud Gamal
  • 72,639
  • 16
  • 129
  • 156
2

You can use ROW_NUMBER() to achieve the same outcome.

e.g. to get rows 1 to 10:

;WITH results AS
(    
    SELECT ROW_NUMBER() OVER (ORDER BY YourColumn ASC) AS RowNo,
        email
    FROM emailTable
)

SELECT * 
FROM results
WHERE RowNo BETWEEN 1 AND 10

Edit: condensed into 1 statement:

SELECT * 
FROM
(
    SELECT ROW_NUMBER() OVER (ORDER BY YourColumn ASC) AS RowNo,
        email
    FROM emailTable
) x
WHERE x.RowNo BETWEEN 1 AND 10
AdaTheDev
  • 128,935
  • 26
  • 185
  • 187
  • 1
    thank you AdaTheDev but can you do it basically? I mean just select email for 20 first users whose id=3, starting by the 9th... maybe you catch me well – Bellash Feb 13 '12 at 13:37
  • It isn't as straight forward as there isn't support for LIMIT. There are other variations of this, but none as as "basic" as LIMIT. e.g. the above could be condensed into 1 SELECT statement, as updated in my answer – AdaTheDev Feb 13 '12 at 13:41
1

Limit with offset in sql server:

SELECT email FROM emailTable WHERE id=3
OFFSET 8 ROWS
FETCH NEXT 12 ROWS ONLY;

//offset - no. of skipped rows

//next - required no. of next rows

Update: This is working but sql server 2012 onwards

Somnath Muluk
  • 46,917
  • 28
  • 204
  • 217