Mysql – Why does adding a column to a MySQL table take incredibly long

alter-tableMySQL

I am using MySQL version 5.6 and I have a database that is in total around 110 GB in size. One of the tables, "outputs" is 49 GB in size. I tried to add a simple BOOL column to the outputs table with the following commands

ALTER TABLE outputs add spent BOOL;

that query took 6 days and 9 hours to complete. There was no index added, because it is a column with only two possible values. Does anyone have clues as to why this relatively simple query would take so long? FYI The outputs table has a primary key column and two other columns which are indexed. It has a total of 9 columns. I can edit this post if more information about my mysql configuration is required, but I'd need to know which parameters are important.

Best Answer

Adding a column in MySQL 5.6 requires the full table to be rebuilt. This becomes online in MySQL 8.0 though, provided the column is at the end of the table! The MySQL manual covers this under 14.13.1 Online DDL Operations (search in page for "Adding a column"):

  • Rebuilds Table?: Yes

Adding secondary indexes (i.e. not the primary key) should always be delayed until the last step so they can be sorted and optimally created. In the manual page I linked to, any operation that says In Place=No it will make sense to drop indexes first as well.