I have a question related to ORDER BY
or GROUP BY
clause.
For example I have below queries
SELECT country_name,COUNT(*) FROM user_location
WHERE country_name IS NOT NULL
GROUP BY country_name
ORDER BY COUNT(*) DESC
And
SELECT country_name,COUNT(*) As Total FROM user_location
WHERE country_name IS NOT NULL
GROUP BY country_name
ORDER BY Total DESC
In 2nd query I am using alias Total
for COUNT(*)
in ORDER BY
clause.
Is there any performance related differences in two queries ?
I've run the following test on a table with 1M products randomly related to 10K categories (MariaDB 10.0.19):
Execution time: 156 msec
Execution time: 156 msec
So there doesn't seem to be any difference in performance.
Note that with
ORDER BY
the engine will copy the result into a temporary table (See EXPLAIN:Using temporary; Using filesort
). So the value can't be recalculated, even when you useORDER BY COUNT(*)
.However - There is a difference (which I can not explain) when I use
ORDER BY COUNT(DISTINGT ...)
:Profile: 863 msec for
Copying to tmp table
Profile: 963 msec for
Copying to tmp table
An Alias is just a synonym, so any timing differences are probably due to the phase of the moon.