In a relational database, if a node in an object graph is deleted, how can the object graph's referential integrity be maintained?
For example:
A product is deleted, how is the invoice containing the order which had a reference to the product kept relevant, in that the order may no longer be relevant. Moreover, how is the order kept relevant?
Best Answer
Typically what you'd do in this scenario is, instead of deleting the products, just set a bit (or use an int type field if there could be more than 2 options) to denote that it is "deleted", or inactive.
Then, instead of calling a
DELETE
on that table for a product you'll no longer support, just do this:That way you don't cascade delete your orders records, or make them completely useless by setting their foreign key references to
NULL
orDEFAULT
.That is a pretty specific use-case that you brought up in your question, which is why I geared the first part of my answer off of that. But the beauty of Referential Integrity is that this is handled by the RDBMS with direction of the database designer/developer. Typically, you'd choose exactly how you want that foreign key to be handled when the referenced primary key entry is deleted or updated.
You didn't specify an RDBMS in your question, and I can't speak for the specifics of other RDBMSes, but for SQL Server you can choose the following:
NULL
when the referenced primary key record is deletedON DELETE SET NULL
, except instead of setting the referencing column toNULL
, it'll set it to theDEFAULT
value for that field