19

I was wondering how useful foreign keys really are in a database. Essentially, if the developers know what keys the different tables depend on, they can write the queries just as though there was a foreign key, right?

Also, I do see how to foreign-key constraints help prevent all sorts of bugs with data integrity, but say for example, the programmers do a good job of preserving data integrity, how necessary are foreign keys really?

1
  • Were you asking about how useful foreign keys are or about how useful foreign key constraints are? Mar 31, 2011 at 4:00

12 Answers 12

25

If you don't care about referential integrity then you are right. But.... you should care about referential integrity.

The problem is that people make mistakes. Computers do not.

Regarding your comment:

but say for example, the programmers do a good job of preserving data integrity

Someone will eventually make a mistake. No one is perfect. Also if you bring someone new in you aren't always sure of their ability to write "perfect" code.

In addition to that you lose the ability to do cascading deletes and a number of other features that having defined foreign keys allow.

2
  • I would want the foreign keys defined 95% of the time. The reason not to do it is for slightly easier discarding of tables if certain features are no longer used. It is common to make and discard a lot of tables in the early stages of projects. But then you can get stuck with poorly designed foreign keys, which was the motivation behind my question.
    – Genadinik
    Mar 30, 2011 at 23:59
  • 4
    Difficult how? The DBMS says you have dependent records? If that is true then that is a VERY good thing. Otherwise you will have orphaned garbage data floating around for the rest of eternity. Mar 31, 2011 at 0:00
10

I think that assuming that programmers will always preserve data integrity is a risky assumption.

There's no reason why you wouldn't create foreign keys, and being able to guarantee integrity instead of just hoping for integrity is reason enough.

7

Not using referential integrity in a database is like not using seatbelts in cars. It will provide you with measurable improvements in taking you from A->B, but it will make "real" difference only in the most extreme cases. Why take the "risk" unless you really have to?

The underlaying reason people ask this question is always performance.

Foreign keys give the optimizer much more information to work with, and it will potentially produce better execution plans. It's not like a specific query will be % percent faster with enabled constraints, it's more like you effectively eliminate entire classes of problems due to bad execution plans. You also enable the optimizer to rewrite queries in ways that just isn't possible without the constraints (join elimination for example).

Starting right here, I would like to start a myth that referential integrity always increases performance in databases. I'm fairly confident that if 100 people designed their databases with full integrity checking, less than 5 people will actually have to consider spend a whopping 1 second to disable them for performance reasons. Out of those 5 people, there will be close to 0 people who find that they need to disable 100% of the constraints.

6

Foreign keys are invaluable as a means of ensuring integrity, and even if you trust your developers to never (!) make errors the cost of having them is usually well worth it.

Foreign keys also serve as documentation, in that you can see what relates to what. This information is typically also used by tools, such as for generating reports, creating data sets from table definitions, object-relational mappers, etc. Even if you do not use any of these today, having FKs will make it easier to tread that path later.

Foreign keys also allow you to define cascade rules, which e.g. can be used to to delete associated records in related tables when a row in one table is deleted.

Only if you have ridiculously high loads should you consider bypassing FKs.

Edit: updated answer to include points from other answers (reports, cascades).

6

You said

but say for example, the programmers do a good job of preserving data integrity

The expression you were looking for is, "I'm 100% certain that every programmer and every database administrator will manually preserve data integrity perfectly no matter what application touches this database, no matter how complex the database becomes, from now until the time it's decommissioned."

5

You don't have to use them but why wouldn't you?

They are there to help. From making life easier with cascade updates and cascade deletes, to guaranteeing that constraints aren't violated.

Maybe the application honors the constraints, but isn't it useful to have them clearly specified? You could document them, or you could put them in the database where most programmers expect to find constraints they are supposed to conform to (a better idea I think!).

Finally, if you ever need to import data into this database which doesn't go via the front-end, you may accidently import data which violates the constraints and breaks the application.

I'd definetly not recommend skipping the relationships in a database

3

Foreign Keys make life so much easier when using report builders and data analysis tools. Just select one table, check the include related tables box and BAM! you've got you're report built. Ok Ok, it's not that easy, but they certianly save time in that respect.

3

Use constraints rather than application logic to enforce integrity because it is generally easier, cheaper and more reliable to maintain constraints in one place (the database) rather than in every application.

I understand from one of your comments that your motivation for asking the question is that you think leaving out the keys may make it easier to evolve the database design during development. In my experience you are wrong about that. I find that it's actually better to be more restrictive with constraints in the early stages of development. If in doubt, create the constraint because it's much easier to remove constraints later than it is to create them. Removing a constraint will tend to break fewer things than adding one and generally requires less testing and fewer code changes to achieve.

2

Another point to make is that when you scrap your current user interface and use a new one with shiny new tools, you won't lose your referential integrity because the new devs have no idea what should be related to what. Databases are generally in use much much longer than user interfaces. They are also often used by more than one application interface and then you have the problem of different interfaces trying to enforce different integrity rules.

I will also point out that I have had occasion to look at the data in, quite literally, hundreds of databases and have not found one yet that has good data if they didn't set up FKs. This bad data complicates reporting, it complicates imports and exports to and from clients and other third party vendors who need or provide the data. And if the bad data is in a financial area, it could also have legal and accounting implications. I can even remember one time the company had thousands of bad inventory records where the actual product that was stored was no longer identifiable (nor the location) which also created issues with defining the value of the inventory necessary for financial reporting. This is not only bad from a perspective of not knowing what parts you have on hand, but it enables people to steal parts without being caught simply by deleting the part number from the part table (this particular place didn't have auditing in place either.).

2

Folks have offered up some good answers above. However, one important point I didn't see mentioned is that foreign keys make your entity relationship diagrams (ERDs) easier to generate and much more meaningful. Without FKs, you either need to depict the FK relationships on your ERD manually (painful for you) or not at all (painful for others, and perhaps even for yourself once your memory of the implied FK relationships starts to fade over time). With FKs explicitly defined, most tools that automatically generate ERDs from database object definitions will automatically detect and depict the FK relationships.

1

Perhaps the question should be "How bad are orphan records?". In many cases orphaned records aren't really going to hurt anything. Yes these records may persist until the end of time but how bad is this really? Cascading updates or deletes are rarely useful features. Referential integrity sounds nice but I think is not as important as we have been lead to believe. The biggest benefit to FK's is the documentation they provide. In my experience FK's for referential integrity are way more trouble than they are worth.

0

I am having the same question today, and found many articles talking about why you don't have to use foreign keys online. But so far, 10 of 11 answers here say you should have FKs.

I am not a db expert and just want to share some points I found online about when and why you don't have FKs:

Some points from 9 reasons why there are no foreign keys constraints:

  • Performance
  • Legacy data
  • Full table reload
  • Higher level framework
  • Cross database relations
  • Database platform agnostic
  • Open for change
  • Lazy architect
  • Keep model a secret

Some points from At GitHub we do not use foreign keys, ever, anywhere.

  • FKs are in your way to shard your database.
  • FKs are a performance impact.
  • FKs don't work well with online schema migrations.

Note: I don't have any opinions. Just sharing some online articles to provide a different answer to most of the current ones.

Not the answer you're looking for? Browse other questions tagged or ask your own question.