How to use RESTRICT for Foreign Key in mysql?

According to the MySQL Documentation on DELETE RESTRICT

• RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.

As for NO ACTION

• NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICT. InnoDB rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.

DELETE RESTRICT protects the parent from deletion, not the children.


If you are wanting to delete the parent and leave the child, then you're probably wanting the ON DELETE SET NULL option:

SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL. Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.

If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL.

There's a lot of 'not' in that last sentence, so just make sure the parent_id can be NULL.

See also this related qestion: What is the purpose of SET NULL in Delete/Update Foreign Keys constraints?

By defining a foreign key, you've told the database to not accept entries in the child table that do not have a corresponding value in the parent.