Why You Can't Group on Column Aliases
January 11, 2025
full-stack
note-to-self
When SQLing, I sometimes run across this -- I do
SELECT department AS dept, COUNT(*)
FROM employees
GROUP BY dept;
and it won't work and I wonder why. Here's why: The GROUP BY
clause is processed before the SELECT
. Usually, the order is:
- FROM: Where the data comes from
- WHERE: Filters the data from the source (
from
) - GROUP BY: If necessary, the data is grouped
- HAVING: If necessary, the groups are filtered by the aggregate conditions
- SELECT: The selected columns, including any aliases, are processed
To reference the same column in both the SELECT
and GROUP BY
clauses, you should use the actual column name instead of the alias:
SELECT department AS dept, COUNT(*)
FROM employees
GROUP BY department;
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.