3

I've already tried all other questions/solutions, and no answer. so here it is: I need to SELECT * FROM people WHERE (dob is 18 to 40)

but my dob is stored as DATE type YYYY-MM-DD

need to select people between 18 and 40 for example!

PeeHaa
  • 69,318
  • 57
  • 185
  • 258

5 Answers5

3

You need to use BETWEEN with some year calculation TIMESTAMPDIFF(YEAR,'1980-02-04',NOW())

SELECT * FROM people WHERE TIMESTAMPDIFF(YEAR,`dob`,NOW()) BETWEEN  18 AND 40

See fiddle here

TIMESTAMPDIFF

YEAR(date)

M Khalid Junaid
  • 62,293
  • 9
  • 87
  • 115
1
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
S Melikian
  • 45
  • 5
1

You have to calculate 40 years ago from today, and 18 years ago from today. Let's say it was 1940-01-01 and 1980-01-01, then it would be:

WHERE dob BETWEEN '1940-01-01' AND '1980-01-01';

redolent
  • 3,957
  • 5
  • 34
  • 43
0

Since age is relative to today:

select * from people where 
date_sub(curdate(), interval 40 year)  =< dob
and date_sub(curdate(), interval 18 year) >= dob

This will work on any version of mysql

gillyspy
  • 1,546
  • 8
  • 14
0

since I do not know the SQL dialect you use I take the full variant

since age is now - birth (!)

select * from people where
    current date - date(birth) > MINAGE
    and
    current date - date(birth) < MAXAGE

current date depends on SQL you are using

halfbit
  • 3,473
  • 2
  • 30
  • 45