Should I really use foreign keys?

You should. There are three main points:

  • Depending on your DB system, you could get better performance
  • Foreign keys ensure data integrity, e.g. can help to avoid orphan records etc
  • They an explicit way to document your DB structure, which can be used by tools for visualization, code generation etc.

Using Foreign keys is one of the basis (if not the only) , the main concept of relational databases. You off course should use foreign keys where needed. Because this helps to:

  1. Make sure of the data validation and integrity
  2. Save lots of extra space

The first one means instead of adding a value manually to a field that is going to be repeated for other records you just choose from what you have in the related, the primary key table. If you try to enter something that does not exist as a primary key in the other table you'll be rejected (In some databases you can tweak this behavior though).

The second one means You don't have to write the "United States of America" each time, which would take a lot more space than just writing the ID of the "United States of America".


"All related tables" is not always clear, so it's not an obvious situation. There can be tables that have a common column but may never see each other.

It's handy, however, to prevent errors that slip past your primary defenses and allow data to be entered that's not easily traceable.

They don't help make queries more efficient if you have the proper indexes in place, and a good application will filter input enough that they should never be needed. But mistakes happen, and they are a cheap line of defense.

If you're just getting comfortable with designing databases, they aren't something to spend a lot of time worrying about and refining in great detail, once you have the basic parent/child relationships in place.

Here's some background--

What's wrong with foreign keys?

Tags:

Database