My question is that how many times will COUNT(*) be called for each group? Three times or just one time?
If the answer is three times, how can i optimize it.
SELECT COUNT(*) AS num1, COUNT(*) / 10 AS num2, COUNT(*) * 10 AS num3
FROM table
GROUP BY column_name
This is a mysql sql problem, something to do with COUNT(*) function
2
Answers
In your query, COUNT(*) will be called three times for each group. This can be inefficient because it requires scanning the group multiple times.
To optimize it, you can calculate COUNT() once and then reuse that result for num2 and num3. You can achieve this by using a subquery or a common table expression (CTE) to calculate COUNT() and then reference it in the outer query. Here’s how you can do it with a subquery:
An experiment gives strange result.
fiddle
When we count the number of rows in the table then
COUNT(*)
is retrieved from the table metadata by the special way, the execution time differs almost twice, i.e. the value of the expression is unlikely to be reused.But when we count the amount of non-NULL values or when we use a conditions (the same for counting the amount in the subquery output) then the value is reused – we see approx. the same time for the queries which uses 1 or 3 expression copies.
Your query uses GROUP BY – so I predict that
COUNT(*)
will be reused.