MySQL: Disable foreign keys while updating database

Richard's picture

Originally found here: http://www.stetsenko.net/2008/10/mysql-how-to-ignore-checking-of-foreign-key-constraints-for-innodb-tables/

Making a note of it here because it always take me a while to find the above article.

You can switch off checking of foreign keys while you truncate/populate the tables in a MySQL database with:

SET FOREIGN_KEY_CHECKS = 0;

and re-enable it with:

SET FOREIGN_KEY_CHECKS = 1;

This is especially useful if, like me, you use an SQL script to pre-populate a MySQL database:

USE `database_name`;
 
SET FOREIGN_KEY_CHECKS = 0;
 
TRUNCATE `table_1`;
TRUNCATE `table_2`;
TRUNCATE `table_3`;
TRUNCATE `table_4`;
 
INSERT INTO `table_1` ...;
INSERT INTO `table_2` ...;
INSERT INTO `table_3` ...;
INSERT INTO `table_4` ...;
 
SET FOREIGN_KEY_CHECKS = 0;

Comments

Richard's picture

Thanks for the tip :-)

Thanks for the tip :-)

Anonymous's picture

Re: MySQL: Disable foreign keys while updating database

As well, I would wrap the majority of the SQL inside a transaction. I normally have 2 files (for the trunk of my projects), one structure.sql and one data.sql. At the top of each:

SET FOREIGN_KEY_CHECKS=0;
START TRANSACTION;

And at the bottom of each:
SET FOREIGN_KEY_CHECKS=1;
COMMIT;

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options