Home >Database >Mysql Tutorial >Why Can't I Use Aliases in SQL's HAVING Clause?
Understanding the Limitations of Using Aliases in HAVING Clauses
In SQL, it might seem intuitive to utilize aliases for aggregates within the HAVING clause. However, this approach results in the error "Invalid column name" due to the specific evaluation order of SQL queries.
To comprehend this limitation, it is crucial to understand how SQL executes a query:
Therefore, since the HAVING clause is evaluated prior to the SELECT clause, the alias assigned to the aggregate in the SELECT statement (e.g., "col7") is not yet known to SQL when it evaluates the HAVING expression. Consequently, the error "Invalid column name 'col7'" occurs.
In contrast, the ORDER BY clause is evaluated after the SELECT statement, allowing aliases defined in the SELECT clause to be used. This is because the ORDER BY clause operates on the result set created by the SELECT statement.
To remedy this issue, replace the alias in the HAVING clause with the actual aggregate expression, as shown below:
select col1,count(col2) from --some join operation group by col1 having count(col2) >= 3
The above is the detailed content of Why Can't I Use Aliases in SQL's HAVING Clause?. For more information, please follow other related articles on the PHP Chinese website!