Exact Meaning of MySQL's Foreign Key 'on delete restrict' Clause

MysqlForeign Keys

Mysql Problem Overview


I have two MySQL tables: collections and privacy_level.
I define them with a foreign key relationship as such:

CREATE TABLE collections (
  coll_id smallint NOT NULL AUTO_INCREMENT UNSIGNED,
  name varchar(30) NOT NULL,
  privacy tinyint NOT NULL UNSIGNED DEFAULT '0',
  PRIMARY KEY(coll_id),
  INDEX(privacy),
  FOREIGN KEY fk_priv (privacy) REFERENCES privacy_level (level) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB;  

 CREATE TABLE privacy_level (
   level tinyint NOT NULL UNSIGNED,
   name varchar(20) NOT NULL,
   PRIMARY KEY (level)
 ) ENGINE InnoDB;  

My question is about the ON DELETE RESTRICT clause and I couldn't derive the answer from the online manual or a google search.

Does this mean that I can never delete a row from privacy_level?
Or, does it mean that I can't delete a row from privacy_level if a row from collections.privacy has a value that is the same as a value in privacy_level.level?

That is, if privacy_level has level = 2, name = 'top secret' but no entry in collections.Privacy has privacy = 2, can I delete the level = 2, name = 'top secret' entry? Or is it forbidden on a column wide basis?

Thanks for any insight.

Mysql Solutions


Solution 1 - Mysql

ON DELETE RESTRICT means you can't delete a given parent row if a child row exists that references the value for that parent row. If the parent row has no referencing child rows, then you can delete that parent row.

ON DELETE RESTRICT is pretty much superfluous syntax, because this is the default behavior for a foreign key anyway.

Solution 2 - Mysql

Also you can use ON DELETE CASCADE, that means when you delete the parent all the children will be removed automatically, this is useful when you have a table associated with another that contains some parameters or settings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDonkey TroubleView Question on Stackoverflow
Solution 1 - MysqlBill KarwinView Answer on Stackoverflow
Solution 2 - Mysqljose miguel rivera rodríguezView Answer on Stackoverflow