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
  • 71,436
  • 58
  • 190
  • 262

5 Answers5

4

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
  • 63,861
  • 10
  • 90
  • 118
1
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
S M
  • 57
  • 6
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
  • 4,159
  • 5
  • 37
  • 47
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,578
  • 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,773
  • 2
  • 34
  • 47