Is there a way to convert Integer field into Varchar without losing data in MySQL?


You can use ALTER command to convert Integer into Varchar. Let us first create a table

mysql> create table DemoTable
(
   UserId int,
   UserFirstName varchar(20),
   UserLastName varchar(20),
   UserAge int
);
Query OK, 0 rows affected (0.73 sec)

Now check the description of table using DESC command:

mysql> desc DemoTable;

This will produce the following output −

+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| UserId        | int(11)     | YES  |     | NULL    |       |
| UserFirstName | varchar(20) | YES  |     | NULL    |       |
| UserLastName  | varchar(20) | YES  |     | NULL    |       |
| UserAge       | int(11)     | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
4 rows in set (0.17 sec)

Now you can change the integer data type to varchar without losing data:

mysql> alter table DemoTable change UserId UserId varchar(20);
Query OK, 0 rows affected (1.35 sec)
Records: 0 Duplicates: 0 Warnings: 0

Check the table description:

mysql> desc DemoTable;

This will produce the following output −

+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| UserId        | varchar(20) | YES  |     | NULL    |       |
| UserFirstName | varchar(20) | YES  |     | NULL    |       |
| UserLastName  | varchar(20) | YES  |     | NULL    |       |
| UserAge       | int(11)     | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

Updated on: 30-Jul-2019

922 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements