
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 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)
Advertisements