MySQL Error 1215: Cannot add foreign key constraint
Asked Answered
B

30

396

I am trying to forward engineer my new schema onto my database server, but I can't figure out why I am getting this error.

I've tried to search for the answer here, but everything I've found has said to either set the database engine to InnoDB or to make sure the keys I'm trying to use as a foreign key are primary keys in their own tables. I have done both of these things, if I'm not mistaken. What else can I do?

Executing SQL script in server

ERROR: Error 1215: Cannot add foreign key constraint

-- -----------------------------------------------------
-- Table `Alternative_Pathways`.`Clients_has_Staff`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `Alternative_Pathways`.`Clients_has_Staff` (
  `Clients_Case_Number` INT NOT NULL ,
  `Staff_Emp_ID` INT NOT NULL ,
  PRIMARY KEY (`Clients_Case_Number`, `Staff_Emp_ID`) ,
  INDEX `fk_Clients_has_Staff_Staff1_idx` (`Staff_Emp_ID` ASC) ,
  INDEX `fk_Clients_has_Staff_Clients_idx` (`Clients_Case_Number` ASC) ,
  CONSTRAINT `fk_Clients_has_Staff_Clients`
    FOREIGN KEY (`Clients_Case_Number` )
    REFERENCES `Alternative_Pathways`.`Clients` (`Case_Number` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_Clients_has_Staff_Staff1`
    FOREIGN KEY (`Staff_Emp_ID` )
    REFERENCES `Alternative_Pathways`.`Staff` (`Emp_ID` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB

SQL script execution finished: statements: 7 succeeded, 1 failed

Here is the SQL for the parent tables.

CREATE  TABLE IF NOT EXISTS `Alternative_Pathways`.`Clients` (
  `Case_Number` INT NOT NULL ,
  `First_Name` CHAR(10) NULL ,
  `Middle_Name` CHAR(10) NULL ,
  `Last_Name` CHAR(10) NULL ,
  `Address` CHAR(50) NULL ,
  `Phone_Number` INT(10) NULL ,
  PRIMARY KEY (`Case_Number`) )
ENGINE = InnoDB

CREATE  TABLE IF NOT EXISTS `Alternative_Pathways`.`Staff` (
  `Emp_ID` INT NOT NULL ,
  `First_Name` CHAR(10) NULL ,
  `Middle_Name` CHAR(10) NULL ,
  `Last_Name` CHAR(10) NULL ,
  PRIMARY KEY (`Emp_ID`) )
ENGINE = InnoDB
Bedel answered 6/6, 2013 at 18:4 Comment(1)
remember unsigned affects the type .Psychasthenia
M
703

I'm guessing that Clients.Case_Number and/or Staff.Emp_ID are not exactly the same data type as Clients_has_Staff.Clients_Case_Number and Clients_has_Staff.Staff_Emp_ID.

Perhaps the columns in the parent tables are INT UNSIGNED?

They need to be exactly the same data type in both tables.

Monogenic answered 6/6, 2013 at 18:8 Comment(2)
You are right dear, "Both the fields should be exactly the same data type in both tables." Thanks.Langouste
In my case the types where the same but the collation of the columns was different.Agincourt
C
302

Reasons you may get a foreign key constraint error:

  1. You are not using InnoDB as the engine on all tables.
  2. 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, or just a key)
  3. The types of the columns are not the same (an exception is the column on the referencing table can be nullable even if it is not nullable in the referenced table).
  4. If the primary key or foreign key is a varchar, make sure the collation is the same for both.
  5. 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.

Check these.

Copyread answered 6/6, 2013 at 18:11 Comment(13)
I'll just add that if the FK is on a character column, I think they need to be of the same charset and collation. (Or possibly 1-byte and 2-byte charsets are not compatible.)Ish
Great and simple answer! Everyone debugging error 1215 should start from here. I added some more subtle cases to look out for, in case your error is not caused by any of these points.Odetteodeum
My reason was your pointed out first one "Different DB Engines for two tables, InnoDB and MyISAM"Shupe
I got another one reason =) ``` ON DELETE CASCADE ON UPDATE SET NULL:``` You have defined a SET NULL condition though some of the columns are defined as NOT NULL. So, i just fix FK definition.Paralysis
Also possible failure is absence of index on target field.Sand
Related to #3: It can also happen if you have a combined primary key and you are not referencing all the parts of the primary keyHero
#5..is the foreign table created? mine was that reason :)Ignatz
The MySQL documentation describes in great detail all the InnoDB foreign key constraints: dev.mysql.com/doc/refman/5.7/en/….Daryldaryle
was updating to InnoDB that fixed the issuePeridot
I actually ran into the issue that @GrahamCharles mentioned, converted my schema collation from utf8 to utf8mb4 without converting my existing tables, and wasn't able to add FKs from the new tables to the older tables because they were on different collation. That took forever to debug. Would be great if you can add "Different collation between tables" as one of the reasons to your answer.Bloodstock
Adding another reason to @Explosion Pills answer above: > 7- When using multi column keys, the order in the foreign key creation > must match the other in the table column order.Edisonedit
spot on it was scenario 4 for me, using Varchar keys, not the same encodingPisa
different charset for me, one table was latin1 the other utf8Snick
T
106

For others, the same error may not always be due to a column type mismatch. You can find out more information about a MySQL foreign key error by issuing the command

SHOW ENGINE INNODB STATUS;

You may find an error near the top of the printed message. Something like

Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.

Tangent answered 8/7, 2014 at 14:55 Comment(4)
How should that work? Execute both queries in a row?Tolan
@C4u, yes we should execute both queries in a row by having SHOW ENGINE INNODB STATUS as first and then followed by other queriesAran
Doing it on PHPMyAdmin won't work. do it on the command prompt.Nothingness
"you need (at least one of) the PROCESS privilege(s) for this operation"Gan
O
15

Error 1215 is an annoying one. Explosion Pill's answer covers the basics. You want to make sure to start from there. However, there are more, much more subtle cases to look out for:

For example, when you try to link up PRIMARY KEYs of different tables, make sure to provide proper ON UPDATE and ON DELETE options. E.g.:

...
PRIMARY KEY (`id`),
FOREIGN KEY (`id`) REFERENCES `t` (`other_id`) ON DELETE SET NULL
....

won't fly, because PRIMARY KEYs (such as id) can't be NULL.

I am sure, there are even more, similarly subtle issues when adding these sort of constraints, which is why when coming across constraint errors, always make sure that the constraints and their implications make sense in your current context. Good luck with your error 1215!

Odetteodeum answered 1/12, 2014 at 8:56 Comment(3)
You will also get this error if you try to delete a foreign key that is not there :)Copyread
Also, from the docs: MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.Splay
That's the reason I came here: I tried to create a foreign key ON DELETE SET NULL on a column I wanted to be NOT NULL. Suppose you can't have your cake and eat it, too.Acetaldehyde
R
12

Check the collation of the table. Using SHOW TABLE STATUS, you can check information about the tables, including the collation.

Both tables have to have the same collation.

It's happened to me.

Rissole answered 29/1, 2018 at 3:53 Comment(1)
This was the issue in my case - the MySQL error is not helpful at all!Merilynmeringue
A
7

In my case, I had deleted a table using SET FOREIGN_KEY_CHECKS=0, then SET FOREIGN_KEY_CHECKS=1 after. When I went to reload the table, I got error 1215. The problem was there was another table in the database that had a foreign key to the table I had deleted and was reloading. Part of the reloading process involved changing a data type for one of the fields, which made the foreign key from the other table invalid, thus triggering error 1215. I resolved the problem by dropping and then reloading the other table with the new data type for the involved field.

Affront answered 8/5, 2014 at 17:51 Comment(0)
S
6

I got the same error while trying to add a foreign key. In my case, the problem was caused by the foreign key table's primary key which was marked as unsigned.

Squamation answered 12/11, 2013 at 23:47 Comment(0)
H
6

There is a pitfall I have experienced with "Error 1215: Cannot add foreign key constraint" when using Laravel 4, especially with JeffreyWay's Laravel 4 Generators.

In Laravel 4, you can use JeffreyWay's Generators to generate migration files to create tables one-by-one, which means, each migration file generates one table.

You have to be aware of the fact that each migration file is generated with a timestamp in the filename, which gives the files an order. The order of generation is also the order of migration operation when you fire the Artisan CLI command php artisan migrate.

So, if a file asks for a foreign key constraint referring to a key which will be, but not yet, generated in a latter file, the Error 1215 is fired.

In such a case, you have to adjust the order of migration files generation. Generate new files in proper order, copy-in the content, and then delete the disordered old files.

Hardspun answered 6/12, 2013 at 9:8 Comment(0)
A
6

For MySQL (InnoDB) ... get definitions for the columns you want to link:

SELECT * FROM information_schema.columns WHERE
TABLE_NAME IN (tb_name','referenced_table_name') AND
COLUMN_NAME  IN ('col_name','referenced_col_name')\G

Compare and verify both column definitions have:

same COLUMN_TYPE(length), same COLATION

It could be necessary to disable/enable the foreign_key mechanism, but be aware if in a production context:

set foreign_key_checks=0;
ALTER TABLE tb_name ADD FOREIGN KEY(col_name) REFERENCES ref_table(ref_column) ON DELETE ...
set foreign_key_checks=1;
Ayurveda answered 24/10, 2016 at 16:34 Comment(0)
K
5

Check for table compatibility (engine) with SHOW TABLE STATUS WHERE Name = 'tableName'.

For example, if one table is MyISAM and the other one is InnoDB, you may have this issue.

You can change it thanks to this command:

ALTER TABLE myTable ENGINE = InnoDB;

From documentation.

Kaylil answered 12/1, 2017 at 0:20 Comment(1)
If using phpMyAdmin you can also check the storage engine in the Operations tab.Designer
W
3

I had the same issue, and my solution is:

Before:

CREATE TABLE EMPRES
( NoFilm smallint NOT NULL

  PRIMARY KEY (NoFilm)

  FOREIGN KEY (NoFilm) REFERENCES cassettes

);

Solution:

CREATE TABLE EMPRES
(NoFilm smallint NOT NULL REFERENCES cassettes,

 PRIMARY KEY (NoFilm)

);
Watcher answered 28/4, 2015 at 21:57 Comment(1)
You forgot a couple of commas in your first CREATECoagulum
S
3

This also happens when the type of the columns is not the same.

E.g., if the column you are referring to is an UNSIGNED INT and the column being referred to is INT then you get this error.

Sinusoid answered 29/8, 2015 at 6:17 Comment(0)
U
3

In my case I had to disable FOREIGN KEY checks as the source tables did not exist.

SET FOREIGN_KEY_CHECKS=0;

Underwater answered 3/10, 2018 at 5:35 Comment(0)
A
3

I just wanted to add this case as well for VARCHAR foreign key relation. I spent the last week trying to figure this out in MySQL Workbench 8.0 and was finally able to fix the error.

Short Answer: The character set and collation of the schema, the table, the column, the referencing table, the referencing column and any other tables that reference to the parent table have to match.

Long Answer: I had an ENUM datatype in my table. I changed this to VARCHAR and I can get the values from a reference table so that I don't have to alter the parent table to add additional options. This foreign-key relationship seemed straightforward but I got 1215 error. arvind's answer and the following link suggested the use of

SHOW ENGINE INNODB STATUS;

On using this command I got the following verbose description for the error with no additional helpful information

Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint. Note that the internal storage type of ENUM and SET changed in tables created with >= InnoDB-4.1.12, and such columns in old tables cannot be referenced by such columns in new tables. Please refer to http://dev.mysql.com/doc/refman/8.0/en/innodb-foreign-key-constraints.html for correct foreign key definition.

After which I used SET FOREIGN_KEY_CHECKS=0; as suggested by Arvind Bharadwaj and the link here:

This gave the following error message:

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint

At this point, I 'reverse engineer'-ed the schema and I was able to make the foreign-key relationship in the EER diagram. On 'forward engineer'-ing, I got the following error:

Error 1452: Cannot add or update a child row: a foreign key constraint fails

When I 'forward engineer'-ed the EER diagram to a new schema, the SQL script ran without issues. On comparing the generated SQL from the attempts to forward engineer, I found that the difference was the character set and collation. The parent table, child table and the two columns had utf8mb4 character set and utf8mb4_0900_ai_ci collation, however, another column in the parent table was referenced using CHARACTER SET = utf8 , COLLATE = utf8_bin ; to a different child table.

For the entire schema, I changed the character set and collation for all the tables and all the columns to the following:

CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;

This finally solved my problem with 1215 error.

Side Note: The collation utf8mb4_general_ci works in MySQL Workbench 5.0 or later. Collation utf8mb4_0900_ai_ci works just for MySQL Workbench 8.0 or higher. I believe one of the reasons I had issues with character set and collation is due to MySQL Workbench upgrade to 8.0 in between. Here is a link that talks more about this collation.

Ararat answered 17/10, 2018 at 21:36 Comment(0)
E
2

I had the same problem.

I solved it doing this:

I created the following line in the primary key: (id int(11) unsigned NOT NULL AUTO_INCREMENT)

I found out this solution after trying to import a table in my schema builder.

Extent answered 30/3, 2014 at 15:11 Comment(0)
L
2

I can not find this error

CREATE TABLE RATING (

Riv_Id INT(5),
Mov_Id INT(10) DEFAULT 0,
Stars INT(5),
Rating_date DATE, 

PRIMARY KEY (Riv_Id, Mov_Id),

FOREIGN KEY (Riv_Id) REFERENCES REVIEWER(Reviewer_ID)
ON DELETE SET NULL ON UPDATE CASCADE,

FOREIGN KEY (Mov_Id) REFERENCES MOVIE(Movie_ID)
ON DELETE SET DEFAULT ON UPDATE CASCADE
)
Loment answered 11/8, 2014 at 1:7 Comment(1)
What do you mean by "I can not find this error"? Can't you reproduce the error? Or are you asking a question? Or something else? How does this answer the question? Can you elaborate?Uzziel
S
2

For me it was the column types. BigINT != INT.

But then it still didn't work.

So I checked the engines. Make sure Table1 = InnoDB and Table = InnoDB

Southard answered 10/9, 2015 at 4:5 Comment(0)
S
2

Another reason: if you use ON DELETE SET NULL all columns that are used in the foreign key must allow null values. Someone else found this out in this question.

From my understanding it wouldn't be a problem regarding data integrity, but it seems that MySQL just doesn't support this feature (in 5.7).

Stolon answered 6/3, 2017 at 10:20 Comment(0)
H
2

You may also check the Engine of both tables is set to InnoDB.

Hickok answered 30/10, 2021 at 12:37 Comment(0)
V
1

When this error occurs because the referenced table uses the MyISAM engine, this answer provides a quick way to convert your database so all Django model tables use InnoDB: Converting an existing MyISAM database to InnoDB with Django

It's a Django management command called convert_to_innodb.

Vesicate answered 7/1, 2015 at 23:45 Comment(0)
P
1

Wooo, I just got it! It was a mix of a lot of already-posted answers (InnoDB, unsigned, etc.).

One thing I didn't see here though is: if your foreign key is pointing to a primary key, ensure the source column has a value that makes sense. For example, if the primary key is a mediumint(8), make sure the source column also contains a mediumint(8). That was part of the problem for me.

Pickaninny answered 5/5, 2015 at 22:16 Comment(0)
T
1

I experienced this error for a completely different reason. I used MySQL Workbench 6.3 for creating my data model (awesome tool). I noticed that when the column order defined in the foreign key constraint definition does not fit the table column sequence, this error is also generated.

It took me about four hours of trying everything else but checking that.

Now all is working well and I can get back to coding. :-)

Taryntaryne answered 5/12, 2015 at 22:8 Comment(2)
What do you mean by that?Cartel
@YazanJaber I think he means this: InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.Stolon
F
1

When trying to make a foreign key when using Laravel migration, like this example:

User table

public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->TinyInteger('color_id')->unsigned();
        $table->foreign('color_id')->references('id')->on('colors');
        $table->timestamps();
    });
}

Colors table

public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('color');
        $table->timestamps();
    });
}

Sometimes properties didn't work:

[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

This error happened because the foreign key (type) in [user table] is different from the primary key (type) in the [colors table].

To solve this problem, you should change the primary key in the [colors table]:

$table->tinyIncrements('id');


When you use the primary key, $table->Increments('id');, you should use Integer as a foreign key:

$table->unsignedInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->tinyIncrements('id'); you should use unsignedTinyInteger as a foreign key:

$table->unsignedTinyInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->smallIncrements('id'); you should use unsignedSmallInteger as a foreign key:

$table->unsignedSmallInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->mediumIncrements('id'); you should use unsignedMediumInteger as a foreign key:

$table->unsignedMediumInteger('fk_id');
$table->foreign('fk_id')->references('id')->on('table_name');
Fults answered 16/6, 2017 at 13:13 Comment(1)
This helps me. I had bigIncrements as the primary key, so I required to use unsignedBigIntegerHadhramaut
V
1

So I tried all the fixes above and no luck. I may be missing the error in my tables -just could not find the cause and I kept getting error 1215. So I used this fix.

In my local environment in phpMyAdmin, I exported data from the table in question. I selected format CSV. While still in phpMyAdmin with the table selected, I selected "More->Options". Here I scrolled down to "Copy table to (database.table). Select "Structure only". Rename the table something, maybe just add the word "copy" next to the current table name. Click "Go" This will create a new table. Export the new table and import it to the new or other server. I am also using phpMyAdmin here also. Once imported change the name of the table back to its original name. Select the new table, select import. For format select CSV. Uncheck "enable foreign key checks". Select "Go". So far all is working good.

I posted my fix on my blog.

Valvulitis answered 2/2, 2020 at 22:0 Comment(0)
S
0

Be aware of the use of backticks too. I had in a script the following statement

ALTER TABLE service ADD FOREIGN KEY (create_by) REFERENCES `system_user(id)`;

but the backticks at the end were false. It should have been:

ALTER TABLE service ADD FOREIGN KEY (create_by) REFERENCES `system_user`(`id`);

MySQL unfortunately does not give any details on this error...

Stumer answered 31/8, 2015 at 12:6 Comment(0)
S
0

Another source of this error is when you have two or more of the same table names which have the same foreign key names.

This sometimes happens to people who use modelling and design software, like MySQL Workbench, and later generate the script from the design.

Strafe answered 6/5, 2016 at 8:43 Comment(0)
C
0

As well as all of the previous advice for making sure that fields are identically defined, and table types also have the same collation, make sure that you don't make the rookie mistake of trying to link fields where data in the child field is not already in the parent field. If you have data that is in the child field that you have not already entered in to the parent field then that will cause this error. It's a shame that the error message is not a bit more helpful.

If you are unsure, then back up the table that has the foreign key, delete all the data and then try to create the foreign key. If successful then you know what to do!

Cawley answered 2/7, 2017 at 22:4 Comment(0)
L
0

This is a subtle version of what has already been said, but in my instance, I had 2 databases (foo and bar). I created foo first and I didn't realize it referenced a foreign key in bar.baz (which wasn't created yet). When I tried to create bar.baz (without any foreign keys), I kept getting this error. After looking around for a while I found the foreign key in foo.

So, long story short, If you get this error, you may have a pre-existing foreign key to the table being created.

Lavernalaverne answered 20/10, 2017 at 4:36 Comment(0)
R
0

For me, the 1215 error occurred when I was importing a dumpfile created by mysqldump, which creates the tables alphabetically, which in my case, caused foreign keys to reference tables created later in the file. (Props to this blog post for pointing it out: MySQL Error Code 1215: “Cannot add foreign key constraint”)

Since mysqldump orders tables alphabetically and I did not want to change the names of tables, I followed the instructions in the answer by JeremyWeir on this page, which states to put set FOREIGN_KEY_CHECKS = 0; at the top of the dump file and put SET FOREIGN_KEY_CHECKS = 1; at the bottom of the dump file.

That solution worked for me.

Righthanded answered 4/6, 2019 at 0:50 Comment(0)
S
0

For me the issue was that I was trying to reference the second column in a composite primary key (eg. ['column1', 'column2']).

In the error message it mentions that the column needs to be first:

Cannot find an index in the referenced table where the referenced columns appear as the first columns [...]

After adding an additional index on the second column (column2 in the example), I was able to add the foreign key.

Sodium answered 22/5, 2023 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.