views:

50

answers:

3

Hi,

Maybe this is sort of a naive question...but I think that we should always have cascading deletes and updates. But I wanted to know are there problems with it and when should we should not do it? I really can't think of a case right now where you would not want to do an cascade delete but I am sure there is one...but what about updates should they be done always?

So can anyone please list out the pros and cons of cascading deletes and updates ? Thanks.

+1  A: 

Pros:

  • Data integrity - Can help avoid situations where a record refers to something that is no longer there.

Cons:

  • Performance - Cascading deletes/updates can be sloooooooooooooooooooow.
  • Complexity - It seems most people I work with are not used to cascades, so when you give them a new project that has it, they're a bit surprised the first time they trigger one of these cascades.
  • As others have already mentioned, can really mess things up when used improperly.
FrustratedWithFormsDesigner
Or, in standard form, SLW O20
jball
+2  A: 

This depends on the entities that are contained in the tables: if the side of the foreign key cannot exist without the side of the primary key, it makes sense to have cascaded delete.

E. g.: An invoice line item does not have any right to survive if the invoice is deleted.

But if you have a foreign key used for the relationship "works for" for the relationship between an employee and his/her boss, would you want to delete the employee if the boss leaves the company?

In addition: a technical issue is that some ORM (object relational mapping) tools are confused if dependent table entries change without them being responsible for that.

Frank
I am not sure that I would delete the boss exactly for this reason, I would probably inactivate the row
SQLMenace
@SQLMenace Would you keep all former employees forever in an employee table?But I hope you see the point: There are situations where the child has an existence by itself, even if the parent gets deleted.
Frank
I am not knocking on your answer, just saying what I would do..we record all changes anyhow and they go into a History table..depending on the company policy you might not be allowed to ever delete rows either
SQLMenace
@SQLMenance If you are not allowed to delete data, then of course a cascaded delete does not make sense at all, and the setting cascade/restrict/set null is irrelevant anyway.
Frank
+1  A: 

Pros:

  • When you delete a row from the Parent table all the foreign key rows are deleted
  • This is usually faster than implementing this with triggers
  • Orphaned rows are unlikely

Cons

  • Orphans are possible
  • If by mistake you delete a row in the parent table all the rows in the corresponding child tables will be deleted and it will be PITA to figure out what you deleted
SQLMenace

related questions