Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql cascading deletes

I have a question about cascading deletes and foreign key references: Let's assume the following tables:

ITEMX                 | ITEMY
------------------    | ------------
ID    FKID_ITEMY      | ID
1     1               | 1
2     1               |

There is a cascade delete on FKID_ITEMY such that if I delete a row in ITEMX, the corresponding item in ITEMY will be deleted. My question is:

Will the delete of row ID 1 in ITEMX delete row ID 1 in ITEMY?

Or will just delete row ID 1 in ITEMX because row ID 2 is still referencing row ID 1 in ITEMY?

In other words, I would like to see row ID 1 of ITEMY deleted when there are no more references to it. Will a cascade delete achieve this?

like image 371
Jason Avatar asked Jun 25 '10 02:06

Jason


People also ask

What is Cascade delete in SQL?

Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.

How do I know if SQL Server has cascade delete?

Please use sys. foreign_keys for foreign key relations. The column - delete_referential_action helps you know if there is a delete on cascade.

How do I add delete on Cascade?

If you want to add an on delete cascade to an existing foreign key constraint, you are going to need two statements. The first statement will drop the constraint and the second statement will recreate it with the addition of the on delete clause.


1 Answers

You've got the concept of cascading deletes backwards.

Even though you declare FKID_ITEMY with a cascading delete option, nothing happens if you delete ITEMX where ID=1.

The cascading behavior affects what happens if the referenced row in ITEMY gets deleted. If you delete ITEMY where ID=1, it will delete both rows in ITEMX that reference that row.

You declare the cascading behavior on the foreign key in a dependent table, because you could have another dependent table ITEMZ, and you want it to behave differently. E.g. if you try to delete a row in ITEMY then you want that to be cancelled if there exist any referencing rows in ITEMZ.

like image 198
Bill Karwin Avatar answered Oct 14 '22 12:10

Bill Karwin