Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you absolutely need foreign keys in a database?

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?

like image 656
Genadinik Avatar asked Mar 30 '11 23:03

Genadinik


2 Answers

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.

like image 140
Abe Miessler Avatar answered Sep 18 '22 21:09

Abe Miessler


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.

like image 34
Michael Fredrickson Avatar answered Sep 18 '22 21:09

Michael Fredrickson