How to implement LIMIT with SQL Server?

Bigballs picture Bigballs · Mar 2, 2009 · Viewed 317.8k times · Source

I have this query with MySQL:

select * from table1 LIMIT 10,20

How can I do this with SQL Server?

Answer

Leon Tayson picture Leon Tayson · Mar 2, 2009

Starting SQL SERVER 2005, you can do this...

USE AdventureWorks;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
    FROM Sales.SalesOrderHeader 
) 
SELECT * 
FROM OrderedOrders 
WHERE RowNumber BETWEEN 10 AND 20;

or something like this for 2000 and below versions...

SELECT TOP 10 * FROM (SELECT TOP 20 FROM Table ORDER BY Id) ORDER BY Id DESC