I was bit by the ‘No Aliases allowed in Where Clauses’. It also explained Linq-to-SQL’s seemingly strange syntax at the same time.
The SQL Order of Operations isn’t as its written by developers, but the other way around.
- FROM clause
- WHERE clause
- GROUP BY clause
- HAVING clause
- SELECT clause
- ORDER BY clause
So, when you have an aliased column, it can’t use that in the WHERE Clause because it hasn’t been told what that means yet. So what happens when you want to use the Aliased column in the Where Clause?
There’s a Hack you can use:
Wrap the entire statement (or that line, as applicable) with a SELECT statement that contains the WHERE Clause you want to alias.
For instance:
select * from ( select a + b as aliased_column from table ) dt where dt.aliased_column = whateveryouputhere.
It does it rather nicely. You can find the question and answer (not mine) on Stack Overflow.