Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column + index in same statement

Tags:

mysql

Is there a way to add the following as one statement instead of two? Each of the following statements takes a few hours to run so I was wondering if on creation it can be indexed?

alter table main_table add `last_updated` datetime DEFAULT CURRENT_TIMESTAMP;
alter table main_table add index (last_updated);
like image 583
David542 Avatar asked Oct 24 '25 23:10

David542


1 Answers

According to the manual, the relevant part of ALTER TABLE syntax is:

ALTER TABLE tbl_name
    [alter_specification [, alter_specification] ...]

alter_specification:
  | ADD [COLUMN] col_name column_definition
        [FIRST | AFTER col_name]
  | ADD {INDEX|KEY} [index_name]
        [index_type] (index_col_name,...) [index_option] ...

which says that you can do both adding a column and an index in the same statement.

I have tested this (on MySQL 5.6) and it works fine:

alter table main_table add `last_updated` datetime DEFAULT CURRENT_TIMESTAMP,
add index (last_updated);
like image 95
Nick Avatar answered Oct 27 '25 19:10

Nick