How do Constraints Work?, FOREIGN KEY (Part 3 of 5)
Here is how a foreign key works (so that orphan rows can not happen):
When inserting a new row in the foreign key table:
The DBMS system makes sure that the new FOREIGN KEY value matches a UNIQUE or PRIMARY KEY value in the parent table. If there is no match, the new row in the foreign key table will not be inserted.
When updating an existing row in the foreign key table:
The DBMS system makes sure that the updated FOREIGN KEY value matches a UNIQUE or PRIMARY KEY value in the parent table. If there is no match, the existing row in the foreign key table will not be updated.
When deleting an existing row in the foreign key table:
There is no need for a referential integrity check.
When inserting a new row in the parent table:
There is no need for a referential integrity check.
When updating an existing row in the parent table:
The DBMS system makes sure that none of the FOREIGN KEY values match a UNIQUE or PRIMARY KEY value in the child table. If a match exists, the existing row in the parent key table will not be updated. However, if ON UPDATE CASCADE is specified, the parent row and all matching foreign key rows will be updated with the new key values.
When deleting an existing row in the parent table:
The DBMS system makes sure that none of the FOREIGN KEY values match a UNIQUE or PRIMARY KEY value in the child table. If a match exists, the existing row in the parent key table will not be deleted. However, if ON UPDATE CASCADE is specified, the parent row and all matching foreign key rows will be deleted.
