mySQL Restrict Cascade No Action settings

Go To StackoverFlow.com

0

What is the best constraint to use on a forum table where users leave comments?

Assuming some users will be deleted at a later stage. if i delete a user who has commented, what happens to the users entry in the table?

Hope someone can explain.

2012-04-05 16:08
by JamesBondInBlack


1

There are two parts to this question:

  1. how best to implement this? You can "soft-delete" user rows. This has the advantages of:

    • not losing user information
    • allowing users to be un-deleted
    • maintaining referential integrity without losing data linked to users

    Soft-deleting can be implemented by adding another column to the users table, with a dateDeleted column -- if it's Null, then the user isn't deleted. I believe SO uses such a mechanism for deleting posts.

  2. what does restrict cascade no action do? The MySQL docs say

  • 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.

  • 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.

In other words, if you use this, you won't be able delete rows if doing so would break referential integrity.

2012-04-05 17:19
by Matt Fenwick
Many thanks for that. so which constraint is the best to use for the first option you gave for ON UPDATE and ON DELETE - JamesBondInBlack 2012-04-05 18:53
@olad if you're using InnoDB as your storage engine, foreign keys will automatically be enforced. So the defaults for ON UPDATE and ON DELETE are fine, since you won't (or at least, shouldn't) be changing the primary keys of rows - Matt Fenwick 2012-04-05 19:21
Ads