views:

36

answers:

2

Hello everyone,

I am using SQL Server 2008 Enterprise on Windows Server 2008. I want to select result from top 11 to top 20 (e.g. I am only interested in the 11th to the 20th result). Any ideas how to write this query in tsql efficiently?

thanks in advance, George

+1  A: 

Assuming a sort field PK,

select top 10 * from MyTable
where PK not in (select top 10 PK from Mytable order by PK)
order by PK

Edit: here's a variant

select top 10 * from 
(select top 20 * from MyTable order by PK) as MySelection
order by PK desc
SeaDrive
I think it is very tricky since when I need to select 21th to 30th, I need to write another tsql statement.
George2
It's pretty easy to parametrize the query.
SeaDrive
+5  A: 

Unfortunately SQL Server does not offer anything similar to MySQL's OFFSET syntax. However, you may want to try using a derived table as follows:

SELECT some_field
FROM   (
          SELECT some_field, ROW_NUMBER() OVER (ORDER BY some_id) AS rownum
          FROM   table
       ) AS t
WHERE  t.rownum BETWEEN 11 AND 20
Daniel Vassallo
Must I have order by some_id?
George2
@George2: Since tables in relational databases are just sets of unordered records, you have to order the result set by one (or more) unique column(s) in order for pagination to make sense. Otherwise, how can you say that a record is the 11th one?
Daniel Vassallo
Cool, question answered!
George2
Yep. How else would you rank the 11th and 20th? Without an ORDER BY, SQL Server can return to you any results it wants - order is not guaranteed. Not sure how you're defining your ranking, but whatever field combo that is must go in the `order by`.
mattmc3