Mysql – Will the foreign key constraint throw an error while restoring a database

importMySQL

I have never faced any issue like this, but I am just curious. Let's say I have a database dump file with me and I want to import the dump file to another database.
There are 2 tables table_A and table_B. table_B contains a primary key and table_A contains the foreign key. And serially, table_A is first and then table_B.

So, when I update the database table_A will be created with a foreign key and next table_B will be created that contains the primary key.

So, will there be any error in this case?

Best Answer

Depending on the type of backup, that can indeed happen. It's therefore recommended to disable foreign key checks before the restore, e.g. with

SET FOREIGN_KEY_CHECKS=0;

and re-enabling them afterwards with

SET FOREIGN_KEY_CHECKS=1;

This has another advantage: MySQL won't check the foreign key for every single imported record, but for all records at once. This will speed up your restore.

See Disabling foreign key checks on the command line on Stack Overflow.