How to get age using BirthDate column by MySQL query?

I have a BirthDate column in a MySQL database table to save the user’s birthday. Now I have a form in html / php with two fields (1. Age From 2. Age To).

If a user wants to get all users where their age is from 10 years to 20 years, is it possible to do this with a MySQL query using the BirthDate column.

thanks

+4
source share
5 answers

Your query will look something like this:

SELECT * FROM your_table WHERE YEAR(CURDATE())-YEAR(BirthDate) BETWEEN 10 AND 20; 
+8
source

You can do it

 SELECT column1, column2, DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(dob)), '%Y') + 0 as age WHERE age >10 AND age <20 ; 
+8
source
 select * from table where (year(curdate())-year(dob))-(right(curdate(),5)< right(dob,5) ) between 10 and 20 
+5
source

Another solution that checks the year and month:

 SELECT * FROM yourTable WHERE FLOOR(DATEDIFF(curdate(), birthdate) / 365.25) BETWEEN 10 AND 20 
+2
source

It can also be achieved with an auxiliary query:

 select * from (select *, TIMESTAMPDIFF(YEAR, birthday, NOW()) as age from table_name) as sub_query where age between 10 AND 20 
0
source

Source: https://habr.com/ru/post/1347204/


All Articles