1

An interview question:

write SQL Server query to return 30th to 40th record of a table A

my answer:

select top 10 * from (select top 40 * from tb desc) asc

select top 40 * from A where id not in(select top 30 id from A) 

which of above 2 is more efficient? why?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
prime23
  • 3,282
  • 2
  • 34
  • 50

2 Answers2

6

Don't use either of those, you can select those rows 30-40 somewhat more directly

See: Row Offset in SQL Server

Community
  • 1
  • 1
Jamie Wong
  • 17,778
  • 7
  • 60
  • 82
1

Using Row_number() is probably the best way to do this !

;With CTETable AS 
( 
  SELECT ROW_NUMBER() OVER (ORDER BY Column_Name DESC) AS ROW_NUM, * FROM tb WHERE <CONDITION> 
) 

SELECT Column_List FROM CTETable WHERE ROW_NUM BETWEEN <StartNum> AND <EndNum> 
Baaju
  • 1,992
  • 2
  • 16
  • 22