I have two MySQL tables:
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
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
That is, if
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.
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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.
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.