Skip to content
Advertisement

Referring to a Column Alias in a WHERE Clause

I get

“invalid column name daysdiff”.

Maxlogtm is a datetime field. It’s the little stuff that drives me crazy.

Advertisement

Answer

Normally you can’t refer to field aliases in the WHERE clause. (Think of it as the entire SELECT including aliases, is applied after the WHERE clause.)

But, as mentioned in other answers, you can force SQL to treat SELECT to be handled before the WHERE clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):

Parenthesis/Subselect:

Or see Adam’s answer for a CTE version of the same.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement