Question

I had to bring in a whole bunch of tables from CSV files. A lot of these files had column that were INT but had null values. To speed up the import I just made all of the column VARCHAR. Now I have all this data in the tables but need to change the type. I'm able to do this in the MySQL workbench except for one problem -- It error's because of the null/blank values. Is there some sort of SQL magic that will allow me to convert these column types and ignore the nulls or replace them with the correct 'null value' for that data type?

Was it helpful?

Solution

You can update the columns to set blank fields as NULL as follows:

UPDATE mytable SET mycolumn=NULL WHERE TRIM(mycolumn,' ')='';

Then do your normal table alters as follows:

ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);

The 'DEFAULT NULL' is optional as fields by default allow null. This should allow you to convert the columns to whatever data types you wish without any problem except in the case where there is mixed data -- such as numbers, and strings, and you wish to make that column FLOAT.

The above example also does not take into account removing carriage returns, etc, in the event that a column contains a "\n" or "\r\n" and nothing else, it will not set it to NULL, but you can modify the "TRIM(mycolumn, ' ')" to meet those requirements if you have them : aka ...

UPDATE mytable SET mycolumn=NULL WHERE TRIM(mycolumn,"\n")='';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top