SQL performance: WHERE vs WHERE(ROW_NUMBER)

后端 未结 3 1610
后悔当初
后悔当初 2020-11-29 20:47

I want get n-th to m-th records in a table, what\'s best choice in 2 below solutions:

Solution 1:

    SELECT * FROM Table WHERE ID >= n AND ID <         


        
3条回答
  •  孤独总比滥情好
    2020-11-29 21:09

    The 2nd answer is your best choice. It takes into account the fact that you could have holes in your ID column. I'd rewrite it as a CTE though instead of a subquery...

    ;WITH MyCTE AS
    (SELECT  *,  
             ROW_NUMBER() OVER (ORDER BY ID) AS row  
    FROM     Table)
    SELECT   *
    FROM     MyCTE
    WHERE    row >= @start 
             AND row <= @end
    

提交回复
热议问题