database-designsql-null

Nullable Foreign Key bad practice?


Say you have a table Orders with a foreign key to a Customer Id and you want to add an Order without a Customer Id. (Whether that should be possible is another question.)

Is it bad practice to make the foreign key NULL?

Should you rather work with a link table between Orders and Customers?

Although the relationship is 1-to-n, a link table would make it n-to-n. On the other hand, with a link table, you wouldn't have those NULLs any more.

There won't be a lot of NULLs in the database, because a record with a foreign key to NULL is temporary until a customer for the order is added.

(It isn't an Order and a Customer.)

What about a unassigned Customer to link to?


Solution

  • Having the link table is probably a better option. At least it does not violate normalization BCNF (Boyce-Codd normal form). however I would favor being pragmatic. If you have very few of these null values and they are only temporary I think you should skip the link table since it only adds complexity to the scheme.

    On a side note; using a link table doesn't necessarily make it n to n, if you in the link table use the foreign key that's pointing to your orders table as the primary key in that link table the relationship is still 1..n. There can only be one entry in that link table per order.