How to alter multiple columns in a single statement in MySQL?

MySQLMySQLi Database

Alter multiple columns in a single statement with the help of CHANGE command. The syntax is as follows −

alter table yourTableName
change yourOldColumnName1 yourNewColumnName1 dataType,
yourOldColumnName2 yourNewColumnName2 dataType,
.
.
.
N

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table AlterMultipleColumns
   −> (
   −> Id int,
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.93 sec)

Now we have two columns with Id and Name. We will alter both the columns.

Here, we will alter Id with StudentId and Name with StudentName. The query to alter multiple columns is as follows −

mysql> alter table AlterMultipleColumns
   −> change Id StudentId varchar(10),
   −> change Name StudentName varchar(100);
Query OK, 0 rows affected (1.82 sec)
Records: 0 Duplicates: 0 Warnings: 0

Now you can check the columns have been altered or not with help of desc command. The query is as follows −

mysql> desc AlterMultipleColumns;

The following is the output −

+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| StudentId   | varchar(10)  | YES  |     | NULL    |       |
| StudentName | varchar(100) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
2 rows in set (0.06 sec)
raja
Published on 11-Jan-2019 14:54:52
Advertisements