ROW_NUMBER Without ORDER BY

前端 未结 4 653
囚心锁ツ
囚心锁ツ 2020-12-28 12:52

I\'ve to add row number in my existing query so that I can track how much data has been added into Redis. If my query failed so I can start from that row no which is updated

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 13:02

    There is no need to worry about specifying constant in the ORDER BY expression. The following is quoted from the Microsoft SQL Server 2012 High-Performance T-SQL Using Window Functions written by Itzik Ben-Gan (it was available for free download from Microsoft free e-books site):

    As mentioned, a window order clause is mandatory, and SQL Server doesn’t allow the ordering to be based on a constant—for example, ORDER BY NULL. But surprisingly, when passing an expression based on a subquery that returns a constant—for example, ORDER BY (SELECT NULL)—SQL Server will accept it. At the same time, the optimizer un-nests, or expands, the expression and realizes that the ordering is the same for all rows. Therefore, it removes the ordering requirement from the input data. Here’s a complete query demonstrating this technique:

    SELECT actid, tranid, val,
     ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
    FROM dbo.Transactions;
    

    Observe in the properties of the Index Scan iterator that the Ordered property is False, meaning that the iterator is not required to return the data in index key order


    The above means that when you are using constant ordering is not performed. I will strongly recommend to read the book as Itzik Ben-Gan describes in depth how the window functions are working and how to optimize various of cases when they are used.

提交回复
热议问题