Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert varchar column to date in mysql at database level

Tags:

mysql

I have one column date1 which is varchar type I want this column to date type. I tried changing field but all date is converted to 0000-00-00. format is dd-mm-yyyy but in varchar.

How can I convert the same date format but with date format using sql queries or similar but at database level ?

like image 215
Pratik Prajapati Avatar asked Jan 17 '13 11:01

Pratik Prajapati


3 Answers

UPDATE `table`
SET `column` = str_to_date( `column`, '%d-%m-%Y' );

More about STR_TO_DATE function.


Since your column name is date1, you can replace column with date1 in the above syntax, and the code shall be:

UPDATE `table`
SET `date1` = str_to_date( `date1`, '%d-%m-%Y' );
like image 118
hjpotter92 Avatar answered Nov 10 '22 23:11

hjpotter92


The other answers here are risky, because if they go wrong you'll lose your data. A safer way to do this is to create a new field on your database with a DATE (or DATETIME if you need time as well) format, then to run a query like

UPDATE `table` SET `my_new_date_field` = STR_TO_DATE( `my_old_data_field`, '%d/%m/%Y');

In this way, if the %d/%m/%Y bit is wrong, you won't lose your data.

Once you're happy, you can delete the old data field and rename the new one.

like image 21
PeteW Avatar answered Nov 11 '22 00:11

PeteW


use STR_TO_DATE Function of MySQL

FIRST you will need to update the value in date format.

UPDATE `tbl` SET `date1` = STR_TO_DATE(`date1`, '%d-%m-%Y') WHERE 1=1

THEN Convert the field to date.

Most importantly remember to insert date as Y-m-d format, after then.

like image 27
Dhruv Patel Avatar answered Nov 10 '22 22:11

Dhruv Patel