How to temporarily disable foreign key checks in MySQL?

Usually it is not a good idea to disable your foreign keys because they make sure that the integrity of the data is maintained. But when you would like to drop some or all of your tables, the presence of foreign keys could pervent that.

To get around this problem you just need to temporarily disable the foreign keys before running the DROP statements and enable them after the DROPs are completed.

To disable foreign key checks:

SET FOREIGN_KEY_CHECKS=0;

To enable foreign key checks:

SET FOREIGN_KEY_CHECKS=1;

Putting it all together with some DROP statements:

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE users;
DROP TABLE messages;

SET FOREIGN_KEY_CHECKS=1;

To make sure you don’t forget to switch it back on I recommend running the disable and enable statements together, as you can see in the above example.