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
  • 732,580
  • 175
  • 1,330
  • 1,459
prime23
  • 3,362
  • 2
  • 36
  • 52

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
  • 18,104
  • 8
  • 63
  • 81
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
  • 18
  • 22