Are MySQL foreign keys always a good idea? I mean if the field I'm using is required for every row and it references another table, should I 100% of the time use a foreign key? It seems to me like I would, and it seems like I'd always want to setup ON DELETE CASCADE as well to maintain data integrity.
Add a comment |
2 Answers
If you have a relationship then it's a good idea to setup your foreign keys. Foreign keys are sort of a key component of relational databases. However, you don't necessarily need cascading deletes. Simply by implementing your foreign keys you'll maintain data integrity. Any delete will fail when conflicting with your foreign key constraints.
2 Comments
Ben
Any delete will fail when conflicting with your foreign key constraints. - what do you mean by this? Can you give me an example of when it will fail?canon
Table
a has a column b_id which references the id column in table b. You will experience a failure if you try to delete a record from b if it's referenced in a, i.e.: it won't get deleted and you'll get an error message. To be honest, I'm not sure exactly what mysql's behavior will be in this case... but it should fail.