I have an integer column which I would like to add a foreign key constraint to. Only problem is if that column does not have/need a value, by default MySQL puts in a '0' value. This obviously breaks the foreign key constraint as there is no record in the primary table with a PK of 0.
How can I overcome this problem?
Perhaps allow nulls in your foreign key column and set the default to null.
However, think long and hard about allowing that FK column to be null. Null means you can have a child record without a parent. Is this really a valid business case? Can you give an example where this is valid?
Also, a null FK (or any null column) means you are now making assumptions about what the null means. How do you tell if the field really is not supposed to have a value, vs someone forgetting to put a value in? You could implement Not Null logic in the app and bypass the issue that way, though this still involves risks. Better minds than mine have said that allowing nulls causes a less stable database design. YMMV. Perhaps consider a default value like -1 that still forces a not null FK and looks up to a dummy record.
You may want to set your foreign key to accept
NULL
values, and use aNULL
instead of a0
value.Conceptually,
NULL
means a missing unknown value. If your row does "not have/need the value", I believe aNULL
fits in perfectly.And yes, a
NULL
value would not break your foreign key constraint.Let's build a basic example:
Then: