In Sql Server 2014 ORDER BY clause with OFFSET FETCH NEXT returns weird results

前端 未结 2 1481
我寻月下人不归
我寻月下人不归 2021-01-12 21:34

I am currently using Sql Server 2014 Professional and the current version is (12.0.4100). I have a View and I am trying to SELECT 10 rows with specific offset.
My View i

相关标签:
2条回答
  • 2021-01-12 22:29

    The documentation explains:

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

    . . .

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

    What happens in your case is that BeginTime is not unique. Databases in general -- and SQL Server in particular -- do not implement stable sorts. A stable sort is one where the rows are in the same order when the keys are the same. This is rather obvious, because tables and result sets represent unordered sets. They have no inherent ordering.

    So, you need a unique key to make the sort stable. Given your data, this would seem to be either duration, name, or both:

    SELECT * 
    ROM View_Name
    ORDER BY BeginTime ASC, Duration, Name
    OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;
    
    0 讨论(0)
  • 2021-01-12 22:32

    your order by should be unique,otherwise you will get indeterministic results(in your case ,begin time is not unique and your are not guarnteed to get same results every time).try changing your query to below to make it unique..

    SELECT * FROM View_Name ORDER BY duration OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
    

    Further to add ,your first query (select * from view) result set is not guaranteed to be accurate every time unless you have an outer order by .

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