Is ORDER BY and ROW_NUMBER() deterministic?

后端 未结 4 1211
醉话见心
醉话见心 2020-12-19 07:06

I\'ve used SQL in couple databases engines from time to time several years but have little theoretical knowledge so my question could be very \"noobish\" for some of you. Bu

4条回答
  •  醉话见心
    2020-12-19 07:40

    ORDER BY is not stable in SQL Server (nor in any other database, as far as I know). A stable sort is one that returns records in the same order that they are found in the table.

    The high-level reason is quite simple. Tables are sets. They have no order. So a "stable" sort just doesn't make sense.

    The lower-level reasons are probably more important. The database could be implementing a parallel sort algorithm. Such algorithms are not, by default, stable.

    If you want a stable sort, then include a key column in the sorting.

    This is alluded to in the documentation:

    To achieve stable results between query requests using OFFSET and FETCH, the following conditions must be met:

    The underlying data that is used by the query must not change. That is, either the rows touched by the query are not updated or all requests for pages from the query are executed in a single transaction using either snapshot or serializable transaction isolation. For more information about these transaction isolation levels, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL).

    The ORDER BY clause contains a column or combination of columns that are guaranteed to be unique.

提交回复
热议问题