开发者

SQL, select Nth to Mth record from a table, which query is more efficient?

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 开发者_C百科* from A where id not in(select top 30 id from A) 

which of above 2 is more efficient? why?


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

See: Row Offset in SQL Server


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜