How to alter column type of multiple columns in a single MySQL query?



To alter column type of multiple columns in a single MySQL query, the syntax is as follows βˆ’

alter table yourTableName
modify column yourColumnName 1 yourDataType1,
modify column yourColumnName 2 yourDataType2,
.
.
N;

Let us first create a table βˆ’

mysql> create table DemoTable
(
   Id varchar(100),
   FirstName text,
   LastName text
);
Query OK, 0 rows affected (0.52 sec)

Let us check the description of table βˆ’

mysql> desc DemoTable;

This will produce the following output βˆ’

+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| Id        | varchar(100) | YES  |     | NULL    |       |
| FirstName | text         | YES  |     | NULL    |       |
| LastName  | text         | YES  |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+
3 rows in set (0.09 sec)

Following is the query to alter column type of multiple columns. Here, we have altered the column type of columns Id, FirstName and LastName βˆ’

mysql> alter table DemoTable
   modify column Id int,
   modify column FirstName varchar(50),
   modify column LastName varchar(50);
Query OK, 0 rows affected (1.63 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the description of table once again βˆ’

mysql> desc DemoTable;

This will produce the following output βˆ’

+-----------+-------------+------+-----+---------+-------+
| Field     | Type        | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| Id        | int(11)     | YES   |    | NULL    |       |
| FirstName | varchar(50) | YES   |    | NULL    |       | 
| LastName  | varchar(50) | YES   |    | NULL    |       |
+-----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Updated on: 2019-10-01T06:47:21+05:30

840 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements