convert the existing data varchar and column into a DATE - mysql

I stored date as a
varchar(256) latin1_swedish_ci
which shows up as: 11/22/2012
Now I wanted to convert the existing data and column to a DATE
What would be the easiest way to do this in SQL
thanks

To be on the safe side I personally would add a new column, Transfer the data and then delete
update `table` set `new_col` = str_to_date( `old_col`, '%m/%d/%Y' ) ;
Check the data is OK before you delete the column.

Edit to convert the existing data use:
STR_TO_DATE(t.datestring, '%d/%m/%Y')
Source: Convert String to Date
You may need to create a temp table to hold your data for conversion:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
Then you can truncate the table:
TRUNCATE [TABLE] tbl_name
Then you can alter the column datatype:
ALTER TABLE tablename MODIFY columnname DATE;
Then you can reload from the temp table:
INSERT INTO table
SELECT temptable.column1, temptable.column2 ... temptable.columnN
FROM temptable;

Use the STR_TO_DATE function.
Make a new column that is the correct datatype, move the strings from the old column into the new one with the STR_TO_DATE function, and then delete the old column.
UPDATE table SET new_col = STR_TO_DATE(old_col);
MySQL STR_TO_DATE Reference.

Related

ALTER COLUMN TYPE from tinyInt to Varchar in Mysql

I need to change column type from tinyInt(used as bool) to Varchar, without loosing data.
I have found many answers on stack-overflow but all of them are written in postgres and I have no idea how to rewrite it in Mysql.
Answers for this problem on stack-overflow looks like that:
ALTER TABLE mytabe ALTER mycolumn TYPE VARCHAR(10) USING CASE WHEN mycolumn=0 THEN 'Something' ELSE 'TEST' END;
How would similar logic look like in Mysql?
The syntax you show has no equivalent in MySQL. There's no way to modify values during an ALTER TABLE. An ALTER TABLE in MySQL will only translate values using builtin type casting. That is, an integer will be translated to the string format of that integer value, just it would in a string expression.
For MySQL, here's what you have to do:
Add a new column:
ALTER TABLE mytable ADD COLUMN type2 VARCHAR(10);
Backfill that column:
UPDATE mytable SET type2 = CASE `type` WHEN 0 THEN 'Something' ELSE 'TEST' END;
If the table has millions of rows, you may have to do this in batches.
Drop the old column and optionally rename the new column to the name of the old one:
ALTER TABLE mytable DROP COLUMN `type`, RENAME COLUMN type2 to `type`;
Another approach would be to change the column, allowing integers to convert to the string format of the integer values. Then update the strings as you want.
ALTER TABLE mytable MODIFY COLUMN `type` VARCHAR(10);
UPDATE mytable SET `type` = CASE `type` WHEN '0' THEN 'Something' ELSE 'TEST' END;
Either way, be sure to test this first on another table before trying it on your real table.

MYSQL-Update Existing Varchar column GUID values to Binary

I have a MYSQL database with GUID(or UUID) stored as Varchar(36). To improve performance, I want to convert them to Binary(16). For new values I can use something like
INSERT INTO sometable (SOMECOLUMN,UUID) VALUES
("Something",UNHEX([the-uuid]))
But how can I update the existing stored GUID values to Binary(16)?
Got the answer myself.
In case anyone else need it. Here it is
Change the Type of GUID column to VARBINARY to avoid right padding.
ALTER TABLE newtable MODIFY COLUMN id VARBINARY(36) NOT NULL;
Update the existing id data to the BINARY id
UPDATE newtable set id=UNHEX(REPLACE(id,'-',''));
Now change the column datatype to BINARY(16)
ALTER TABLE newtable MODIFY COLUMN id BINARY(16) NOT NULL;
Create a new column:
ALTER TABLE sometable ADD newColumn BINARY(16) AFTER UUID;
Update the table:
UPDATE sometable SET newColumn = UNHEX(UUID);
Drop the old column and rename the new one (if so desired—often best not to rename, so that application code that has not been updated will fail rather than use the table incorrectly):
ALTER TABLE sometable DROP UUID, CHANGE newColumn UUID BINARY(16);

Unable to convert varchar to datetime in MySql

In my MySql table there's a column called _time of type varchar. The values it holds are in the format: year month day hour minute without the whitespaces: 201409201945 I want to convert it to datetime so I'm doing this:
ALTER TABLE `my_table` CHANGE COLUMN `_time` `date_time` DATETIME NOT NULL;
And it throws this error for some reason:
Error Code: 1292. Incorrect datetime value: '201409201945' for column '_date_time' at row 1 0.036 sec
The three steps #Arkain mentioned would be with the help of the function STR_TO_DATE
-- add the new column
ALTER TABLE `my_table` ADD COLUMN `date_time` DATETIME;
-- update the new column with the help of the function STR_TO_DATE
UPDATE `my_table` SET `date_time` = STR_TO_DATE(`_time`, '%Y%m%d%H%i');
-- drop the old column
ALTER TABLE `my_table` DROP COLUMN `_time`;
The complete list of specifiers for STR_TO_DATE can be found at DATE_FORMAT, here an excerpt with those I used:
%d Day of the month, numeric (00..31)
%H Hour (00..23)
%i Minutes, numeric (00..59)
%m Month, numeric (00..12)
%Y Year, numeric, four digits
Demo of the UPDATE
If the new column should have the attribute NOT NOLL, one way could be to set the sql mode before the operation to '' and reset the sql_mode later on:
SET #old_mode = ##sql_mode;
SET ##sql_mode = ''; -- permits zero values in DATETIME columns
ALTER TABLE `my_table` ADD COLUMN `date_time` DATETIME NOT NULL;
UPDATE `my_table` SET `date_time` = STR_TO_DATE(`_time`, '%Y%m%d%H%i');
ALTER TABLE `my_table` DROP COLUMN `_time`;
SET ##sql_mode = #old_mode;
Updated Demo
If your varchar data were formatted like this '2014-09-20 19:45' altering your column's data type would work. Why? that's the character representation used by DATETIME and other time-oriented data types.
But it isn't. So, what choices do you have?
One is to use these four steps:
alter the table to add a new DATETIME column with a temporary name
do an UPDATE with no WHERE clause to fill in the values of that column
alter the table to drop the previous column
alter the table to rename your new column to have the same name as the column you just dropped.
Here's how that would go.
ALTER TABLE my_table ADD COLUMN tempstamp DATETIME
UPDATE my_table SET tempstamp = STR_TO_DATE(_time, '%Y%m%d%H%i')
ALTER TABLE my_table DROP COLUMN _time
ALTER TABLE my_table CHANGE tempstamp _time DATETIME NOT NULL
Another approach: Change the strings in your _time to valid datetime values, then alter your column. If your varchars() are wide enough to hold a few extra characters, try this.
UPDATE my_table SET `_time`=STR_TO_DATE(`_time`, '%Y%m%d%H%i')
ALTER TABLE my_table CHANGE `_time` `_time` DATETIME NOT NULL
This works because STR_TO_DATE() makes DATETIME values of your strings, and then MySQL casts them back to strings to store back into your varchar column. Then you can change the datatype to DATETIME.
You probably noticed I threw in NOT NULL. If you're going to put an index on that column, NOT NULL is a good thing to have. But, if some of your time values are missing, it won't work.
Because the database doesn't know what to do with 201409201945, it's not a valid DateTime format, therefore it can't change it
You can delete the data that is in it already, and then try changing it

How to convert a varchar column type to date type without losing the dates

I am looking for a way to change the datatype of a column. Currently, in my database, the date columns types were defined as varchar and I need to convert them back to the date type.
Any idea how to do it?
You will need to adapt this based your your exact table structure but something like;
CREATE TABLE temp (startdate varchar(255), stuff varchar(255));
INSERT INTO temp
SELECT startdate,stuff
FROM mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable ALTER COLUMN startdate DATETIME NOT NULL;
INSERT INTO mytable
SELECT CAST(startdate AS DATETIME), stuff FROM temp;
DROP TABLE temp;
First, create the new column with type data
Next, run update query, to populate the new column with the value of the old one, applying any conversion if needed
Next, drop the old column
Finally, rename the new column to the old one
Create a new DATE column with a temporary name
Populate the new column with an UPDATE query that makes use of STR_TO_DATE()
If everything's right, remove the VARCHAR column and rename the DATE column.
Mysql default date format is : YYYY-MM-DD . If your try to insert the date otherwise, as you actually did, the date will be inserted with these values : 000-00-00, giving you a hint to the acceptable date format for mySql.
Wanna share this for SQL server users. For me this method is much convenient and safer.
In your Table create new column "NewDate" (temporarily or name whatever you want).
Make sure no invalid Datetime format in the Table you want to convert. Try those formats here: https://www.w3schools.com/sql/trysqlserver.asp?filename=trysql_func_sqlserver_cast3 <--- you need to check thoroughly otherwise there would be an error executing the command below.
Execute this command:
UPDATE myTable
SET NewDate = CAST(OldDate AS datetime)
WHERE (OldDate <> '') AND (OldDate IS NOT NULL) --to make sure you cast only what is needed otherwise there would be an error.
You can now delete the old column i.e. "OldDate".
Finally you can drag and drop the new table you've created to the slot where you just deleted the old column in the table design.
If the field of your column is VARCHAR and stored date as DD-MM-YYYY then we have to convert the date in YYYY-MM-DD format by following PHP code.
$cd = array();
$cd1 = array();
$cdf = array();
$getdata = mysqli_query($link,"SELECT columnname FROM tablename");
while($row=mysqli_fetch_array($getdata))
{
$cd = $row['columnname'];
$cd1 = strtotime($cd);
$cdf = date('Y-m-d',$cd1);
mysqli_query($link,"UPDATE tablename SET columnname =
REPLACE(columnname,'$cd','$cdf')");
}
After running this PHP code, in your MySQL table change the datatype of your column to 'DATE'.
It works for me without losing or truncate data.

query sql convert text field dd/mm/yyyy to date field yyyy-mm-dd

I've imported a CSV file into mysql with dates in format dd/mm/yyyy.
I now need a query to convert it from text to date format yyy-mm-dd.
You could use the STR_TO_DATE(str, format) MySQL function.
Example switching out my_date_col for a converted one:
BEGIN;
ALTER TABLE `date_test`
ADD COLUMN `my_date_col_converted` DATE;
UPDATE `date_test`
SET `my_date_col_converted` = STR_TO_DATE(`my_date_col`, '%d/%c/%Y');
ALTER TABLE `date_test`
DROP COLUMN `my_date_col`;
ALTER TABLE `date_test`
CHANGE COLUMN `my_date_col_converted` `my_date_col` DATE;
COMMIT;
You can use STR_TO_DATE() in the following way to convert your text in to a DATE:
STR_TO_DATE( datefield , "%d/%m/%Y" )
If you need this DATE in a specific format, you can use DATE_FORMAT().
This probably isn't necessary in your case, but here's an example for completeness:
DATE_FORMAT( STR_TO_DATE( datefield , "%d/%m/%Y" ) , "%Y/%m/%d" )
So, you could do this over the whole table with a single UPDATE to replace the current data with the reformatted data (while keeping the datatype the same):
UPDATE tableName
SET originalDate = DATE_FORMAT(STR_TO_DATE(originalDate,"%d/%m/%Y" ),"%Y/%m/%d" );
Or, if you want to convert the datatype of the column DATE you could alter the table to create a new DATE formatted column, use the above update to fill that column, remove the original column, and then (optionally) rename the new column to the old name.
ALTER tableName
ADD modifiedDate DATE;
UPDATE tableName
SET modifiedDate = DATE_FORMAT( STR_TO_DATE( originalDate ,"%d/%m/%Y" ) ,"%Y/%m/%d" );
ALTER tableName
DROP COLUMN originalDate;
ALTER tableName
CHANGE COLUMN modifiedDate originalDate;
This should work but it doesn't:
BEGIN;
ALTER TABLE `date_test`
ADD COLUMN `my_date_col_converted` DATE;
UPDATE `date_test`
SET `my_date_col_converted` = STR_TO_DATE(`my_date_col`, '%d/%c/%Y');
ALTER TABLE `date_test`
DROP COLUMN `my_date_col`;
ALTER TABLE `date_test`
CHANGE COLUMN `my_date_col_converted` `my_date_col` DATE;
COMMIT;
Also this should work: Doesn't Work
UPDATE db_test SET anticipated_court_date = DATE_FORMAT(STR_TO_DATE(anticipated_court_date,"%d/%m/%Y" ),"%Y-%m-%d" );
Server version: 5.0.95-community-log MySQL Community Edition (GPL)
However this works:
SELECT STR_TO_DATE('8/31/12', '%m/%d/%Y'); // WORKS
Using MySQL - I couldn't find any solution that worked reliably. Even the same exact date wasn't converted successfully.
The solution I've found is this: PHP
$user_date = "8/31/12"; // WORKS
$mysql_date = date('Y-m-d H:i:s', strtotime($user_date));
The above were helpful, but the following worked for me on Mysql.
ALTER TABLE `tablename` ADD `newcolumn` DATE NOT NULL ;
UPDATE `tablename` SET `newcolumn`=STR_TO_DATE(`oldcolumn`, '%d/%c/%Y')
Now delete the oldcolumn (if you wish).