sqlmysqlwhere-clause

Age calculation not working


I am receiving an error during my age calculation.

Here is my query:

SELECT (YEAR(CURDATE()) - YEAR(STR_TO_DATE(birthdate, '%m/%d/%Y'))) age, name
FROM pers 
WHERE age >= 50 
ORDER BY age DESC 
LIMIT 100;

Here is the error:

#1054 - Unknown column 'age' in 'where clause'

"age" will output just fine when i remove the where clause, it just will not allow me to use it as a condition and im not sure why.


Solution

  • You cannot use column aliases in WHERE clauses. Use the entire expression or use the HAVING clause, although that is only applied after the ORDER BY (so it could be quite inefficient with large datasets).