Home >Database >Mysql Tutorial >Can I Use Column Aliases in MySQL's WHERE Clause?
Use aliases in MySQL WHERE clause
In MySQL, aliases are often used to give temporary names to derived columns. Although convenient for reference, using them in a WHERE clause can cause errors.
MySQL restricts referencing column aliases in the WHERE clause. This is because the column value may not yet be determined when the WHERE clause is executed. Therefore, specifying an alias in the WHERE clause will trigger an "unknown column" error.
Solution
To overcome this limitation, there are several workarounds:
<code class="language-sql">HAVING avg_rating > 5</code>
<code class="language-sql">WHERE (sum(reviews.rev_rating)/count(reviews.rev_id)) > 5</code>
Restrictions
Please note that not all expressions are allowed in the WHERE clause. Aggregate functions like SUM require the HAVING clause.
As stated in the MySQL manual:
"References to column aliases in a WHERE clause are not allowed because the column value may not have been determined when the WHERE clause is executed."
The above is the detailed content of Can I Use Column Aliases in MySQL's WHERE Clause?. For more information, please follow other related articles on the PHP Chinese website!