How to Temporarily Disable a Foreign Key Constraint in MySQL

How can I temporarily disable a foreign key constraint in MySQL?

Try DISABLE KEYS or

SET FOREIGN_KEY_CHECKS=0;

Make sure to

SET FOREIGN_KEY_CHECKS=1;

after.

How to disable and enable all constraints in table mysql incl. PK FK CHK UNI etc

Use the following to disable constraints:

-- disable UNIQ, PK, ...
ALTER TABLE <tablename> DISABLE KEYS;
-- diable FK
SET FOREIGN_KEY_CHECKS=0;

Check for instance this site for more examples. Restore with:

SET FOREIGN_KEY_CHECKS=1;
ALTER TABLE <tablename> ENABLE KEYS;

From the reference:

  • foreign_key_checks
  • DISABLE KEYS: " Use ALTER TABLE ... DISABLE KEYS to tell MySQL to stop updating nonunique indexes. ..."

p.s.: from InnoDB performance tuning tips

SET autocommit=0; 
SET unique_checks=0;
SET foreign_key_checks=0;

How can foreign key constraints be temporarily disabled using T-SQL?

If you want to disable all constraints in the database just run this code:

-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

To switch them back on, run: (the print is optional of course and it is just listing the tables)

-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).

If you are deleting all the data you may find this solution to be helpful.

Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.



Related Topics



Leave a reply



Submit