Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a foreign key constrained table?

Why doesn't a TRUNCATE on mygroup work? Even though I have ON DELETE CASCADE SET I get:

ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (mytest.instance, CONSTRAINT instance_ibfk_1 FOREIGN KEY (GroupID) REFERENCES mytest.mygroup (ID))

drop database mytest; create database mytest; use mytest;  CREATE TABLE mygroup (    ID    INT NOT NULL AUTO_INCREMENT PRIMARY KEY ) ENGINE=InnoDB;  CREATE TABLE instance (    ID           INT NOT NULL AUTO_INCREMENT PRIMARY KEY,    GroupID      INT NOT NULL,    DateTime     DATETIME DEFAULT NULL,     FOREIGN KEY  (GroupID) REFERENCES mygroup(ID) ON DELETE CASCADE,    UNIQUE(GroupID) ) ENGINE=InnoDB; 
like image 641
user391986 Avatar asked Mar 27 '11 21:03

user391986


People also ask

How do you truncate a table with a foreign key constraint?

You can't truncate a table that has a foreign key constraint, that is the whole reason for having a constraint. You will need to delete and re-create the constraints so make sure you script them out before deleting them.

Can we truncate table with foreign key?

You cannot truncate a table that has foreign key constraints.

Does truncate delete constraints?

Truncate also has the ability to reset the seed to its initial value. On delete triggers are also not fired and all foreign keys constraint must be removed or disabled. Instead of removing all constraints, it is possible to tell SQL Server to not check foreign key.


1 Answers

Yes you can:

SET FOREIGN_KEY_CHECKS = 0;  TRUNCATE table1; TRUNCATE table2;  SET FOREIGN_KEY_CHECKS = 1; 

With these statements, you risk letting in rows into your tables that do not adhere to the FOREIGN KEY constraints.

like image 159
user447951 Avatar answered Sep 23 '22 10:09

user447951