Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will changing the mysql field type from INT to VARCHAR affect data previously stored as an INT

Tags:

mysql

varchar

I need to update a field in my production db from INT to VARCHAR.

The information in the current INT field is sensitive and I want to ensure that I don't alter it inadvertently or destroy it while changing the table type. For example, a user may have INT 123456 stored in this column and I want to ensure that is accurately stored once converted to VARCHAR.

What is the recommended process for accomplishing this?

Is there anything I need to worry about when using something like this?

ALTER TABLE table_sample CHANGE col_sample col_sample VARCHAR; 

Thanks in advance for any help.

like image 766
john k Avatar asked Sep 19 '11 01:09

john k


People also ask

Can we change the datatype of a column in MySQL?

If you want to change all columns of a certain type to another type, you can generate queries using a query like this: select distinct concat('alter table ', table_name, ' modify ', column_name, ' <new datatype> ', if(is_nullable = 'NO', ' NOT ', ''), ' NULL;') from information_schema.

Can we make the changes to the data stored in MySQL?

We can use COMMIT command to make the changes, made in a current transaction, permanently recorded in MySQL database. Suppose if we run some DML statements and it updates some data objects, then COMMIT command will record these updates permanently in the database.


1 Answers

Get your MySQL server into strict mode before you change the column type and make sure that your varchar(n) column has a large enough n to hold all of the integers when they're converted to strings. If you're not in strict mode then MySQL will silently truncate your data to fit your string size:

If strict SQL mode is not enabled and you assign a value to a CHAR or VARCHAR column that exceeds the column's maximum length, the value is truncated to fit and a warning is generated. For truncation of nonspace characters, you can cause an error to occur (rather than a warning) and suppress insertion of the value by using strict SQL mode.

But if you get into strict mode first:

mysql> set sql_mode = 'STRICT_ALL_TABLES'; mysql> alter table table_sample change col_sample col_sample varchar(6); 

You'll get a nice error message like this:

ERROR 1406 (22001): Data too long for column 'col_sample' at row ... 

if your integers don't all fit in your varchar.

And, of course, you will have a fresh verified backup of your database before you try to change the table. And by verified I mean that you have successfully restored your backup into a test database.

like image 70
mu is too short Avatar answered Sep 22 '22 13:09

mu is too short