Which is better: Distinct or Group By

后端 未结 6 991
南方客
南方客 2021-02-07 12:45

Which is more efficient?

SELECT  theField
FROM    theTable
GROUP BY theField

or

SELECT  DISTINCT theField
FROM    theTable


        
相关标签:
6条回答
  • 2021-02-07 13:09

    In MySQL, DISTINCT seems a bit faster than GROUP BY if theField is not indexed. DISTINCT only eliminate duplicate rows but GROUP BY seems to sort them in addition.

    0 讨论(0)
  • 2021-02-07 13:14

    In your example, both queries will generate the same execution plan so their performance will be the same.

    However, they both have their own purpose. To make your code easier to understand, you should use distinct to eliminate duplicate rows and group by to apply aggregate operators (sum, count, max, ...).

    0 讨论(0)
  • 2021-02-07 13:15

    Doesn't matter, it results in the same execution plan. (at least for these queries). These kind of questions are easy to solve, by enabling query analyzer or SSMS to show the execution plan and perhaps the server trace statistics after running the query.

    0 讨论(0)
  • 2021-02-07 13:25

    Hmmm...so far as I can see in the Execution Plan for running similar queries, they are identical.

    0 讨论(0)
  • 2021-02-07 13:26

    You can check the Execution Plan to look for the total cost of this statements. The answer may vary in different scenarios.

    0 讨论(0)
  • 2021-02-07 13:29

    In most cases, DISTINCT and GROUP BY generate the same plans, and their performance is usually identical

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