I have a table which has several ID columns to other tables.
I want a foreign key to force integrity only if I put data in there. If I do an update at a later time to populate that column, then it should also check the constraint.
(This is likely database server dependant, I'm using MySQL & InnoDB table type)
I believe this is a reasonable expectation, but correct me if I am wrong.
Best Answer
Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:
The first insert will pass because we insert a NULL in the
parent_id
. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in theparent
table.