Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ON DELETE SET NULL on self referencing relationship

I have the table with one primary key and one foreign key referencing the same table primary key. i.e there are parents and childs in the same table. In sql sever there are three options for the delete rule. But it is only possible to set "NO ACTION" delete rule. I understand that it is not possible to set the "cascade" delete because of cycles and chaining. But why the other options are not allowed? Especially the "SET NULL" one.

Right now I have to do this manually. I have to find the child records and set the foreign key on null. After that I can delete the parent. Why is it not possible to set the rule for it?

like image 468
mattti Avatar asked Mar 27 '15 09:03

mattti


People also ask

Can set null be used with on delete command?

SET NULL. It is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is set to NULL when the parent data is deleted or updated.

What does on delete set null do?

What is a foreign key with "Set NULL on Delete" in Oracle? A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null. The records in the child table will not be deleted.

What is the difference between on delete set null and on delete cascade?

ON DELETE CASCADE : SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table. ON DELETE SET NULL : SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted.

What is delete rule in SQL?

The delete rule works as follows: With RESTRICT or NO ACTION, an error occurs and no rows are deleted. With CASCADE, the delete operation is propagated to the dependents of p in table D. With SET NULL, each nullable column of the foreign key of each dependent of p in table D is set to null.


1 Answers

Because it cannot perform two actions on the same table together which are:

-delete the parent.

-update the children.

A mutating table is a table that is being modified by an UPDATE, DELETE, or INSERT statement, or a table that might be updated by the effects of a DELETE CASCADE constraint.

you can overcome doing it manually by creating a procedure that would hold the parent key to delete the record and set the children to NULL.

procedure(parent_id) --takes the id as a parameter

   update table set null where foreign_key = parent_id;

   delete from table where id = parent_id;

end;
like image 75
Mohamed Mutter Avatar answered Oct 26 '22 23:10

Mohamed Mutter