Friday, June 21, 2013

MySQL foreign key constraints


Below are explanations for MySQL's foreign key constraints:

1. ON DELETE RESTRICT

This means that a given parent row cannot be deleted if a child row referencing to it exists. It can be deleted only if there are no referencing child rows.
Modern database systems make this clause redundant as this would be default behavior of any foreign key. I am not sure which versions of MySQL include this as default, still wouldn't hurt keeping this clause.


2. ON DELETE CASCADE

ON DELETE CASCADE means that if a given parent row is deleted then all referencing child rows will also be deleted.

3. ON DELETE SET NULL

ON DELETE SET NULL means that if a given parent row is deleted then all referencing child rows will be set to NULL.

4.  ON DELETE NO ACTION

Same as ON DELETE RESTRICT, that is, a given parent row cannot be deleted if a child row referencing to it exists.