Let\'s say you have a table Orders with a foreign key to a Customer Id. Now, suppose you want to add an Order without a Customer Id, (whether that should be possible is anot
You could always add an artificial row to your Customer table, something like Id=-1 and CustomerName = 'Unknown' and then in cases when you would normally set your CustomerId in Order NULL set it to -1.
This allows you to have no nullable FKs but still represent the lack of data appropriately (and will save you from downstream users not knowing how to deal with NULLs).
I've heard it argued that Nullable columns in general are break the first degree of normalization. But in practice it's very practical.
If you are only adding the order temporarily with no customer id until a customer is defined, would it not be simpler to add the customer and order in a single transaction, thereby removing the need for the NULL foreign key entry and avoiding any constraints or triggers you've set up being violated?
Normally this situation arises ins web apps where the order is detailed before the customer defines who he/she is. And in those situations the order is kept in server state or in a cookie until all the necessary state for a complete order is supplied at which point the order is persisted to the database.
NULL foreign keys are ok for things like addresses, as mentioned above. But a NULL customer field doesn't make sense for an order and should be constrained.
Yes theres something wrong. Its not a foreign key if its nullable. Its database design by code. Maybe you make a zero link to unassigned. or "Unassigned" if your using a character col. Keep the integrity of your data 100%.
No There is nothing wrong with Nullable FKs. This is common when the entity the FK points to is in a (zero or one) to (1 or many) relationship with the primary Key referenced table.
An example might be if you had both a Physical address and a Mailing address attribute (column) in a table, with FKs to an Address table. You might make the Physical address nullable to handle when the entity only has a post office box (mailing address), and the mailing address nullable to handle when the mailing address is the same as the physical address (or not).