Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL convert column datatype from VARCHAR to INT

Tags:

I have a MySQL table with a VARCHAR(25) column that I want to convert to INT. All of the data in the column is either integer or blanks. I have tried this command:

ALTER TABLE ip MODIFY isp INT UNSIGNED NOT NULL; 

Unfortunately, since some of the existing rows are empty I get this error:

ERROR 1366 (HY000): Incorrect integer value: '' for column 'isp' at row 2 

Thanks for assistance.

like image 473
Brian G Avatar asked Feb 14 '14 16:02

Brian G


People also ask

Can we convert VARCHAR to int in SQL?

SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT. We'll also look at the more efficient and secure approach to transform values from one data type to another.

Can we change the datatype of a column in MySQL?

SQL query to change the column type in MySQL Server. We can use ALTER TABLE MODIFY COLUMN statement to change the datatype of the column. The syntax to change the datatype of the column is following.


1 Answers

before altering your table, try to update your values.

The goal is to set a '0' value in the fields where you have empty values (which can't be converted to int)

update ip set isp = '0' where trim(coalesce(isp, '')) = ''; 

If isp was not nullable, you can remove the coalesce function.

update ip  set isp = '0' where trim(isp) = ''; 
like image 102
Raphaël Althaus Avatar answered Oct 17 '22 00:10

Raphaël Althaus