SQL Row_Number() function in Where Clause without ORDER BY?

前端 未结 5 1112
北海茫月
北海茫月 2020-12-08 06:45

I found a bunch of questions on this topic with nice solutions but none of them actually deal with what to do if the data is not to be ordered in one specific way. For insta

相关标签:
5条回答
  • 2020-12-08 06:59

    The real problem with the approach that you are proposing is that order in the db is not guaranteed. It may coincidentally be returning to your application in the same order all of the time, but the SQL Standard guarantees no such order and may change depending on version or edition changes. The order of data from a SQL Server is not guaranteed without an order by clause. This design would be one that simply relies on 'luck.' If this possible variation in order has an impact on your implementation, you may want to change it now before you get too far into the implementation.

    Good article on this topic

    0 讨论(0)
  • 2020-12-08 07:07

    I use this to suppress the sort:

    ORDER BY @@rowcount
    

    @@rowcount is constant within the query. Example:

    select N = row_number() over (order by @@rowcount) from sys.columns
    

    Use of (select 0) in the ORDER BY seems to run much slower.

    0 讨论(0)
  • 2020-12-08 07:12

    Just in case it is useful to someone else. I just figured it out from elsewhere:

    WITH MyCte AS 
    (
        select   employee_id,
                 RowNum = row_number() OVER (ORDER BY (SELECT 0))
        from     V_EMPLOYEE 
        ORDER BY Employee_ID
    )
    SELECT  employee_id
    FROM    MyCte
    WHERE   RowNum > 0
    
    0 讨论(0)
  • 2020-12-08 07:15

    There's a solution that is simpler than above. You can still use ROW_NUMBER but supply an arbitrary value in the Order by clause:

    Select firstName, lastName, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) from tblPerson
    
    0 讨论(0)
  • 2020-12-08 07:23

    There is no such thing as ORIGINAL ORDER. SQL server cannot guarantee order of rows if you don't specify ORDER BY. You may get lucky and get results in particular order, but it may change any time.

    0 讨论(0)
提交回复
热议问题