How to mimic MySQL’s Limit feature in MS T-SQL
Wednesday, August 23, 2006
One of the features that MS SQL Server 2000 is sorely lacking is the ability to select rows 10-20 or 11-20, or whatever range you want to select. In MySQL, you can just do a ” LIMIT 5, 10 ” , and it will pull the first 10 rows after the 5th row. This is very useful for paging through a set of items, for instance. SQL Server does provide a “SELECT TOP” feature, but you can’t set an offset to start from.
I came across a solution on Google Groups today, and it was so useful I just had to post about it… mostly so I’ll remember it. I’ve always used a stored procedure with derived tables or temporary tables to accomplish this in SQL Server, but here’s the simple way around it:
SELECT TOP 10 *
FROM (SELECT TOP 14 * FROM MyTable ORDER BY OrderColumn) as T
ORDER BY OrderColumn DESC
This gives you the bottom 10 of the top 14, which is the same thing as a MySQL ” SELECT * from MyTable LIMIT 5, 10″. If you wanted to retrieve the next 10 records, you would simply do this:
SELECT TOP 10 *
FROM (SELECT TOP 24 * FROM MyTable ORDER BY OrderColumn) as T
ORDER BY OrderColumn DESC
Obviously this is now selecting a larger amount of records on the second pass… and each time you page further you’d be selecting another 10 records… but this could still be very useful. Note that this method only works if you are sorting your results. Of course you should be doing that anyway, right ?
March 23rd, 2008 at 5:27 am
Hey,
that’s use ful, man. I just came across, that there was no LIMIT keyword in T-SQL. This one’s a nice one, even though it’ll be necessary to retrieve 10000 results first, if you wanted to select the last 10 of 10000. Can be quite annoying and not very performant.
Cheers, Paul
April 3rd, 2008 at 7:31 am
You seem to be forgetting that putting an order by clause on a select without a where causes the query engine to retrieve ALL records, order them, and then returning the top x of ALL records.
For instance, when you have 1000000 records in your table and you select the bottom 10 of the top 10000, 1000000 records are still being sorted(n log n) by the database engine, before selecting the top 10000, sorting them, and returning the top(or bottom) 10.
And I’m afraid there’s no way around it in TSQL. (Although I’m not 100% sure)