Is there Performance related difference in using aggregate function in ORDER BY clause and alias of aggregate function?

隐身守侯 提交于 2019-12-10 23:02:02

问题


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 ?


回答1:


I've run the following test on a table with 1M products randomly related to 10K categories (MariaDB 10.0.19):

select p.categoryId, count(*) as total
from products p
group by p.categoryId
having count(*) = 100

Execution time: 156 msec

select p.categoryId, count(*) as total
from products p
group by p.categoryId
having total = 100

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 use ORDER BY COUNT(*).

However - There is a difference (which I can not explain) when I use ORDER BY COUNT(DISTINGT ...):

select p.categoryId, count(distinct p.productData) as total
from products p
group by p.categoryId
order by total

Profile: 863 msec for Copying to tmp table

select p.categoryId, count(distinct p.productData) as total
from products p
group by p.categoryId
order by count(distinct p.productData)

Profile: 963 msec for Copying to tmp table




回答2:


An Alias is just a synonym, so any timing differences are probably due to the phase of the moon.



来源:https://stackoverflow.com/questions/45636306/is-there-performance-related-difference-in-using-aggregate-function-in-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!