
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Column and Index to Existing Table with ALTER in MySQL
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)
Advertisements