Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Change date string to date type in place?

Tags:

date

sql

mysql

(Hi all. I'm new-ish to SQL and MySQL in particular. I know some PHP.)

I have a table which contains a "date_string" column. For legacy reasons, this is a text field, containing the date in d/m/YY format. e.g. "22/11/09" for 22nd November 2009.

Question: how could I convert all fields in this column to a standard MySQL date format (YYYY-mm-dd), in-place?

Or, failing being able to change it in place, given that the column type is text, how could I take each existing text-based date, and create a standard date in another column (of type 'date') within the table?

Thanks for any help.

like image 273
SirRatty Avatar asked Dec 05 '22 05:12

SirRatty


1 Answers

You probably want to use the STR_TO_DATE() function.

SELECT STR_TO_DATE(textdate, '%d/%m/%y') FROM MyTable...

Or create another column with DATE data type and copy the values:

ALTER TABLE MyTable ADD COLUMN realdate DATE;
UPDATE MyTable SET realdate = STR_TO_DATE(textdate, '%d/%m/%y');
like image 139
Bill Karwin Avatar answered Dec 10 '22 09:12

Bill Karwin