Why are foreign keys more used in theory than in practice?

Viewed 21972

When you study relational theory foreign keys are, of course, mandatory. But in practice, in every place I worked, table products and joins are always done by specifying the keys explicitly in the query, instead of relying on foreign keys in the DBMS.

This way, you could of course join two tables by fields that are not meant to be foreign keys, having unexpected results.

Why do you think that is? Shouldn't DBMSs enforce that Joins and Products be made only by foreign keys?

EDIT: Thanks for all the answers. It's clear to me now that the main reason for FKs is reference integrity. But if you design a DB, all relationships in the model (I.E. arrows in the ERD) become Foreign keys, at least in theory, whether or not you define them as such in your DBMS, they're semantically FKs. I can't imagine the need to join tables by fields that aren't FKs. Can someone give an example that makes sense?

PS: I'm aware about the fact that N:M relationships become separate tables and not foreign keys, just omitted it for simplicity's sake.

17 Answers

The main reason is there is no way to set them up without a query in most MySQL GUI tools (Navicat, MySQL, etc.)

Sounds stupid but I'm guilty of this as well since I don't have the syntax memorized :/

Part of it for me is that (and yes, this is a lame excuse) the UI in MS's SQL Server Management studio for adding foreign keys is awful.

A foreign key is a constraint that "any value in column x on table a must appear in column y on table b", but the UI for specifying it in SSMS doesn't clearly indicate which table you're messing with, which is the parent table, which is the child table, and so on.

Every time I've had to create a foreign key, it's been trial and error until it seemed to work.

Related