I am trying to insert dates along with other data into my SQL table:
insert into weather values
(1, 'London', -1, str_to_date('2021-01-01','y%-m%-d%')),
(2, 'London', -2, str_to_date('2021-01-02','y%-m%-d%')),
(3, 'London', 4, str_to_date('2021-01-03','y%-m%-d%')),
but I am getting the message below:
Error Code: 1411. Incorrect datetime value:
‘2021-01-01’ for function str_to_date
I’ve tried different combinations of dates and looked online but couldn’t find one because the format looks alright. Even MySQL documentation has the same syntax.
2
Answers
The correct format is :
'%Y-%m-%d'
%y
is for 2 digits year format, is working forstr_to_date('21-01-01','%y-%m-%d')
So your query should be :
Docs here
By now you should know that you had a typo inside your format, swapping the letter with the ‘%’ symbol (‘y%-m%-d%’ instead of ‘%Y-%m-%d’).
Although since you’re respecting the standard format in your date string, you can avoid the
STR_TO_DATE
pattern matching operation and apply a simpleCAST
instead.Output:
Check the demo here.