How to use OFFSET and Fetch without Order by in SQL Server

Mohsen Tavoosi محسن طاوسی picture Mohsen Tavoosi محسن طاوسی · Jun 22, 2015 · Viewed 16.6k times · Source

I want use OFFSET and Fetch in my SQL server 2012 query.But without any order by.I can not use order by.Because my sort order will be lost. How can I use OFFSET and Fetch without order by and row number and where in my query? My 2 select tables have same structure.

INSERT INTO @TempTable [some columns]  
select [some columns] from table1 order by col1 
INSERT INTO @TempTable [same columns]
select [some columns] from table2 order by col2
select * from @TempTable OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY

This query has syntax error at OFFSET keyword.

Answer

Jörg picture Jörg · Jul 5, 2017

There is an even simpler way of providing a dummy ORDER BY clause:

select * from @TempTable ORDER BY(SELECT NULL) OFFSET 20 ROWS FETCH NEXT 50 ROWS ONLY