# Temporarily Disable a Foreign Key Constraint in MySQL

> Use SET FOREIGN_KEY_CHECKS=0 to temporarily disable foreign key constraints in MySQL for bulk operations, or permanently alter the constraint with ON DELETE

**URL:** https://sentry.io/answers/mysql-foreign-key-constraint/

---

## The Problem

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? 

## The Solution

There are multiple ways to disable the foreign key constraint in MySQL.

### Disabling Temporarily

You can disable foreign key checks for your current session using the `FOREIGN_KEY_CHECKS` variable. In your MySQL session, execute the following command:

```mysql
SET FOREIGN_KEY_CHECKS=0;
```

You can re-enable the constraint using the following command:

```mysql
SET FOREIGN_KEY_CHECKS=1;
```

### Disabling Permanently

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:

```mysql
ALTER TABLE table_name DROP FOREIGN KEY fk_name1;
```

And then recreate the constraint with `ON DELETE SET NULL` condition:

```mysql
ALTER TABLE table_name
  ADD FOREIGN KEY (other_table_id)
        REFERENCES other_table(id)
        ON DELETE SET NULL;
```

---

*Source: [sentry.io/answers/mysql-foreign-key-constraint/](https://sentry.io/answers/mysql-foreign-key-constraint/)*
