Why does SQL Server 2008 order when using a GROUP BY and no order has been specified?

后端 未结 4 721
无人共我
无人共我 2021-01-06 05:23

I\'m running into a very strange issue that I have found no explanation for yet. With SQL Server 2008 and using the GROUP BY it is ordering my columns without any ORDER BY s

4条回答
  •  佛祖请我去吃肉
    2021-01-06 06:03

    To answer this question, look at the query plans produced by both.

    The first SELECT is a simple table scan, which means that it produces rows in allocation order. Since this is a new table, it matches the order you inserted the records.

    The second SELECT adds a GROUP BY, which SQL Server implements via a distinct sort since the estimated row count is so low. Were you to have more rows or add an aggregate to your SELECT, this operator may change.

    For example, try:

    CREATE TABLE #Values ( FieldValue varchar(50) )
    
    ;WITH FieldValues AS
    (
        SELECT '4' FieldValue UNION ALL
        SELECT '3' FieldValue UNION ALL
        SELECT '2' FieldValue UNION ALL
        SELECT '1' FieldValue
    )
    INSERT INTO #Values ( FieldValue )
    SELECT
        A.FieldValue
    FROM FieldValues A
    CROSS JOIN FieldValues B
    CROSS JOIN FieldValues C
    CROSS JOIN FieldValues D
    CROSS JOIN FieldValues E
    CROSS JOIN FieldValues F
    
    SELECT
        FieldValue
    FROM #Values
    GROUP BY
        FieldValue
    
    DROP TABLE #Values
    

    Due to the number of rows, this changes into a hash aggregate, and now there is no sort in the query plan.

    With no ORDER BY, SQL Server can return the results in any order, and the order it comes back in is a side-effect of how it thinks it can most quickly return the data.

提交回复
热议问题