sql group by versus distinct

后端 未结 5 1859
予麋鹿
予麋鹿 2020-12-01 10:30

Why would someone use a group by versus distinct when there are no aggregations done in the query?

Also, does someone know the group by versus distinct performance c

5条回答
  •  一整个雨季
    2020-12-01 11:02

    A little (VERY little) empirical data from MS SQL Server, on a couple of random tables from our DB.

    For the pattern:

    SELECT col1, col2 FROM table GROUP BY col1, col2
    

    and

    SELECT DISTINCT col1, col2 FROM table 
    

    When there's no covering index for the query, both ways produced the following query plan:

    |--Sort(DISTINCT ORDER BY:([table].[col1] ASC, [table].[col2] ASC))
       |--Clustered Index Scan(OBJECT:([db].[dbo].[table].[IX_some_index]))
    

    and when there was a covering index, both produced:

    |--Stream Aggregate(GROUP BY:([table].[col1], [table].[col2]))
       |--Index Scan(OBJECT:([db].[dbo].[table].[IX_some_index]), ORDERED FORWARD)
    

    so from that very small sample SQL Server certainly treats both the same.

提交回复
热议问题