Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any example of a necessary nullable foreign key?

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?

like image 914
eggdrop Avatar asked May 29 '09 09:05

eggdrop


People also ask

Can foreign key be null with example?

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.

Can you make a foreign key nullable?

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).

Why are foreign keys allowed to have null values explain with examples?

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.

Under what conditions foreign key must not be null?

A foreign key may not be null when it is part of a composite primary key in the child table.


2 Answers

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.

like image 193
n3rd Avatar answered Oct 03 '22 13:10

n3rd


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.

like image 30
molf Avatar answered Oct 03 '22 13:10

molf