I understand that you use foreign keys to relate rows from one table to the other and if this foreign key also becomes a primary key of that table then it is a primary foreign key.
But, for example, if a hotel records the date and time of check-ins for each customer, and each customer has a customer ID, should I include the customer ID as a primary foreign key or just a foreign key? Because at one time there can be multiple check-ins so date and time is not enough as a primary key?
Best Answer
It can't be a "primary foreign key" because a
PRIMARY KEY
is alwaysUNIQUE
(andNOT NULL
) and presumably a customer can check in again, perhaps at a different day or time.A
PRIMARY FOREIGN KEY
is, in my opinion, an anti-pattern in all cases where the table you're referencing is not a compound key. It means there is a strict 0-1:1 relationship, just like allNULLABLE
columns. And in all cases, in most databases, it's better to put such relationships on the original table in columns and let themDEFAULT
toNULL
.Is perfectly fine. If
b
is not there or applicable, you can set it toNULL
(or let it default to that).Is a bit silly. The only time I can see this making sense is something like this,
In the above case
bar
has a compound primary key of whicha
is a constituent that happens to reference tablefoo
.