Customers
customer_id
Orders
order_id
customer_id fk
If I have two tables and define a foreign key on customer_id in the Orders table, by allowing it to be null I am saying that I can have an order that does not have a customer associated with it. As such, the notion of a nullable foreign key seems at odds with the purpose of a foreign key, which is to enforce this constraint.
Is there a simple example of a situation in which a nullable foreign key would be necessary? Or an argument in favor of permitting them?
A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.
Short answer: Yes, it can be NULL or duplicate. I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table).
Explain with an example. Here both the table 'Customer' and 'Order' are related with each other with a common field 'CCode' which is Primary key in Customer table and Foreign key in Order table. So we cannot insert a new CCode in Order table if it does not exist in Customer table but we can have null values instead.
A foreign key may not be null when it is part of a composite primary key in the child table.
Imagine a table that holds the TODOs of a team. If a TODO is not yet assigned to a member of the team, its user_id
is NULL
. If it is not NULL
it is a foreign key to the users
table.
No, nullable foreign keys are never necessary.
You can always normalize an optional 1-many relationship. Taking your example, you may have the following tables:
Customers: customer_id, ...
Orders: order_id, ...
OrdersCustomers: order_id, customer_id
UNIQUE(order_id)
The two unique constraints make sure that one order can belong to only one customer, and never to the same customer twice.
Whether you should always normalize such a relationship is a different story. In some cases denormalization may lead to simpler implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With