Error Code: 1005. Can't create table '...' (errno: 150)
Asked Answered
M

13

108

I searched for a solution to this problem on the Internet and checked the Stack Overflow questions, but none of the solutions worked for my case.

I want to create a foreign key from table sira_no to metal_kod.

ALTER TABLE sira_no
    ADD CONSTRAINT METAL_KODU FOREIGN KEY(METAL_KODU)
    REFERENCES metal_kod(METAL_KODU)
    ON DELETE SET NULL
    ON UPDATE SET NULL ;

This script returns:

Error Code: 1005. Can't create table 'ebs.#sql-f48_1a3' (errno: 150)

I tried adding an index to the referenced table:

CREATE INDEX METAL_KODU_INDEX ON metal_kod (METAL_KODU);

I checked METAL_KODU on both tables (charset and collation), but I couldn't find a solution to this problem. How can I fix this problem?

Here is the metal_kod table:

METAL_KODU    varchar(4)    NO    PRI
DURUM    bit(1)    NO
METAL_ISMI    varchar(30)    NO
AYAR_YOGUNLUK    smallint(6)    YES        100
Maples answered 26/1, 2012 at 13:14 Comment(1)
Can you show the schema for the metal_kod table ... which field in that table should the Foreign Key reference ?Raggletaggle
H
284

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:

  1. The two key fields type and/or size doesn’t match exactly. For example, if one is INT(10) the key field needs to be INT as well and not BIGINT or SMALLINT or TINYINT. You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same.
  2. 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.
  3. 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.
  4. One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type.
  5. You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL. You can fix this by either changing your cascade or setting the field to allow NULL values.
  6. 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.
  7. You have a default value (that is, default=0) on your foreign key column
  8. 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.
  9. You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship
  10. 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

Housman answered 26/1, 2012 at 13:26 Comment(13)
the problem was that the foreign key charsets were not matching. Thanks for the answer.Maples
SHOW ENGINE INNODB STATUS as mentioned in this question helped me diagnose my particular problem (PEBCAK, in my case...)Mentally
damn, even the it is a primary key. You need to create individual index for that key. thanks this solved my problem.Nesbitt
#4 was my problem - one of the tables was MyISAM and the script tried to create an InnoDB table. I ran into this problem when I was trying to deploy an old system that was initially running MySQL 5.0 or similar version, where the default storage engine was MyISAM and the scripts were running OK. My current environment is 5.5 and the default storage is InnoDB. Adding set names 'utf8', storage_engine=MYISAM; at the beginning of the script solved the issue for me. Thank you @Housman and @Stefano for the elaborate answer! :o)Oberheim
After hours and hours trying to figure this out #2 was my problem. The column I was referencing was a primary key, but it was a composite primary key. I solved this by adding a generic index on top of it being part of the primary key and that solved the issue.Cantonese
I had a FK to columns with the same charset, but different collation. That's also a no-no.Tactless
Mine was missing the 'unsigned' attribute as mentioned in #1, thanks!Meristic
thanks.. :) my issue was unassigned attribute and it's resolvedBenedictbenedicta
#8 is not correct. A composite index is fine as long as the referenced field is the leftmost field in the index.Transsonic
Thanks for the answer, the column size issue was the exact solution to my problemCoxcombry
#6 fixed my problem, one is utf8, another is utf8mb4Durning
Had the same problem, it was field-type mismatch on FK, thanks for the help!Sororate
I edited the first cause about INT types. The number argument to an integer type (e.g. INT(10) vs. INT(11)) makes no difference. You can mix and match these, since that argument doesn't affect the size of the data type anyway. But you cannot mix other types of INT, like BIGINT, SMALLINT, TINYINT.Watershed
T
11

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.

Teriteria answered 7/5, 2015 at 13:27 Comment(0)
P
5

Sometimes it is due to the master table is dropped (maybe by disabling foreign_key_checks), but the foreign key CONSTRAINT still exists in other tables. In my case I had dropped the table and tried to recreate it, but it was throwing the same error for me.

So try dropping all the foreign key CONSTRAINTs from all the tables if there are any and then update or create the table.

Potentiate answered 1/2, 2015 at 11:21 Comment(0)
A
4

Very often it happens when the foreign key and the reference key don't have the same type or same length.

Autolithography answered 25/8, 2014 at 12:29 Comment(0)
B
2

Error Code: 1005

I had a similar issue, so here are few things that I did try (not in any order, except for the solution :) )

  1. Changed the foreign key names (it didn't work)
  2. Reduced the foreign key length
  3. Verified the datatypes (darn nothing wrong)
  4. Check indexes
  5. Check the collations (everything fine, darn again)
  6. Truncated the table, of no good use
  7. Dropped the table and re-created
  8. Tried to see if any circular reference is being created --- all fine
  9. Finally, I saw that I had two editors open. One that in PhpStorm (JetBrains) and the other MySQL workbench. It seems that the PhpStorm / MySQL Workbench creates some kind of edit lock.

    I closed PhpStorm just to check if locking was the case (it could have been the other way around). This solved my problem.

Bonita answered 7/5, 2016 at 3:18 Comment(0)
B
2

I had a similar error. The problem had to do with the child and parent table not having the same charset and collation. This can be fixed by appending ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `country` (`id` INT(11) NOT NULL AUTO_INCREMENT,...) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

... on the SQL statement means that there is some missing code.

Benavides answered 14/7, 2016 at 8:34 Comment(0)
B
2

I had the very same error message. Finally I figured out I misspelled the name of the table in the command:

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES country (id);

versus

ALTER TABLE `users` ADD FOREIGN KEY (country_id) REFERENCES countries (id);

I wonder why on earth MySQL cannot tell such a table does not exist...

Bilbe answered 7/2, 2017 at 3:4 Comment(0)
B
2

The foreign key has to have the exact same type as the primary key that it references. For the example has the type “INT UNSIGNED NOT NULL” the foreing key also have to “INT UNSIGNED NOT NULL”

CREATE TABLE employees(
id_empl INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE offices(
id_office INT UNSIGNED NOT NULL AUTO_INCREMENT,
id_empl INT UNSIGNED NOT NULL,
PRIMARY KEY(id),
CONSTRAINT `constraint1` FOREIGN KEY (`id_empl`) REFERENCES `employees` (`id_empl`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='my offices';
Brandybrandyn answered 15/2, 2017 at 13:10 Comment(1)
unsigned was the problem for me. Thanks!Tourniquet
H
1

It happened in my case, because the name of the table being referenced in the constraint declaration wasn't correct (I forgot the upper case in the table name):

ALTER TABLE `Window` ADD CONSTRAINT `Windows_ibfk_1` FOREIGN KEY (`WallId`) REFERENCES `Wall` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Herbherbaceous answered 10/3, 2015 at 15:45 Comment(0)
U
1

MyISAM has been just mentioned. Simply try adding ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; at the end of a statement, assuming that your other tables were created with MyISAM.

CREATE TABLE IF NOT EXISTS `tablename` (
  `key` bigint(20) NOT NULL AUTO_INCREMENT,
  FOREIGN KEY `key` (`key`) REFERENCES `othertable`(`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Utility answered 20/1, 2016 at 23:29 Comment(0)
E
1

In my case, it happened when one table is InnoB and other is MyISAM. Changing engine of one table, through MySQL Workbench, solves for me.

Enervated answered 28/3, 2016 at 2:1 Comment(0)
L
1

check both tables has same schema InnoDB MyISAM. I made them all the same in my case InnoDB and worked

Loewe answered 21/9, 2019 at 2:35 Comment(0)
O
1

My problem was not listed, it was something so silly ..... The table that has the FK as PK was a composite PK that was declared like this: primary key (CNPJ, CEP) I wanted the CEP field to be FK in another table and I was stuck in this error, the moral of the story just inverted the code above for Primary key (CEP, CNPJ) and it worked. Get tip their friends.

Osset answered 8/6, 2020 at 4:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.