How to add column and index in a single MySQL query?


Use ALTER for this with ADD. Following is the syntax −

alter table yourTableName
add yourColumnName DATETIME DEFAULT NOW(),
add index(yourColumnName);

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;

Output

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 column and index in a single MySQL query −

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;

Output

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)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements