Skip to content

Instantly share code, notes, and snippets.

@ralexandr
Last active September 2, 2020 06:00
Show Gist options
  • Save ralexandr/18e4648fffd5520f9e5fcde4fd6a900e to your computer and use it in GitHub Desktop.
Save ralexandr/18e4648fffd5520f9e5fcde4fd6a900e to your computer and use it in GitHub Desktop.
Non-blocking ALTER TABLE for mySQL
ALTER TABLE `my_awesome_database`.`user_transaction`
ADD FOREIGN KEY (`userId`) REFERENCES `my_awesome_database`.`user` (`id`),
ALGORITHM=INPLACE, LOCK=NONE;
@ralexandr
Copy link
Author

Problem:

...ALTER TABLE blocks reads (not just writes) at the point where it is ready to clear outdated table structures from the table and table definition caches. At this point, it must acquire an exclusive lock. To do so, it waits for current readers to finish, and blocks new reads and writes.

Solution:
In order to avoid blocking as much as possible, innoDB tables could be altered with 'inplace' algorithm and lock=none flag

@ralexandr
Copy link
Author

ralexandr commented Sep 2, 2020

In case you get ALGORITHM=INPLACE is not supported. Reason: Adding foreign keys needs foreign_key_checks=OFF

Run following query before altering your table (it will disable foreign checks only for your current db-connection)

SET SESSION foreign_key_checks=OFF;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment