If you ever wonder why column alias can be used in order by and not in where clause, it’s the logical query processing order. Pinal Dave blogged about the complete order here.
SELECT
Name n, GroupName g
FROM HumanResources.Department D
WHERE g = 'Executive General and Administration'
In the above query, from clause is executed first followed by where clause, and select goes last. So where clause is trying to use a column g which doesn’t exist until select completes execution and thus resulting in a “invalid column g” error.
SELECT
Name n, GroupName g
FROM HumanResources.Department D
ORDER BY g
But order by in this above query is executed at the end after select has created a column g.
And order by lived happily ever after >:]
~Sam.