LIMIT 10..20 in SQL Server
For SQL Server 2012 + you can use.
SELECT *
FROM sys.databases
ORDER BY name
OFFSET 5 ROWS
FETCH NEXT 5 ROWS ONLY
The LIMIT
clause is not part of standard SQL. It's supported as a vendor extension to SQL by MySQL, PostgreSQL, and SQLite.
Other brands of database may have similar features (e.g. TOP
in Microsoft SQL Server), but these don't always work identically.
It's hard to use TOP
in Microsoft SQL Server to mimic the LIMIT
clause. There are cases where it just doesn't work.
The solution you showed, using ROW_NUMBER()
is available in Microsoft SQL Server 2005 and later. This is the best solution (for now) that works solely as part of the query.
Another solution is to use TOP
to fetch the first count + offset rows, and then use the API to seek past the first offset rows.
See also:
- "Emulate MySQL LIMIT clause in Microsoft SQL Server 2000"
- "Paging of Large Resultsets in ASP.NET"
as you found, this is the preferred sql server method:
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY name) as row FROM sys.databases
) a WHERE a.row > 5 and a.row <= 10
If you are using SQL Server 2012+ vote for Martin Smith's answer and use the OFFSET
and FETCH NEXT
extensions to ORDER BY
,
If you are unfortunate enough to be stuck with an earlier version, you could do something like this,
WITH Rows AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY [dbo].[SomeColumn]) [Row]
, *
FROM
[dbo].[SomeTable]
)
SELECT TOP 10
*
FROM
Rows
WHERE Row > 10
I believe is functionaly equivalent to
SELECT * FROM SomeTable LIMIT 10 OFFSET 10 ORDER BY SomeColumn
and the best performing way I know of doing it in TSQL, before MS SQL 2012.
If there are very many rows you may get better performance using a temp table instead of a CTE.
How about this?
SET ROWCOUNT 10
SELECT TOP 20 *
FROM sys.databases
ORDER BY database_id DESC
It gives you the last 10 rows of the first 20 rows. One drawback is that the order is reversed, but, at least it's easy to remember.