Why disable foreign key checks!?

One cannot speak of relational databases without mentioning foreign keys as they are integral part of those kind of databases. But sometimes when you’re using MySQL you’ll find yourself in need of temporarily disabling foreign key checks. For example imagine a situation where you’re continuously trying to import a MySQL table but on each try you get FK error. Now that might be frustrating and you know it should work but only if you could somehow disable those pesky foreign keys if only for a moment.

How to disable FK?

Disabling foreign keys is very simple. If you wish to disable FK checks for only one session then you’d use the following command SET FOREIGN_KEY_CHECKS = 0. When you finished executing query that was giving you errors set back the FK checks to true SET FOREIGN_KEY_CHECKS = 1.

If you wish to disable FK checks not just for the current session but globally then you’d have to add GLOBAL keyword like this: SET GLOBAL FOREIGN_KEY_CHECKS = 0. Just remember same as before once you’ve finished with execution of your queries turn it back on SET GLOBAL FOREIGN_KEY_CHECKS = 1.

Read more