-3

I have problems to get age of certain dates.

SELECT birthday, DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)), '%Y')+0 AS age FROM users;

The result is:

| 27-07-1955 | NULL |

What's wrong in this select?

Guif If
  • 535
  • 2
  • 7
  • 18

2 Answers2

0

Would this work?

SELECT TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS age FROM users;
Evert
  • 93,428
  • 18
  • 118
  • 189
Roemer
  • 1,124
  • 8
  • 23
  • no. all results are as NULL – Guif If Mar 31 '18 at 19:58
  • Then probably birthday is all NULL, or you have a wrong data type. It works perfectly fine on a normal datefield that is not null. I tested. – Roemer Mar 31 '18 at 20:11
  • I guess from your original posting you use a string. Which is not the right way to store dates, we have the DATE type for that. In that case you should use `SELECT TIMESTAMPDIFF(YEAR, str_to_date(birthday, '%d-%m-%Y'), CURDATE()) AS age FROM users;` But I highly recommend you use the right datatype. Also, the answer you accepted als a correct answer will give wrong answers. For people over 50 sometimes really wrong. – Roemer Mar 31 '18 at 20:21
-1

You can use this query, it better:

SELECT DATEDIFF(CURRENT_DATE, STR_TO_DATE(t.birthday, '%d-%m-%Y'))/365 AS ageInYears
  FROM YOUR_TABLE t
Vahid Moghadam
  • 90
  • 1
  • 11