Can I depend on order of output when using row_number()

后端 未结 4 1177
孤独总比滥情好
孤独总比滥情好 2021-01-21 09:09

I believe the answer is no. And am looking for a counter example to show that order of output is not guaranteed, absent an order by clause.

4条回答
  •  清歌不尽
    2021-01-21 09:13

    As mentioned, you can't rely on row order without an ORDER BY.

    However, you can rely on the ROW_NUMBER() function value.

    SELECT
        principal_id, name, 
        ROW_NUMBER() OVER (ORDER BY principal_id DESC) AS DemoRank
    FROM
        msdb.sys.database_principals
    ORDER BY
        name
    

    If you consume the data in your client by DemoRank, then you would be OK, even without the ORDER BY clause

    If you rely on recordset ordering (ordinal index), then no.

    The example above gives first row (index = 0) as '##MS_PolicyEventProcessingLogin##', but using DemoRank value gives "db_denydatawriter"

    Basically, use ORDER BY.

提交回复
热议问题