https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
We can see that some functions do not like incomplete dates:
Some date functions can be used with “zero” dates or incomplete dates such as ‘2001-11-00’, whereas others cannot.
I want to subtract two dates like this:
SELECT DATEDIFF(CURRENT_DATE(), birthdate)
birthdate
is a DATE
column according to the phpMyAdmin console.
But some of the birth dates don’t have the month or day, example '1874-00-00'
. You cannot get the days difference because the days are not known.
Is there a way to tell it to assume Jan 1 or something? Or would I need to resort to some building the date up myself so it recognizes it?
I really just need the approximate number of years difference. But I get NULL
.
Thanks.
2
Answers
Use only YEAR from your field & do simple subtraction:
It will work both for valid & invalid date
If you have dates like
'1874-00-00'
then the data type of the column isVARCHAR
unless you have disabledNO_ZERO_IN_DATE
mode which is enabled by default.If the year is always included in your dates and it is 4 digits at the start then all you need is to subtract your date form the current year:
MySql will do implicit conversion of the
birthdate
to an integer which will be just the year.For this sample data:
the result will be:
Or if you want to be more precise when the
birthdate
s are valid dates:See the demo.