Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better: Distinct or Group By

Tags:

sql

sql-server

Which is more efficient?

SELECT  theField
FROM    theTable
GROUP BY theField

or

SELECT  DISTINCT theField
FROM    theTable
like image 217
wcm Avatar asked Dec 17 '08 15:12

wcm


People also ask

Should we use GROUP BY or distinct in SQL?

When and where to use GROUP BY and DISTINCT. DISTINCT is used to filter unique records out of the records that satisfy the query criteria. The "GROUP BY" clause is used when you need to group the data and it should be used to apply aggregate operators to each group.

Which is better distinct or GROUP BY in Oracle?

DISTINCT implies you want a distinct set of columns. However, GROUP BY implies you want to compute some sort of aggregate value which you are not. It will take more time in your case.

Which is better distinct or GROUP BY in Teradata?

Conclusion: There is no difference between GROUP BY and DISTINCT in Teradata.

Why is GROUP BY faster than distinct?

DISTINCT would usually be faster than GROUP BY if a) there's no index on that column and b) you are not ordering as well since GROUP BY does both filtering and ordering.


2 Answers

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, ...).

like image 158
dub Avatar answered Sep 23 '22 13:09

dub


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.

like image 22
Frans Bouma Avatar answered Sep 20 '22 13:09

Frans Bouma