Truncating MySQL tables with foreign key constraints
·1 min read·paskov
With foreign key checks enabled, MySQL does not allow TRUNCATE TABLE on an InnoDB table referenced by a foreign key in another table. TRUNCATE behaves differently from DELETE. Here are two ways to work around this restriction.
Option 1: Drop and recreate the foreign key constraints.
- Drop the foreign key constraints that reference the table.
- Truncate the table.
- Delete rows in related tables that now reference missing rows.
- Recreate the foreign key constraints.
Option 2: Temporarily disable foreign key checks.
This can be useful when clearing related tables during development. Run all of the following statements in the same database session:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;
TRUNCATE table2;
SET FOREIGN_KEY_CHECKS = 1;Disabling foreign key checks can compromise data integrity by leaving rows that reference missing records. Re-enabling FOREIGN_KEY_CHECKS does not validate existing rows or repair broken references.
Related Posts
CRLF in SQL Server
2012-05-06
SQL Server ODBC connection string
2011-09-19