Question

How an empty table can throw a "A foreign key constraint fails"? I have two table: "listini" and "listinoprezzi", the second one has a foreign reference to the first one. However the "listinoprezzi" is empty, and when I try to truncate "listini" I get:

#1701 - Cannot truncate a table referenced in a foreign key constraint (`listiniprezzi`, CONSTRAINT `listiniprezzi_ibfk_4` FOREIGN KEY (`listino`) REFERENCES `listini` (`id`))

How is it possible?

Was it helpful?

Solution

As documented under TRUNCATE TABLE Syntax (emphasis added):

To achieve high performance, it bypasses the DML method of deleting data. Thus, it cannot be rolled back, it does not cause ON DELETE triggers to fire, and it cannot be performed for InnoDB tables with parent-child foreign key relationships.

Although TRUNCATE TABLE is similar to DELETE, it is classified as a DDL statement rather than a DML statement. It differs from DELETE in the following ways in MySQL 5.5:

[ deletia ]

  • TRUNCATE TABLE fails for an InnoDB table if there are any FOREIGN KEY constraints from other tables that reference the table. Foreign key constraints between columns of the same table are permitted.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top