Naveera A.
—The FOREIGN KEY
constraint, like other database constraints, ensures the accuracy and reliability of the data. It prevents deleting data from the referenced table, which can cause bugs and inaccuracy.
But sometimes we need to disable the foreign key constraint temporarily or permanently, for example, when truncating a table or deleting column values.
How can you disable a foreign key constraint in MySQL?
There are multiple ways to disable the foreign key constraint in MySQL.
If you want to disable the foreign key constraint for specific tables, you can use the DISABLE_KEYS
statement. Run the following command after replacing the table_name
with your table name:
ALTER TABLE table_name DISABLE KEYS;
Once you have performed the required operations, you can re-enable foreign key checks by running the following command:
ALTER TABLE table_name ENABLE KEYS;
If you want to disable foreign key checks across all databases and tables, you can use the FOREIGN_KEY_CHECKS
statement. In your MySQL execute the following command:
SET FOREIGN_KEY_CHECKS=0;
You can re-enable the constraint using the following command:
SET FOREIGN_KEY_CHECKS=1;
You may want to change the behavior of the foreign key permanently. For example, you may require that when you delete a record, the foreign key in the dependent tables should be set to NULL
.
To do this, first drop the existing foreign key constraint in the dependent table, like so:
ALTER TABLE table_name DROP FOREIGN KEY fk_name1;
And then recreate the constraint with ON DELETE SET NULL
condition:
ALTER TABLE table_name ADD FOREIGN KEY (other_table_id) REFERENCES other_table(id) ON DELETE SET NULL;
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.