Error Code: 1005. Can't create table '...' (errno: 150)
Error Code: 1005 -- there is a wrong primary key reference in your code
Usually it's due to a referenced foreign key field that does not exist. It might be you have a typo mistake, or check case it should be same, or there's a field-type mismatch. Foreign key-linked fields must match definitions exactly.
Some known causes may be:
- The two key fields type and/or size doesn’t match exactly. For example, if one is
INT(10)
the key field needs to beINT(10)
as well and notINT(11)
orTINYINT
. You may want to confirm the field size usingSHOW
CREATE
TABLE
because Query Browser will sometimes visually show justINTEGER
for bothINT(10)
andINT(11)
. You should also check that one is notSIGNED
and the other isUNSIGNED
. They both need to be exactly the same. - One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field.
- The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this.
- One or both of your tables is a
MyISAM
table. In order to use foreign keys, the tables must both beInnoDB
. (Actually, if both tables areMyISAM
then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type. - You have specified a cascade
ON
DELETE
SET
NULL
, but the relevant key field is set toNOT
NULL
. You can fix this by either changing your cascade or setting the field to allowNULL
values. - Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns.
- You have a default value (that is, default=0) on your foreign key column
- One of the fields in the relationship is part of a combination (composite) key and does not have its own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint.
- You have a syntax error in your
ALTER
statement or you have mistyped one of the field names in the relationship - The name of your foreign key exceeds the maximum length of 64 characters.
For more details, refer to: MySQL Error Number 1005 Can’t create table
This could also happen when exporting your database from one server to another and the tables are listed in alphabetical order by default.
So, your first table could have a foreign key of another table that is yet to be created. In such cases, disable foreign_key_checks and create the database.
Just add the following to your script:
SET FOREIGN_KEY_CHECKS=0;
and it shall work.
Very often it happens when the foreign key and the reference key don't have the same type or same length.