1

I have a following table:

CREATE TABLE IF NOT EXISTS `Tree` (
  `id` int(10) NOT NULL,
  `parent` int(10) DEFAULT NULL,
  `text` varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `parent` (`parent`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `Tree` (`id`, `parent`, `text`) VALUES
(1, 1, '1'),
(2, 1, '1.1'),
(3, 1, '1.2'),
(4, 1, '1.3');

ALTER TABLE `Tree` ADD CONSTRAINT `tree_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `tree` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

After having executed all of the above statements a problem observed for the following one:

UPDATE  `Tree` SET  `id` =  '10' WHERE  `Tree`.`id` = 1

While it is expected that changing the main id would cause all linked parent records to update automatically due to ON UPDATE CASCADE constraint. Aren't these cascading referential integrity constraints are all about?

4
  • I'd expect a constraint error on the primary key, myself. You can't have two rows with an id = 2. Mar 27, 2011 at 1:13
  • Oooups, technical mistake, you get the problem when you are trying to set id = 10, thanks by the way
    – Lu4
    Mar 27, 2011 at 1:19
  • You say "After having executed all of the above statements a problem observed..." What kind of problem is observed? Did you try the statement? Does it cause an error message? What is the result?
    – Hammerite
    Mar 27, 2011 at 1:42
  • #1451 - Cannot delete or update a parent row: a foreign key constraint fails (test.tree, CONSTRAINT tree_ibfk_1 FOREIGN KEY (parent) REFERENCES tree (id) ON DELETE CASCADE ON UPDATE CASCADE)
    – Lu4
    Mar 27, 2011 at 7:19

1 Answer 1

6

The docs say the following (emphasis mine):

Deviation from SQL standards: If ON UPDATE CASCADE or ON UPDATE SET NULL recurses to update the same table it has previously updated during the cascade, it acts like RESTRICT. This means that you cannot use self-referential ON UPDATE CASCADE or ON UPDATE SET NULL operations. This is to prevent infinite loops resulting from cascaded updates. A self-referential ON DELETE SET NULL, on the other hand, is possible, as is a self-referential ON DELETE CASCADE. Cascading operations may not be nested more than 15 levels deep.

2
  • 2
    Uh-oh. A big gotcha and limitation of MySQL. Some people simply suggest SET FOREIGN_KEY_CHECKS=0; without knowing this. Good catch! Jul 26, 2013 at 9:16
  • 1
    I would rather avoid the use of foreign key in this situation, and manually use UPDATE Tree set Parent=10 WHERE Parent=1 instead. Feb 16, 2015 at 16:10

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.