Reputation: 6639
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.
Upvotes: 32
Views: 37746
Reputation: 6639
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.:
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.
Upvotes: 9
Reputation: 3008
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;
Upvotes: 11
Reputation: 49885
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;
Upvotes: 36