I realized that putting an alias in GROUP BY
and call it in the SELECT
query is ungrammatical like below.
ERROR
SELECT
day, num
FROM users
GROUP BY DAYNAME(created_at) as day
ORDER BY COUNT(*) as num;
However, If I were to do the other way around(using an alias in SELECT
and then calling it in GROUP BY
), it works like below.
CORRECT
SELECT
DAYNAME(created_at) as day, COUNT(*) as num
FROM users
GROUP BY day
ORDER BY num;
I am aware of the order of execution in MySQL which tells me SELECT
is executed after GROUP BY
. but according to the result, it's really confusing to me. Can anyone make this clear, please?
This is another question that might be marked as a similar question but the answers don't seem to describe what's happening in detail. Group by Alias not working -stackoverflow