jeffery_the_wind
jeffery_the_wind

Reputation: 18228

MySQL Error: Incorrect datetime value: '01/27/1989' for function str_to_date

I know that this question is very similar to the question posted here. But I cannot figure out why I am getting this error. This query syntax is:

update schema.table set date_field = str_to_date(date_field, '%m/%d/%Y') where str_to_date(date_field, '%Y-%m-%d') is null;

The where clause is there to make sure it doesn't change any dates that are already formatted correctly. It throws this error:

Error Code: 1411. Incorrect datetime value: '01/27/1989' for function str_to_date

I can execute the following query without any problems or errors, this is how i test before I make the changes:

select row_id, date_field, str_to_date(date_field, '%m/%d/%Y'), str_to_date(date_field, '%Y-%m-%d') from schema.table;

This error is strange because when doing this last select statement, if there is improper or unexpected format str_to_date will just return null. I have also used this same syntax (without the where clause) for changing time formats, and there was no problem. If the format was unexpected or incorrect it would just update that field with a null value. I don't know what is up with this error.

Upvotes: 0

Views: 5576

Answers (1)

user1191247
user1191247

Reputation: 12973

It is because of the WHERE clause. What is the current data in this column? Is it that some are in Y-m-d and some are m/d/Y? If so, you could use a regex for your WHERE clause -

UPDATE schema.table
SET date_field = STR_TO_DATE(date_field, '%m/%d/%Y')
WHERE date_field REGEXP('^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$');

Upvotes: 1

Related Questions