Search code examples
sqlgroup-byalias

SQL - using alias in Group By


Just curious about SQL syntax. So if I have

SELECT 
 itemName as ItemName,
 substring(itemName, 1,1) as FirstLetter,
 Count(itemName)
FROM table1
GROUP BY itemName, FirstLetter

This would be incorrect because

GROUP BY itemName, FirstLetter 

really should be

GROUP BY itemName, substring(itemName, 1,1)

But why can't we simply use the former for convenience?


Solution

  • SQL is implemented as if a query was executed in the following order:

    1. FROM clause
    2. WHERE clause
    3. GROUP BY clause
    4. HAVING clause
    5. SELECT clause
    6. ORDER BY clause

    For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.

    So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.

    There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.