Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL str_to_date() function returns error

I keep receiving an error message when trying to convert a column, CreatedDate, of string date values in my Estimates table into the mySQL date format using str_to_date(). My column of data contains dates in m/d/yy format (for example: 1/26/16 or 3/3/16).

I ran this query:

UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )

mySQL is returning this error message:

Error
SQL query:
UPDATE Estimates
SET CreatedDate = str_to_date( CreatedDate, '%c/%e/%y' )
MySQL said: #1411 - Incorrect datetime value: '' for function str_to_date

What is wrong with my query?

like image 430
Liz Avatar asked Feb 06 '23 10:02

Liz


2 Answers

Disable NO_ZERO_DATE SQL mode:

set @old_sql_mode = @@sql_mode; 
set sql_mode = ''; 

Run your statement:

UPDATE Estimates
SET CreatedDate = NULLIF(str_to_date(CreatedDate, '%c/%e/%y'), FROM_DAYS(0))

Then enable original SQL modes:

set sql_mode = @old_sql_mode;

Disabling NO_ZERO_DATE mode will make STR_TO_DATE return zero date 0000-00-00 for invalid date strings, the same value is returned by FROM_DAYS(0). So NULLIF will convert zero dates to NULL.

This answer was helpful.

like image 143
mixel Avatar answered Feb 09 '23 00:02

mixel


The usual strategy for cleaning up data like this is as follows:

ALTER TABLE Estimates CHANGE COLUMN CreatedDate CreatedDateString VARCHAR(255);
ALTER TABLE Estimates ADD COLUMN CreatedDate DATE

UPDATE Estimates SET CreatedDate=STR_TO_DATE(CreatedDateString, '%c/%e/%y'))
  WHERE CreatedDateString IS NOT NULL AND CreatedDateString != ''

Then when you're confident everything got converted correctly:

ALTER TABLE Estimates DROP COLUMN CreatedDateString

The advantage to proper DATE fields is they're in a consistent format and when you add an INDEX on them data retrieval is very fast, even on ranges, like:

SELECT * FROM Estimates WHERE CreatedDate BETWEEN '2016-01-01' AND '2016-06-30'
like image 33
tadman Avatar answered Feb 09 '23 00:02

tadman