T-SQL Querying and Query Processing Order

The order in which we write T-SQL queries happen in this order:

however, the order the Query Processor on SQL Server processes the queries are in this order:

There are 2 ways to assign aliases to table in the FROM statement: “table alias” and “table AS alias”.

This shows why we cannot use column aliases in the WHERE, GROUP BY and HAVING clauses, because the SELECT statement has yet to be processed by the Query Processor. If you try to use an alias in any of the aforementioned columns, the Query Processor will return an “invalid column name” error.

There are 3 ways to assign an alias in the SELECT statement: “column AS alias”, “column alias” and “column = alias”. Using the version with the AS is considered standard by Microsoft. Remember, SELECT empID, firstName lastName does not error and does not return 3 columns!

HAVING is processed after the GROUP BY statement, to remove those rows that are not ‘true’ to the HAVING statement.

Views – 519

Leave a Reply