It appears that I cannot use a computed value in a WHERE
clause?
SELECT id, TIMESTAMPDIFF(YEAR,dateOfBirth,CURDATE()) AS age
FROM user
WHERE age >= 20
I get ERROR 1054 (42S22): Unknown column 'age' in 'where clause'
. A possible workaround is to use subquery but it overly complicate things?
You can use a computed value in a WHERE
clause but not its Alias. You have to type the whole expression again
WHERE TIMESTAMPDIFF(YEAR,dateOfBirth,CURDATE()) >=20
An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column:
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined.
Reference
Yes, but mySQL behaviour isn't like you think
SELECT id, TIMESTAMPDIFF(YEAR,dateOfBirth,CURDATE()) AS age
FROM user
WHERE TIMESTAMPDIFF(YEAR,dateOfBirth,CURDATE()) >= 20
mySQL WHERE CLAUSE only look into columns and not into alias.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With