Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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.

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.

Pro: it allows you to reduce the quantity of SQL statements needed to perform delete actions.

Con: you could delete data that somewhat may be important for auditing in a later time. So it's important to keep it even if the parent row has been deleted. In this case the foreign key should receive a NULL value for example.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top