Change column name without recreating the MySQL table

Ran picture Ran · Nov 17, 2011 · Viewed 7.7k times · Source

Is there a way to rename a column on an InnoDB table without a major alter?

The table is pretty big and I want to avoid major downtime.

Answer

Bill Karwin picture Bill Karwin · Nov 17, 2011

Renaming a column (with ALTER TABLE ... CHANGE COLUMN) unfortunately requires MySQL to run a full table copy.

Check out pt-online-schema-change. This helps you to make many types of ALTER changes to a table without locking the whole table for the duration of the ALTER. You can continue to read and write the original table while it's copying the data into the new table. Changes are captured and applied to the new table through triggers.

Example:

pt-online-schema-change h=localhost,D=databasename,t=tablename \
  --alter 'CHANGE COLUMN oldname newname NUMERIC(9,2) NOT NULL'

Update: MySQL 5.6 can do some types of ALTER operations without rebuilding the table, and changing the name of a column is one of those supported as an online change. See http://dev.mysql.com/doc/refman/5.6/en/innodb-create-index-overview.html for an overview of which types of alterations do or don't support this.