Maraino
Maraino

Reputation: 203

Add a new column in a large MySQL table

What would be the fastest way to add a new column in a large MySQL table?

ALTER TABLE ADD COLUMN creates a copy of the full table, and then replaces the old one with the new create table. While this process is running, the original table is readable, but all inserts and updates are stalled.

On large tables the copy can take a long time, is there any way to reduce it?

Upvotes: 15

Views: 5485

Answers (3)

VisionQuest
VisionQuest

Reputation: 171

Assuming an INNODB table:

  1. Copy {Existing Table} to {New Table} with no data (schema only)
  2. Use Alter table commands to add/alter columns on NEW table (should work in a flash)
  3. MYSQLDUMP existing table (using single-transaction, --no-drop-table, etc) to file
  4. import dump file into {New Table} (this, may take awhile, but old table still usable during this period)
  5. during maintenance period, DROP {Old Table} and rename {New Table} to previous {Old Table}.

Upvotes: 2

Evert
Evert

Reputation: 99687

You are stuck doing the ALTER TABLE. The best possible way to effectively deal with this, is to use a MASTER-MASTER setup.

You can modify MASTER1 first, and just use MASTER2 in production. Then you switch over and do the exact opposite.

Upvotes: 6

Paul Sonier
Paul Sonier

Reputation: 39490

Don't do this live on an active system. For an active system, do this while you take the system down for regular maintenance.

Upvotes: 2

Related Questions