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.

SELECTName n, GroupName gFROM HumanResources.Department DORDER BY g

But order by in this above query is executed at the end after select has created a column g.