2. Foreign key constraints and NULLs
It is a common misconception that foreign keys always
prevent orphan rows, that is, rows in the child table that do not have
corresponding rows in the parent table. In fact, if the columns involved
in the foreign key constraint are nullable, then we may have orphan
rows.
Let's see for ourselves. Listing 10 creates a parent and child pair of tables.
We have a composite FOREIGN KEY constraint on the Latitude and Longitude
columns in the child table, but since both of these columns are
nullable, we can add a child row without a matching parent row into the
child table, even though the parent table is empty at this time, as Listing 11 demonstrates.
The database engine will verify whether or not there is a matching row in the parent table if, and only if, neither the Latitude nor Longitude column in the child table contains a NULL. Listing 12, for example, will fail.
This demonstrates that, if we need to make
sure that every row in the child table has a matching row in the parent
table, it is not enough to simply create a FOREIGN KEY; in such cases, we also need to ensure that the columns involved in the FOREIGN KEY, in the child table, are not nullable. Use of nullable columns in FOREIGN KEY
constraints must be reserved only for the cases when it is acceptable
to have rows in the child table without matching rows in the parent one.