Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why shouldn’t you use DISTINCT when you could use GROUP BY?

Tags:

sql

mysql

According to tips from MySQL performance wiki:

Don't use DISTINCT when you have or could use GROUP BY.

Can somebody post example of queries where GROUP BY can be used instead of DISTINCT?

like image 791
Yada Avatar asked Dec 11 '09 13:12

Yada


People also ask

Can distinct be used with GROUP BY?

Well, GROUP BY and DISTINCT have their own use. GROUP BY cannot replace DISTINCT in some situations and DISTINCT cannot take place of GROUP BY. It is as per your choice and situation how you are optimizing both of them and choosing where to use GROUP BY and DISTINCT.

Is it better to use distinct or GROUP BY?

DISTINCT is used to filter unique records out of all records in the table. It removes the duplicate rows. SELECT DISTINCT will always be the same, or faster than a GROUP BY.

Why you shouldn't use select distinct?

As a general rule, SELECT DISTINCT incurs a fair amount of overhead for the query. Hence, you should avoid it or use it sparingly. The idea of generating duplicate rows using JOIN just to remove them with SELECT DISTINCT is rather reminiscent of Sisyphus pushing a rock up a hill, only to have it roll back down again.

Is there any difference between GROUP BY and distinct?

GROUP BY lets you use aggregate functions, like AVG , MAX , MIN , SUM , and COUNT . On the other hand DISTINCT just removes duplicates. This will give you one row per department, containing the department name and the sum of all of the amount values in all rows for that department.


2 Answers

If you know that two columns from your result are always directly related then it's slower to do this:

SELECT DISTINCT CustomerId, CustomerName FROM (...)

than this:

SELECT CustomerId, CustomerName FROM (...) GROUP BY CustomerId

because in the second case it only has to compare the id, but in the first case it has to compare both fields. This is a MySQL specific trick. It won't work with other databases.

like image 129
Mark Byers Avatar answered Oct 01 '22 03:10

Mark Byers


SELECT Code
FROM YourTable
GROUP BY Code

vs

SELECT DISTINCT Code
FROM YourTable
like image 25
Adriaan Stander Avatar answered Oct 01 '22 02:10

Adriaan Stander