Tutorialspoint

1 Answer
karthikeya Boyini

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;

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;

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)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.