Okay, I desperately lack time to write full articles posts lately, so I’m going to make this quick! :P

Background: Suppose you have a table named Songs and a table named Genres. Genres only contains Genre IDs and Genre Names. Songs contains all sorts of data, but at some point there is one field (let’s call it Song_Genre_ID) that points to the Genre ID. Get the picture? I’m sorry, I don’t have the time for an actual picture of this. That “pointer” is called a Foreign Key. The Genre_ID, being the Primary key.

Data Integrity Enforcement means that MySQL is going to prevent you from putting any crappy value into the Foreign Key (FK) that would not exist in the refered Primary Key (PK). It will also prevent you from deleting a Genre if there are songs pointing to it. The bottom line is: if you’re serious about your DB, you can’t do without!

Now how would you enforce the integrity? Basically with something like this (but you may want to check the MySQL manual for details, right? :P):

ALTER TABLE Songs ADD CONSTRAINT FK_any_name FOREIGN KEY (Song_Genre_ID) REFERENCES Genres (Genre_ID) ON DELETE RESTRICT ON UPDATE RESTRICT;

Now, here’s my point: from my experience I have found that a hell lot of things can go wrong when you try to add that constraint, and it can be a nightmare to find out what’s going wrong! As a matter of fact, you’ll find out MySQL’s error messages aren’t very helpful >:XX…

So here’s a checklist to follow in order to find out what’s been going wrong:

  • If the error message is even less helpful than you could possibly imagine, check your version of MySQL. Versions 4.1+ definitely have better messages than previous versions.
  • Check that both of your tables are of type InnoDB. Don't even try it otherwise.
  • Check that the PK you are refering to is actually defined as the Primary Key for its table.
  • On versions < 4.1, check that the the FK is being properly INDEXed before creating the foreign key.
  • Check the data types of the FK and the PK. They should be exactly the same. And I really mean *exactly*! Check the "UNSIGNED" attribute also. If it's signed on one side and unsigned on the other, it won't work! (I recommend using INT UNSIGNED for most of your FKs and PKs).
  • Check that any existing values in the PK column have matches in the FK column at the time you try to create the constraint.
  • Check that the DEFAULT value for your FK also has a match in the FK column at the time you try to create the constraint.

Okay I hope I didn’t forget anything. Of course, if you find another reason for the constraint creation to fail, I’d love to hear about it! ;)

Good luck! :»