October 2014 Archives

03-10-2014 15:55

How the MySQL ALTER command works.

What does an ALTER command do in MySQL? Quoting from this StackOverflow thread:

In most cases, ALTER TABLE works by making a temporary copy of the original table. The alteration is performed on the copy, and then the original table is deleted and the new one is renamed. While ALTER TABLE is executing, the original table is readable by other sessions. Updates and writes to the table are stalled until the new table is ready, and then are automatically redirected to the new table without any failed updates.
This makes a lot of sense. Using the "show processlist;" command, we can see the state an ALTER command is in. Such as "copy to tmp table ALTER TABLE mdl_sessions2 ENGINE=InnoDB". This gives one confident to cancel the operation while nothing has actually been changed. There might be a small window between checking the state of the command to actually cancelling it. But if it is a long running query (which would be the only way it would be humanly possible to cancel it) then the next step is altering the tmp table, so again, no issue if that is cancelled. So cancel away on an ALERT command while it is still copying. If it is in a state of altering the tmp table, but be careful you don't cancel it as it deletes the original table.

Posted by DaveQB | Permanent Link | Categories: IT