<p>When setting up foreign keys in SQL Server, under what circumstances should you have it cascade on delete or update, and what is the reasoning behind it?</p>

<p>This probably applies to other databases as well.</p>

<p>I'm looking most of all for concrete examples of each scenario, preferably from someone who has used them successfully.</p>

[{'answer_id': 59318, 'author': 'juan', 'author_id': 1782, 'author_profile': 'https://Stackoverflow.com/users/1782', 'pm_score': 3, 'selected': False, 'text': "<p>One example is when you have dependencies between entities... ie: Document -> DocumentItems (when you delete Document, DocumentItems don't have a reason to exist)</p>\n"}, {'answer_id': 59325, 'author': 'pauliephonic', 'author_id': 5374, 'author_profile': 'https://Stackoverflow.com/users/5374', 'pm_score': 2, 'selected': False, 'text': "<p>I try to avoid deletes or updates that I didn't explicitly request in SQL server. </p>\n\n<p>Either through cascading or through the use of triggers. They tend to bite you in the ass some time down the line, either when trying to track down a bug or when diagnosing performance problems.</p>\n\n<p>Where I would use them is in guaranteeing consistency for not very much effort. To get the same effect you would have to use stored procedures.</p>\n"}, {'answer_id': 59330, 'author': 'Loofer', 'author_id': 5552, 'author_profile': 'https://Stackoverflow.com/users/5552', 'pm_score': 4, 'selected': False, 'text': "<p>I never use cascading deletes.</p>\n\n<p>If I want something removed from the database I want to explicitly tell the database what I want taking out.</p>\n\n<p>Of course they are a function available in the database and there may be times when it is okay to use them, for example if you have an 'order' table and an 'orderItem' table you may want to clear the items when you delete an order. </p>\n\n<p>I like the clarity that I get from doing it in code (or stored procedure) rather than 'magic' happening. </p>\n\n<p>For the same reason I am not a fan of triggers either.</p>\n\n<p>Something to notice is that if you do delete an 'order' you will get '1 row affected' report back even if the cascaded delete has removed 50 'orderItem's. </p>\n"}, {'answer_id': 59366, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 6, 'selected': False, 'text': "<p>Foreign keys are the best way to ensure referential integrity of a database. Avoiding cascades due to being magic is like writing everything in assembly because you don't trust the magic behind compilers.</p>\n\n<p>What is bad is the wrong use of foreign keys, like creating them backwards, for example.</p>\n\n<p>Juan Manuel's example is the canonical example, if you use code there are many more chances of leaving spurious DocumentItems in the database that will come and bite you. </p>\n\n<p>Cascading updates are useful, for instance, when you have references to the data by something that can change, say a primary key of  a users table is the name,lastname combination. Then you want changes in that combination to propagate to wherever they are referenced.</p>\n\n<p>@Aidan, That clarity you refer to comes at a high cost, the chance of leaving spurious data in your database, which is <em>not small</em>. To me, it's usually just lack of familiarity with the DB and inability to find which FKs are in place before working with the DB that foster that fear.  Either that, or constant misuse of cascade, using it where the entities were not conceptually related, or where you have to preserve history.</p>\n"}, {'answer_id': 59381, 'author': 'Martynnw', 'author_id': 5466, 'author_profile': 'https://Stackoverflow.com/users/5466', 'pm_score': 4, 'selected': False, 'text': "<p>I do a lot of database work and rarely find cascade deletes useful. The one time I have used them effectively is in a reporting database that is updated by a nightly job. I make sure that any changed data is imported correctly by deleting any top level records that have changed since the last import, then reimport the modified records and anything that relates to them. It save me from having to write a lot of complicated deletes that look from  the bottom to the top of my database. </p>\n\n<p>I don't consider cascade deletes to be quite as bad as triggers as they only delete data, triggers can have all kinds of nasty stuff inside.</p>\n\n<p><strong>In general I avoid real Deletes altogether and use logical deletes (ie. having a bit column called isDeleted that gets set to true) instead.</strong></p>\n"}, {'answer_id': 59478, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 8, 'selected': True, 'text': '<p>Summary of what I\'ve seen so far:</p>\n\n<ul>\n<li>Some people don\'t like cascading at all.  </li>\n</ul>\n\n<h2>Cascade Delete</h2>\n\n<ul>\n<li>Cascade Delete may make sense when the semantics of the relationship can involve an exclusive <em>"is part of</em>" description.  For example, an OrderLine record is part of its parent order, and OrderLines will never be shared between multiple orders. If the Order were to vanish, the OrderLine should as well, and a line without an Order would be a problem.</li>\n<li>The canonical example for Cascade Delete is SomeObject and SomeObjectItems, where it doesn\'t make any sense for an items record to ever exist without a corresponding main record.</li>\n<li>You should <em>not</em> use Cascade Delete if you are preserving history or using a "soft/logical delete" where you only set a deleted bit column to 1/true.  </li>\n</ul>\n\n<h2>Cascade Update</h2>\n\n<ul>\n<li>Cascade Update may make sense when you use a real key rather than a surrogate key (identity/autoincrement column) across tables.</li>\n<li>The canonical example for Cascade Update is when you have a mutable foreign key, like a username that can be changed. </li>\n<li>You should <em>not</em> use Cascade Update with keys that are Identity/autoincrement columns.</li>\n<li>Cascade Update is best used in conjunction with a unique constraint.  </li>\n</ul>\n\n<h2>When To Use Cascading</h2>\n\n<ul>\n<li>You may want to get an extra strong confirmation back from the user before allowing an operation to cascade, but it depends on your application.</li>\n<li>Cascading can get you into trouble if you set up your foreign keys wrong.  But you should be okay if you do that right.</li>\n<li>It\'s not wise to use cascading before you understand it thoroughly.  However, it is a useful feature and therefore worth taking the time to understand.</li>\n</ul>\n'}, {'answer_id': 75796, 'author': 'Jen A', 'author_id': 12979, 'author_profile': 'https://Stackoverflow.com/users/12979', 'pm_score': 2, 'selected': False, 'text': "<p>I, like everyone else here, find that cascade deletes are really only marginally helpful (it's really not that much work to delete referenced data in other tables -- if there are lot of tables, you simply automate this with a script) but really annoying when someone accidentally cascade deletes some important data that is difficult to restore.   </p>\n\n<p>The only case where I'd use is if the data in the table table is highly controlled (e.g., limited permissions) and only updated or deleted from  through a controlled process (like a software update) that has been verified.</p>\n"}, {'answer_id': 75820, 'author': 'Mathias F', 'author_id': 13442, 'author_profile': 'https://Stackoverflow.com/users/13442', 'pm_score': 4, 'selected': False, 'text': '<p>I work a lot with cascading deletes. </p>\n\n<p>It feels good to know whoever works against the database might never leave any unwanted data. If dependencies grow I just change the constraints in the diagramm in Management Studio and I dont have to tweak sp or dataacces.</p>\n\n<p>That said, I have 1 problem with cascading deletes and thats circular references. This often leads to parts of the database that have no cascading deletes. </p>\n'}, {'answer_id': 216301, 'author': 'WW.', 'author_id': 14663, 'author_profile': 'https://Stackoverflow.com/users/14663', 'pm_score': 2, 'selected': False, 'text': '<p>One reason to put in a cascade delete (rather than doing it in the code) is to improve performance.</p>\n\n<p>Case 1: With a cascade delete</p>\n\n<pre><code> DELETE FROM table WHERE SomeDate &lt; 7 years ago;\n</code></pre>\n\n<p>Case 2: Without a cascade delete</p>\n\n<pre><code> FOR EACH R IN (SELECT FROM table WHERE SomeDate &lt; 7 years ago) LOOP\n   DELETE FROM ChildTable WHERE tableId = R.tableId;\n   DELETE FROM table WHERE tableId = R.tableid;\n   /* More child tables here */\n NEXT\n</code></pre>\n\n<p>Secondly, when you add in an extra child table with a cascade delete, the code in Case 1 keeps working.</p>\n\n<p>I would only put in a cascade where the semantics of the relationship is "part of".  Otherwise some idiot will delete half of your database when you do: </p>\n\n<pre><code>DELETE FROM CURRENCY WHERE CurrencyCode = \'USD\'\n</code></pre>\n'}, {'answer_id': 15156457, 'author': 'testpattern', 'author_id': 1326235, 'author_profile': 'https://Stackoverflow.com/users/1326235', 'pm_score': 3, 'selected': False, 'text': '<p>Use cascade delete where you would want the record with the FK to be removed if its referring PK record was removed. In other words, where the record is meaningless without the referencing record.</p>\n\n<p>I find cascade delete useful to ensure that dead references are removed by default rather than cause null exceptions.</p>\n'}, {'answer_id': 21076883, 'author': 'Durai Amuthan.H', 'author_id': 730807, 'author_profile': 'https://Stackoverflow.com/users/730807', 'pm_score': 3, 'selected': False, 'text': "<h2>ON Delete Cascade:</h2>\n\n<p>When you want <em>rows in child table to be deleted</em> If <em>corresponding row is deleted</em> in parent table.</p>\n\n<p>If <em>on cascade delete</em> isn't used then an error will be raised for <em>referential integrity</em>.</p>\n\n<h2>ON Update Cascade:</h2>\n\n<p>When you want <em>change in primary key</em> to be updated in <em>foreign key</em></p>\n"}, {'answer_id': 24368533, 'author': 'BrianBurkill', 'author_id': 2287960, 'author_profile': 'https://Stackoverflow.com/users/2287960', 'pm_score': 3, 'selected': False, 'text': '<p>I have heard of DBAs and/or "Company Policy" that prohibit using "On Delete Cascade" (and others) purely because of bad experiences in the past. In one case a guy wrote three triggers which ended up calling one another. Three days to recover resulted in a total ban on triggers, all because of the actions of one idjit.</p>\n\n<p>Of course sometimes Triggers are needed instead of "On Delete cascade", like when some child data needs to be preserved. But in other cases, its perfectly valid to use the On Delete cascade method. A key advantage of "On Delete cascade" is that it captures ALL the children; a custom written trigger/store procedure may not if it is not coded correctly. </p>\n\n<p>I believe the Developer should be allowed to make the decision based upon what the development is and what the spec says. A carpet ban based on a bad experience should not be the criteria; the "Never use" thought process is draconian at best. A judgement call needs to be made each and every time, and changes made as the business model changes. </p>\n\n<p>Isn\'t this what development is all about?</p>\n'}, {'answer_id': 25147620, 'author': 'Erik Hart', 'author_id': 832306, 'author_profile': 'https://Stackoverflow.com/users/832306', 'pm_score': 0, 'selected': False, 'text': '<p>If you\'re working on a system with many different modules in different versions, it can be very helpful, if the cascade deleted items are part of / owned by the PK holder. Else, all modules would require immediate patches to clean up their dependent items before deleting the PK owner, or the foreign key relation would be omitted completely, possibly leaving tons of garbage in the system if cleanup is not performed correctly.</p>\n\n<p>I just introduced cascade delete for a new intersection table between two already existing tables (the intersection to delete only), after cascade delete had been discouraged from for quite some time. It\'s also not too bad if data gets lost.</p>\n\n<p>It is, however, a bad thing on enum-like list tables: somebody deletes entry 13 - yellow from table "colors", and all yellow items in the database get deleted. Also, these sometimes get updated in a delete-all-insert-all manner, leading to referential integrity totally omitted. Of course it\'s wrong, but how will you change a complex software which has been running for many years, with introduction of true referential integrity being at risk of unexpected side effects?</p>\n\n<p>Another problem is when original foreign key values shall be kept even after the primary key has been deleted. One can create a tombstone column and an ON DELETE SET NULL option for the original FK, but this again requires triggers or specific code to maintain the redundant (except after PK deletion) key value.</p>\n'}, {'answer_id': 34983465, 'author': 'Mayank Chopra', 'author_id': 2494522, 'author_profile': 'https://Stackoverflow.com/users/2494522', 'pm_score': 1, 'selected': False, 'text': '<p>A deletion or update to S that removes a foreign-key value found in some tuples of R can be handled in one of three ways:</p>\n\n<ol>\n<li>Rejection</li>\n<li>Propagation</li>\n<li>nullification.</li>\n</ol>\n\n<p>Propagation is referred to as cascading.</p>\n\n<p>There are two cases:</p>\n\n<p>‣ If a tuple in S was deleted, delete the R tuples that referred to it.</p>\n\n<p>‣ If a tuple in S was updated, update the value in the R tuples that refer to it.</p>\n'}, {'answer_id': 41068520, 'author': 'Mark Allen', 'author_id': 7274511, 'author_profile': 'https://Stackoverflow.com/users/7274511', 'pm_score': 0, 'selected': False, 'text': '<p>Cascade deletes are extremely useful when implementing logical super-type and sub-type entities in a physical database. </p>\n\n<p>When separate super-type and sub-type tables are are used to physically implement super-types/sub-types (as opposed to rolling up all sub-type attributes into a single physical super-type table), there is a one-to-one relationship between these tables and the issue then becomes how to keep the primary keys 100% in sync between these tables.</p>\n\n<p>Cascade deletes can be a very useful tool to:</p>\n\n<p>1) Make sure that deleting a super-type record also deletes the corresponding single sub-type record.</p>\n\n<p>2) Make sure that any delete of a sub-type record also deletes the super-type record. This is achieved by implementing an "instead-of" delete trigger on the sub-type table that goes and deletes the corresponding super-type record, which, in turn, cascade deletes the sub-type record.</p>\n\n<p>Using cascade deletes in this manner ensures that no orphan super-type or sub-type records ever exist, regardless of whether you delete the super-type record first or the sub-type record first.</p>\n'}, {'answer_id': 73498113, 'author': 'Jonas Kello', 'author_id': 2761797, 'author_profile': 'https://Stackoverflow.com/users/2761797', 'pm_score': 0, 'selected': False, 'text': "<p>I would make a distinction between</p>\n<ul>\n<li>Data integrity</li>\n<li>Business logic/rules</li>\n</ul>\n<p>In my experience it is best to enforce integrity as far as possible in the database using PK, FK, and other constraints.</p>\n<p>However business rules/logic IMO is best implemented using code for the reason of cohesion (google &quot;coupling and cohesion&quot; to learn more).</p>\n<p>Is cascade delete/update data integrity or business rules? This could of course be debated but I would say it is usually a logic/rule. For example a business rule may be that if an <code>Order</code> is deleted all <code>OrderItems</code> should be automatically deleted. But it could also be that it should never be possible to delete an <code>Order</code> if it still have <code>OrderItems</code>. So this may be up to the business to decide. How do we know how this rule is currently implemented? If it is all in code we can just look at the code (high cohesion). If the rule is maybe implemented in the code or maybe implemented as cascade in the database then we need to look in multiple places (low cohesion).</p>\n<p>Of course if you go all-in with putting your business rules only in the database and use triggers, stored proc then cascade may make sense.</p>\n<p>I usually consider database vendor lock-in before using any stored proc or triggers. A SQL database that just stores data and enforces integrity is IMO easier to port to another vendor. So for that reason I usually don't use stored proc or triggers.</p>\n"}]
['https://Stackoverflow.com/questions/59297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3043/']