Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top