简体   繁体   中英

SQL Order of Operations - GROUP BY using field created in SELECT

I'm having trouble wrapping my head around a fairly elementary concept. Any help appreciated! I have learned from resources like this that the processing order of SQL operations is:

1) from 2) where 3) group by 4) having 5) select 6) order by 7) limit

However, I am perplexed when looking at this below query taken from DataCamp. If SQL is processing GROUP BY before SELECT, how can I use a field that was created within the SELECT statement (home_team) in the GROUP BY clause?

Thank you!

-- Identify the home team as Bayern Munich, Schalke 04, or neither
SELECT 
    CASE WHEN hometeam_id = 10189 THEN 'FC Schalke 04'
        WHEN hometeam_id = 9823 THEN 'FC Bayern Munich'
         ELSE 'Other' END AS home_team,
    COUNT(id) AS total_matches
FROM matches_germany
-- Group by the CASE statement alias
GROUP BY home_team;

Your particular query has:

GROUP BY hometeam_id
---------^

This is a column in the original data, not in the SELECT . The data is aggregated at the hometeam_id level. Then the CASE expression is applied after the aggregation.

Your question supposed that the query is written using:

GROUP BY home_team

And this might or might not work, depending on the database.

SQL does not have an "order of processing". The SQL engine analyzes the query and develops a directed-acyclic graph (DAG) representing the operations that need to be performed on the data.

What you are thinking of are rules for the scoping of identifiers in SQL. The big question is where an alias defined in a SELECT can be used.

Basically no databases allow column aliases to be used in the following clauses:

  • SELECT
  • FROM
  • WHERE

All databases allow column aliases in the following clauses:

  • ORDER BY .

Some databases allow column aliases in the GROUP BY and HAVING clauses.

Your database appears to be one that allows such usage in the GROUP BY .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM