Bug #9762 Can't delete records which have foreign keys to themselves
Submitted: 8 Apr 2005 14:47 Modified: 22 Jan 2014 14:57
Reporter: Matthew Sgarlata Email Updates:
Status: Verified Impact on me:
Category:MySQL Server: InnoDB storage engine Severity:S3 (Non-critical)
Version:4.1 OS:Microsoft Windows (Win XP Pro)
Assigned to: CPU Architecture:Any

[8 Apr 2005 14:47] Matthew Sgarlata
If a table has a foreign key to itself, then rows which point to themselves cannot be deleted.  For example, say we have a table tree with a primary key of treeid and a column roottreeid which points to the root of the tree.  So roottreeid is a foreign key that references treeid.  With this data structure, we can't delete the root of the tree.  For example, the root node of a tree might have treeid=1 and thus would have roottreeid=1.  The following SQL command doesn't work:

delete from tree where treeid = 1

The error message is

Cannot delete or update a parent row: a foreign key constraint fails

How to repeat:
Try the scenario I described above
[8 Apr 2005 14:54] Heikki Tuuri

A workaround is to do:




'Deferred' constraint checking is in the TODO.

[8 Apr 2005 15:02] Matthew Sgarlata
FYI I figured out another workaround that will allow code to be run without any special checks for MySQL:

update tree set treerootid = null where treeid = 1
delete from tree where treeid = 1
[30 Sep 2008 10:39] Konstantin Osipov
[22 Jan 2014 14:57] Ståle Deraas
Abandoned use of "to be fixed later" setting to status "verified"
[13 Nov 2017 0:21] Federico Razzoli
Still happens in 8.0.3.

mysql> CREATE TABLE t (
    ->   id INT PRIMARY KEY,
    ->   parent INT NOT NULL,
    ->   FOREIGN KEY fk_test (parent)
    ->     REFERENCES t (id)
    -> ) ENGINE InnoDB;
Query OK, 0 rows affected (0.31 sec)

mysql> INSERT INTO t (id, parent) VALUES (1, 1);
Query OK, 1 row affected (0.05 sec)

mysql> DELETE FROM t WHERE id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`t`, CONSTRAINT `fk_test` FOREIGN KEY (`parent`) REFERENCES `t` (`id`))