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