Skip to content
Advertisement

How can I use a calculated value in the WHERE clause?

I have the following SQL:

SELECT members.id, FLOOR(DATEDIFF('2019-10-25', crew_cv.dob) / 365.25) as age
FROM members
JOIN crew_cv ON members.id=crew_cv.user_id 
WHERE members.active=1 AND age>20 AND age<30 
ORDER BY crew_cv.last_name, crew_cv.first_name 
LIMIT 0,30

And I get the following error in phpMySQL:

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

How can I use the calculated value age in the WHERE clause?

Advertisement

Answer

In sql you can’t use alias in where clause (you must repeat the column code )

  SELECT members.id, FLOOR(DATEDIFF('2019-10-25', crew_cv.dob) / 365.25) as age
  FROM members
  JOIN crew_cv ON members.id=crew_cv.user_id 
  WHERE members.active=1 AND FLOOR(DATEDIFF('2019-10-25', crew_cv.dob) / 365.25)>20 
      AND age<FLOOR(DATEDIFF('2019-10-25', crew_cv.dob) / 365.25) 
  ORDER BY crew_cv.last_name, crew_cv.first_name 
  LIMIT 0,30

but you could create a view

create view my_view as 
select   members.id, crew_cv.last_name, crew_cv.first_name , FLOOR(DATEDIFF('2019-10-25', crew_cv.dob) / 365.25) as age
 FROM members
  JOIN crew_cv ON members.id=crew_cv.user_id 
  WHERE members.active=1

and then

SELECT id,  age, last_name, first_name
from  my_view 
where  age>20 AND age<30 
      ORDER BY last_name, first_name 
      LIMIT 0,30

or apply the condition to an having clause

In sql there the cluases are evalueated in a specific order
the where condition is evaluated before select clause (so the column alias name in not know in this phase) instead the having clause is evaluated after the select clause

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement