Add a new column and index to an existing table with ALTER in a single MySQL query?


To add a new column to an existing table, use ADD. With that, to add a new index, use the ADD INDEX(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(100),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.69 sec)

Let us check the description of the table −

mysql> desc DemoTable;

This will produce the following output −

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| Id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| Name  | varchar(100) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

Here is the query to add a new column and index to an existing table −

mysql> alter table DemoTable
   -> add ArrivalDate DATETIME DEFAULT NOW(),
   -> add index(ArrivalDate);
Query OK, 0 rows affected (2.05 sec)
Records: 0 Duplicates: 0 Warnings: 0

Let us check the description of the table once again −

mysql> desc DemoTable;

This will produce the following output −

+-------------+--------------+------+-----+-------------------+----------------+
| Field       | Type         | Null | Key | Default           | Extra          |
+-------------+--------------+------+-----+-------------------+----------------+
| Id          | int(11)      | NO   | PRI | NULL              | auto_increment |
| Name        | varchar(100) | YES  |     | NULL              |                |
| ArrivalDate | datetime     | YES  | MUL | CURRENT_TIMESTAMP |                |
+-------------+--------------+------+-----+-------------------+----------------+
3 rows in set (0.01 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jul-2019

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements