Performance of MySQL ALTER TABLE ADD COLUMN AFTER COLUMN - on a large table

Create another table and alter the new table. ( like Book Of Zeus did )

And using ALTER TABLE newtable DISABLE KEYS and ALTER TABLE newtable ENABLE KEYS before and after the inserting query can make it faster. ( like below )

CREATE TABLE newtable ....;
ALTER TABLE newtable ....;

ALTER TABLE newtable DISABLE KEYS;
INSERT INTO newtable ....;
ALTER TABLE newtable ENABLE KEYS;

DROP TABLE oldtable;

While the other answers are useful as examples of the syntax required to add columns to a table, the answer to the actual question was provided by N.B.:


  • You'd get more CPU usage since records would have to be shifted.
  • From the memory usage point of view - it'd be the same with AFTER COLUMN option and without it.
  • In most cases, a tmp table is created. There are MySQL engines that support hot schema changes (TokuDB being one) that don't create the tmp table and waste tons of resources.
  • However, if you're doing this with MyISAM or InnoDB - I'd say that "AFTER COLUMN" option will take slightly more time due to record shifting.

    – N.B.


Here's what I would do:

CREATE TABLE newtable LIKE oldtable;
ALTER TABLE newtable ADD COLUMN columnname INT(10) UNSIGNED NOT NULL DEFAULT 0; 

I don't know the type of your column. I give an example with INT. Now here you can specify WHERE you want to add this new column. By default it will add it at the end unless you specify the AFTER keyword, if you provide it, you will have to specify in the order you will insert otherwise you need to put it at the end.

INSERT INTO newtable SELECT field1, field2, field3 /*etc...*/, newcolumn = 0 FROM oldtable; 

OR, if you added it between columns:

# eg: ALTER TABLE newtable ADD COLUMN columnname INT(10) UNSIGNED  NULL AFTER field2; 
INSERT INTO newtable SELECT field1, field2, newcolumn = 0, field3 /*etc...*/ FROM oldtable; 

You can add a where clause if you want to do them in batch.

Once all the records are there

DROP TABLE oldtable;
RENAME TABLE newtable to oldtable;

Tags:

Mysql