简体   繁体   中英

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

I want to achieve the following use the following command to add a column to an existing table:

   ALTER TABLE foo ADD COLUMN bar AFTER COLUMN old_column;

Can this option take substantially longer than the same command without the AFTER COLUMN option, as follows?

   ALTER TABLE foo ADD COLUMN bar;

Will the first command use a greater amount of tmp table space during execution to perform the action?

Context: I have a very large table (think over a billion rows) and I want to add an additional column using the AFTER COLUMN option, but I don't want to be penalized too much.

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;

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 NB :


  • 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.

    NB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM