Ever wonder why when alias columns in "SELECT" clause of a TSQL code, you cannot use them in some other clauses but not on others?
Until I know the truth I was also confused and frustrated.
This is caused by how SQL server query parsing engine works. It process key words/clauses in a particular order.
- FROM
- Cross JOIN
- ON
- WHERE
- GROUP BY
- CUBE/ROLLUP
- HAVING
- SELECT
- Expressions, aggregates and alias
- DISTINCT
- TOP
- ORDER BY
- OFFSET / FETCH
As you can see from above order, alias is pretty down the order, just before ORDERY BY clause. So you can really use alias in ORDER BY clause only.
Kind of disappointing isn't it?
No comments:
New comments are not allowed.