January 9, 2017

MySQL Error 1215: Cannot add foreign key constraint

As a newbie, I was confused on this error until I search through StackOverflow. Phew!

Reasons you may get a foreign key constraint error:
  • You are not using InnoDB as the engine on all tables.
  • You are trying to reference a nonexistent key on the target table. Make sure it is a key on the other table (it can be a primary or unique key)
  • The types of the columns are not the same (exception is the column on the referencing table can be nullable).
  • One of the reasons may also be that the column you are using for ON DELETE SET NULL is not defined to be null. So make sure that the column is set default null
  • You are not using the same Character Set for both tables.