Why SQL WHERE Clause Cannot Reference SELECT Aliases but ORDER BY Can
A common SQL pitfall involves using a SELECT alias inside a WHERE clause, which throws an 'invalid column name' error. This happens because SQL does not execute clauses in the order they are written — the actual processing sequence begins with FROM, followed by WHERE, GROUP BY, HAVING, SELECT, and finally ORDER BY. Since WHERE is evaluated before SELECT, any alias defined in the SELECT clause does not yet exist when the WHERE filter runs. ORDER BY, however, executes after SELECT, which is why referencing an alias there works without error. Developers filtering on aggregated values should use the HAVING clause instead, as it operates after GROUP BY and can correctly evaluate aggregate expressions.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in