<p>As far as I know, foreign keys (FK) are used to aid the programmer to manipulate data in the correct way. Suppose a programmer is actually doing this in the right manner already, then do we really need the concept of foreign keys?</p>

<p>Are there any other uses for foreign keys? Am I missing something here?</p>

[{'answer_id': 18723, 'author': 'John Topley', 'author_id': 1450, 'author_profile': 'https://Stackoverflow.com/users/1450', 'pm_score': 8, 'selected': True, 'text': "<p>Foreign keys help enforce referential integrity at the data level. They also improve performance because they're normally indexed by default.</p>\n"}, {'answer_id': 18728, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 6, 'selected': False, 'text': '<p>Foreign keys can also help the programmer write less code using things like <code>ON DELETE CASCADE</code>. This means that if you have one table containing users and another containing orders or something, then deleting a user could automatically delete all orders that point to that user.</p>\n'}, {'answer_id': 18730, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 6, 'selected': False, 'text': '<p>I can\'t imagine designing a database without foreign keys. Without them, eventually you are bound to make a mistake and corrupt the integrity of your data.</p>\n\n<p>They are not <em>required</em>, strictly speaking, but the benefits are huge.</p>\n\n<p>I\'m fairly certain that <a href="http://en.wikipedia.org/wiki/FogBugz" rel="noreferrer">FogBugz</a> does not have foreign key constraints in the database. I would be interested to hear how the <a href="http://en.wikipedia.org/wiki/Fog_Creek_Software" rel="noreferrer">Fog Creek Software</a> team structures their code to guarantee that they will never introduce an inconsistency.</p>\n'}, {'answer_id': 18732, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 3, 'selected': False, 'text': '<p>Without a foreign key how do you tell that two records in different tables are related?</p>\n\n<p>I think what you are referring to is referential integrity, where the child record is not allowed to be created without an existing parent record etc. These are often known as foreign key constraints - but are not to be confused with the existence of foreign keys in the first place.</p>\n'}, {'answer_id': 18735, 'author': 'Pascal', 'author_id': 1311, 'author_profile': 'https://Stackoverflow.com/users/1311', 'pm_score': 1, 'selected': False, 'text': '<p>You can view foreign keys as a constraint that, </p>\n\n<ul>\n<li>Help maintain data integrity</li>\n<li>Show how data is related to each other (which can help in enforcing business logic and rules)</li>\n<li>If used correctly, can help increase the efficiency with which the data is fetched from the tables.</li>\n</ul>\n'}, {'answer_id': 18741, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 3, 'selected': False, 'text': '<p>I think <strong>some single thing</strong> at some point must be responsible for ensuring valid relationships.</p>\n\n<p>For example, <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="nofollow noreferrer">Ruby on Rails</a> does not use foreign keys, but it validates all the relationships itself. If you only ever access your database from that Ruby on Rails application, this is fine.</p>\n\n<p>However, if you have other clients which are writing to the database, then without foreign keys they need to implement their own validation. You then have two copies of the validation code which are most likely different, which any programmer should be able to tell is a cardinal sin.</p>\n\n<p>At that point, foreign keys really are neccessary, as they allow you to move the responsibility to a single point again.</p>\n'}, {'answer_id': 18758, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': 4, 'selected': False, 'text': "<blockquote>\n  <p>Suppose a programmer is actually doing this in the right manner already</p>\n</blockquote>\n\n<p>Making such a supposition seems to me to be an extremely bad idea; in general software is phenomenally buggy.</p>\n\n<p>And that's the point, really.  Developers can't get things right, so ensuring the database can't be filled with bad data is a Good Thing.</p>\n\n<p>Although in an ideal world, natural joins would use relationships (i.e. FK constraints) rather than matching column names. This would make FKs even more useful.</p>\n"}, {'answer_id': 18759, 'author': 'Peter Meyer', 'author_id': 1875, 'author_profile': 'https://Stackoverflow.com/users/1875', 'pm_score': 4, 'selected': False, 'text': "<p>Personally, I am in favor of foreign keys because it formalizes the relationship between the tables.  I realize that your question presupposes that the programmer is not introducing data that would violate referential integrity, but I have seen way too many instances where data referential integrity is violated, despite best intentions!  </p>\n\n<p>Pre-foreign key constraints (aka declarative referential integrity or DRI) lots of time was spent implementing these relationships using triggers.  The fact that we can formalize the relationship by a declarative constraint is very powerful.</p>\n\n<p>@John - Other databases may automatically create indexes for foreign keys, but SQL Server does not. In SQL Server, foreign key relationships are only constraints.  You must defined your index on foreign keys separately (which can be of benefit.)</p>\n\n<p>Edit: I'd like to add that, IMO, the use of foreign keys in support of ON DELETE or ON UPDATE CASCADE is not necessarily a good thing.  In practice, I have found that cascade on delete should be carefully considered based on the relationship of the data -- e.g. do you have a natural parent-child where this may be OK or is the related table a set of lookup values.  Using cascaded updates implies you are allowing the primary key of one table to be modified.  In that case, I have a general philosophical disagreement in that the primary key of a table should not change.  Keys should be inherently constant.</p>\n"}, {'answer_id': 18760, 'author': 'csmba', 'author_id': 350, 'author_profile': 'https://Stackoverflow.com/users/350', 'pm_score': 5, 'selected': False, 'text': '<p>Yes.</p>\n\n<ol>\n<li>They keep you honest</li>\n<li>They keep new developers honest</li>\n<li>You can do <code>ON DELETE CASCADE</code></li>\n<li>They help you to generate nice diagrams that self explain the links between tables</li>\n</ol>\n'}, {'answer_id': 18810, 'author': 'John Christensen', 'author_id': 1194, 'author_profile': 'https://Stackoverflow.com/users/1194', 'pm_score': 1, 'selected': False, 'text': '<p>We don\'t currently use foreign keys. And for the most part we don\'t regret it.</p>\n\n<p>That said - we\'re likely to start using them a lot more in the near future for several reasons, both of them for similar reasons:</p>\n\n<ol>\n<li><p>Diagramming. It\'s so much easier to produce a diagram of a database if there are foreign key relationships correctly used.</p></li>\n<li><p>Tool support. It\'s a lot easier to build data models using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual Studio 2008</a> that can be used for <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL_.28formerly_called_DLINQ.29" rel="nofollow noreferrer">LINQ&nbsp;to&nbsp;SQL</a> if there are proper foreign key relationships.</p></li>\n</ol>\n\n<p>So I guess my point is that we\'ve found that if we\'re doing a lot of manual SQL work (construct query, run query, blahblahblah) foreign keys aren\'t necessarily essential. Once you start getting into using tools, though, they become a lot more useful.</p>\n'}, {'answer_id': 18816, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 2, 'selected': False, 'text': "<p>They are not strictly necessary, in the way that seatbelts are not strictly necessary.  But they can really save you from doing something stupid that messes up your database.</p>\n\n<p>It's so much nicer to debug a FK constraint error than have to reconstruct a delete that broke your application.</p>\n"}, {'answer_id': 18964, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 1, 'selected': False, 'text': '<p>The best thing about foreign key constraints (and constraints in general, really) are that you can rely on them when writing your queries. A lot of queries can become a lot more complicated if you can\'t rely on the data model holding "true".</p>\n\n<p>In code, we\'ll generally just get an exception thrown somewhere - but in <a href="http://en.wikipedia.org/wiki/SQL" rel="nofollow noreferrer">SQL</a>, we\'ll generally just get the "wrong" answers.</p>\n\n<p>In theory, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL&nbsp;Server</a> could use constraints as part of a query plan - but except for check constraints for partitioning, I can\'t say that I\'ve ever actually witnessed that.</p>\n'}, {'answer_id': 18986, 'author': 'Guy', 'author_id': 993, 'author_profile': 'https://Stackoverflow.com/users/993', 'pm_score': 6, 'selected': False, 'text': "<p>A database schema without FK constraints is like driving without a seat belt.</p>\n<p>One day, you'll regret it.  Not spending that little extra time on the design fundamentals and data integrity is a sure fire way of assuring headaches later.</p>\n<p>Would you accept code in your application that was that sloppy?  That directly accessed the member objects and modified the data structures directly.</p>\n<p>Why do you think this has been made hard and <em>even unacceptable</em> within modern languages?</p>\n"}, {'answer_id': 19289, 'author': 'danb', 'author_id': 2031, 'author_profile': 'https://Stackoverflow.com/users/2031', 'pm_score': 2, 'selected': False, 'text': '<p>I think about it in terms of cost/benefit... In <a href="http://en.wikipedia.org/wiki/MySQL" rel="nofollow noreferrer">MySQL</a>, adding a constraint is a single additional line of <a href="http://en.wikipedia.org/wiki/Data_definition_language" rel="nofollow noreferrer">DDL</a>. It\'s just a handful of key words and a couple of seconds of thought. That\'s the only "cost" in my opinion...</p>\n\n<p>Tools love foreign keys. Foreign keys prevent bad data (that is, orphaned rows) that may not affect business logic or functionality and therefor go unnoticed, and build up. It also prevents developers who are unfamiliar with the schema from implementing entire chunks of work without realizing they\'re missing a relationship. Perhaps everything is great within the scope of your current application, but if you missed something and someday something unexpected is added (think fancy reporting), you might be in a spot where you have to manually clean up bad data that\'s been accumulating since the inception of the schema without a database enforced check.</p>\n\n<p>The little time it takes to codify what\'s already in your head when you\'re putting things together could save you or someone else a bunch of grief months or years down the road.</p>\n\n<p>The question:</p>\n\n<blockquote>\n  <p>Are there any other uses for foreign\n  keys? Am I missing something here?</p>\n</blockquote>\n\n<p>It is a bit loaded. Insert comments, indentation or variable naming in place of "foreign keys"... If you already understand the thing in question perfectly, it\'s "no use" to you.</p>\n'}, {'answer_id': 19510, 'author': 'Grzegorz Gierlik', 'author_id': 1483, 'author_profile': 'https://Stackoverflow.com/users/1483', 'pm_score': 1, 'selected': False, 'text': '<p>Foreign keys had never been explicit (FOREIGN KEY REFERENCES table(column)) declared in projects (business applications and social networking websites) which I worked on.</p>\n\n<p>But there always was a kind of convention of naming columns which were foreign keys.</p>\n\n<p>It\'s like with <a href="http://en.wikipedia.org/wiki/Database_normalization" rel="nofollow noreferrer">database normalization</a> -- you have to know what are you doing and what are consequence of that (mainly performance).</p>\n\n<p>I am aware of advantages of foreign keys (data integrity, index for foreign key column, tools aware of database schema), but also I am afraid of using foreign keys as general rule. </p>\n\n<p>Also various database engines could serve foreign keys in a different way, which could lead to subtle bugs during migration.</p>\n\n<p>Removing all orders and invoices of deleted client with ON DELETE CASCADE is the perfect example of nice looking, but wrong designed, database schema.</p>\n'}, {'answer_id': 22686, 'author': 'Tundey', 'author_id': 1453, 'author_profile': 'https://Stackoverflow.com/users/1453', 'pm_score': 3, 'selected': False, 'text': "<p>Is there a benefit to not having foreign keys? Unless you are using a crappy database, FKs aren't that hard to set up. So why would you have a policy of avoiding them? It's one thing to have a naming convention that says a column references another, it's another to know the database is actually verifying that relationship for you.</p>\n"}, {'answer_id': 80005, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Yes. The ON DELETE [RESTRICT|CASCADE] keeps developers from stranding data, keeping the data clean. I recently joined a team of Rails developers who did not focus on database constraints such as foreign keys.</p>\n\n<p>Luckily, I found these: <a href="http://www.redhillonrails.org/foreign_key_associations.html" rel="nofollow noreferrer">http://www.redhillonrails.org/foreign_key_associations.html</a> --  RedHill on Ruby on Rails plug-ins generate foreign keys using the <a href="http://en.wikipedia.org/wiki/Convention_over_configuration" rel="nofollow noreferrer">convention over configuration</a> style. A migration with <em>product_id</em> will create a foreign key to the <em>id</em> in the <em>products</em> table.  </p>\n\n<p>Check out the other great plug-ins at <a href="http://www.redhillonrails.org/" rel="nofollow noreferrer">RedHill</a>, including migrations wrapped in transactions. </p>\n'}, {'answer_id': 80073, 'author': 'Craig', 'author_id': 13988, 'author_profile': 'https://Stackoverflow.com/users/13988', 'pm_score': 3, 'selected': False, 'text': '<p>Foreign keys allow someone who has not seen your database before to determine the relationship between tables.</p>\n\n<p>Everything may be fine now, but think what will happen when your programmer leaves and someone else has to take over.</p>\n\n<p>Foreign keys will allow them to understand the database structure without trawling through thousand of lines of code.</p>\n'}, {'answer_id': 83137, 'author': 'JacquesB', 'author_id': 7488, 'author_profile': 'https://Stackoverflow.com/users/7488', 'pm_score': 3, 'selected': False, 'text': '<p>I suppose you are talking about <em>foreign key constraints enforced by the database</em>. You probably already are using foreign keys, you just haven\'t told the database about it.</p>\n\n<blockquote>\n  <p>Suppose a programmer is actually doing\n  this in the right manner already, then\n  do we really need the concept of\n  foreign keys?</p>\n</blockquote>\n\n<p>Theoretically, no. However, there have never been a piece of software without bugs.</p>\n\n<p>Bugs in application code are typically not that dangerous - you identify the bug and fix it, and after that the application runs smoothly again. But if a bug allows currupt data to enter the database, then you are stuck with it! It\'s very hard to recover from corrupt data in the database. </p>\n\n<p>Consider if a subtle bug in <a href="http://en.wikipedia.org/wiki/FogBugz" rel="noreferrer">FogBugz</a> allowed a corrupt foreign key to be written in the database. It might be easy to fix the bug and quickly push the fix to customers in a bugfix release. However, how should the corrupt data in dozens of databases be fixed? <em>Correct</em> code might now suddenly break because the assumptions about the integrity of foreign keys dont hold anymore.</p>\n\n<p>In web applications you typically only have one program speaking to the database, so there is only one place where bugs can corrupt the data. In an enterprise application there might be several independent applications speaking to the same database (not to mention people working directly with the database shell). There is no way to be sure that all applications follow the same assumptions without bugs, always and forever.</p>\n\n<p>If constraints are encoded in the database, then the worst that can happen with bugs is that the user is shown an ugly error message about some <a href="http://en.wikipedia.org/wiki/SQL" rel="noreferrer">SQL</a> constraint not satisfied. This is <em>much</em> prefereable to letting currupt data into your enterprise database, where it in turn will break all your applications or just lead to all kinds of wrong or misleading output.</p>\n\n<p>Oh, and foreign key constraints also improves performance because they are indexed by default. I can\'t think of any reason <em>not</em> to use foreign key constraints.</p>\n'}, {'answer_id': 86501, 'author': 'Mike McAllister', 'author_id': 16247, 'author_profile': 'https://Stackoverflow.com/users/16247', 'pm_score': 2, 'selected': False, 'text': '<p>They are important, because your application is not the only way data can be manipulated in the database. Your application may handle referential integrity as honestly as it wants, but all it takes is one bozo with the right privileges to come along and issue an insert, delete or update command at the database level, and all your application referential integrity enforcement is bypassed. Putting FK constraints in at the database level means that, barring this bozo choosing to disable the FK constraint before issuing their command, the FK constraint will cause a bad insert/update/delete statement to fail with a referential integrity violation.</p>\n'}, {'answer_id': 176260, 'author': 'Peter Wone', 'author_id': 1715673, 'author_profile': 'https://Stackoverflow.com/users/1715673', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>As far as I know, foreign keys are used to aid the programmer to manipulate data in the correct way. </p>\n</blockquote>\n\n<p>FKs allow the DBA to protect data integrity from the fumbling of users when the programmer <em>fails</em> to do so, and sometimes to protect against the fumbling of programmers.</p>\n\n<blockquote>\n  <p>Suppose a programmer is actually doing this in the right manner already, then do we really need the concept of foreign keys?</p>\n</blockquote>\n\n<p>Programmers are mortal and fallible. FKs are <em>declarative</em> which makes them harder to screw up. </p>\n\n<blockquote>\n  <p>Are there any other uses for foreign keys? Am I missing something here?</p>\n</blockquote>\n\n<p>Although this is not why they were created, FKs provide strong reliable hinting to diagramming tools and to query builders. This is passed on to end users, who desperately need strong reliable hints.</p>\n'}, {'answer_id': 765525, 'author': 'cherouvim', 'author_id': 72478, 'author_profile': 'https://Stackoverflow.com/users/72478', 'pm_score': 3, 'selected': False, 'text': '<p>FKs are very important and should always exist in your schema, <a href="http://www.infoq.com/interviews/dan-pritchett-ebay-architecture" rel="noreferrer">unless you are eBay</a>.</p>\n'}, {'answer_id': 1829657, 'author': 'Quibblesome', 'author_id': 1143, 'author_profile': 'https://Stackoverflow.com/users/1143', 'pm_score': 2, 'selected': False, 'text': '<p>Entropy reduction. Reduce the potential for chaotic scenarios to occur in the database.\nWe have a hard time as it is considering all the possiblilites so, in my opinion, entropy reduction is key to the maintenance of any system.</p>\n\n<p>When we make an assumption for example: each order has a customer that assumption should be enforced by <em>something</em>. In databases that "something" is foreign keys.</p>\n\n<p>I think this is worth the tradeoff in development speed. Sure, you can code quicker with them off and this is probably why some people don\'t use them. Personally I have killed a number of hours with <a href="http://en.wikipedia.org/wiki/NHibernate" rel="nofollow noreferrer">NHibernate</a> and some foreign key constraint that gets angry when I perform some operation. HOWEVER, I know what the problem is so it\'s less of a problem. I\'m using normal tools and there are resources to help me work around this, possibly even people to help!  </p>\n\n<p>The alternative is allow a bug to creep into the system (and given enough time, it will) where a foreign key isn\'t set and your data becomes inconsistent. Then, you get an unusual bug report, investigate and "OH". The database is screwed. Now how long is that going to take to fix?</p>\n'}, {'answer_id': 60080945, 'author': 'Mike Griffin', 'author_id': 12010707, 'author_profile': 'https://Stackoverflow.com/users/12010707', 'pm_score': 0, 'selected': False, 'text': '<p>If you plan on generating your data access code, ie, Entity Framework or any other ORM you entirely lose the ability to generate a hierarchical model without Foreign Keys</p>\n'}]
['https://Stackoverflow.com/questions/18717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184/']