Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column name without recreating the MySQL table

Tags:

mysql

alter

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.

like image 262
Ran Avatar asked Nov 17 '11 18:11

Ran


People also ask

How can I change the column name in MySQL table?

To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.

How do I rename a column in a table?

Rename a column using table designer. In Object Explorer, right-click the table to which you want to rename columns and choose Design. Under Column Name, select the name you want to change and type a new one. On the File menu, select Save table name.

How do I edit a column in MySQL?

The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ]; table_name. The name of the table to modify.


1 Answers

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.

like image 198
Bill Karwin Avatar answered Sep 27 '22 20:09

Bill Karwin