I’ve talked to several people that have questions about how alter table works under the hood. They want to know how it handles locking tables why they can sometimes use a table during alter table and other times they can’t. Also why it’s so slow
First let’s look at the basic process alter table typically goes through.
- If a transaction is open on this thread, commit it.
- Acquire a read lock for the table.
- Make a temporary table with new structure
- Copy the old table to the temporary table row by row changing the structure of the rows on the fly.
- Rename the original table out of the way
- Rename the temporary table to the original table name.
- Drop the original table.
- Release the read lock.
The slowest part of the process is copying rows from the original table to the temporary table. For large tables this can take minutes …
[Read more]