0

I am trying to determine the age of the people that are listed in my database. This is what I came up with, but I can't seem to limit the query to show people who are only 18 and under.

SELECT 
  * 
FROM 
  patientdetails 
WHERE 
  ageInYears IN (
    SELECT 
      DATEDIFF(CURRENT_DATE, STR_TO_DATE(p.DOB, '%d-%m-%Y'))/365 AS ageInYears 
    FROM 
      patientdetails p
  ) < 19
Kjuly
  • 34,476
  • 22
  • 104
  • 118
Kevin Weber
  • 198
  • 2
  • 11

3 Answers3

1

I believe something like this should work:

SELECT * 
FROM patientdetails 
WHERE DATEDIFF(CURRENT_DATE, STR_TO_DATE(p.DOB, '%d-%m-%Y'))/365 < 19
Jordan Kaye
  • 2,837
  • 15
  • 15
0

You don't need the subquery:

SELECT *
FROM PatientDetails pd
WHERE DATEDIFF(CURRENT_DATE, STR_TO_DATE(p.DOB, '%d-%m-%Y'))/365 <19
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

This sort of works:

SELECT *
FROM PatientDetails pd
WHERE DATEDIFF(CURRENT_DATE, STR_TO_DATE(pd.DOB, '%d-%m-%Y')) / 365 < 19

Dividing the days by 365 will fail to accommodate for leap years, meaning you will be off by 4 days guaranteed. You could divide by 365.25 and then subtract 0.75. I think that accounts for everything, but I'm shooting from the hip a bit. I'm not sure offhand if there would be integer errors with this calculation or not. I'm not sure how MySQL handles implicit typecasting.

I would be more inclined to do it this way. Logically, it's "all patients whose 19th birthday is in the future":

SELECT *
FROM PatientDetails pd
WHERE DATE_ADD( STR_TO_DATE(pd.DOB, '%d-%m-%Y'), INTERVAL 19 YEAR ) > CURDATE()

However, this exact question is addressed and explained in the MySQL documentation for date calculations, but it seems kind of ass-backwards to me:

SELECT name, birth, CURDATE(),
(YEAR(CURDATE())-YEAR(birth))
- (RIGHT(CURDATE(),5)<RIGHT(birth,5))
AS age
FROM pet
Bacon Bits
  • 30,782
  • 5
  • 59
  • 66