EmergencyEMERGENCY? Get 24/7 Help Now!

Dealing with MySQL Error Code 1215: “Cannot add foreign key constraint”

 | April 6, 2017 |  Posted In: Insight for DBAs, Insight for Developers, MySQL

PREVIOUS POST
NEXT POST

MySQL error code 1215In this blog, we’ll look at how to resolve MySQL error code 1215: “Cannot add foreign key constraint”.

Our Support customers often come to us with things like “My database deployment fails with error 1215”, “Am trying to create a foreign key and can’t get it working” or “Why am I unable to create a constraint?” To be honest, the error message doesn’t help much. You just get the following line:

ERROR 1215 (HY000): Cannot add foreign key constraint

But MySQL never tells you exactly WHY it failed. There’s actually a multitude of reasons this can happen. This blog post is a compendium of the most common reasons why you can get ERROR 1215, how to diagnose your case to find which one is affecting you and potential solutions for adding the foreign key.

(Note: be careful when applying the proposed solutions, as many involve ALTERing the parent table and that can take a long time blocking the table, depending on your table size, MySQL version and the specific ALTER operation being applied; In many cases using pt-online-schema-change will be likely a good idea).

So, onto the list:

1) The table or index the constraint refers to does not exist yet (usual when loading dumps).

How to diagnose: Run SHOW TABLES or SHOW CREATE TABLE for each of the parent tables. If you get error 1146 for any of them, it means tables are being created in wrong order.
How to fix: Run the missing CREATE TABLE and try again, or temporarily disable foreign-key-checks. This is especially needed during backup restores where circular references might exist. Simply run:

Example:

2) The table or index in the constraint references misuses quotes.

How to diagnose: Inspect each FOREIGN KEY declaration and make sure you either have no quotes around object qualifiers, or that you have quotes around the table and a SEPARATE pair of quotes around the column name.
How to fix: Either don’t quote anything, or quote the table and the column separately.
Example:

3) The local key, foreign table or column in the constraint references have a typo:

How to diagnose: Run SHOW TABLES and SHOW COLUMNS and compare strings with those in your REFERENCES declaration.
How to fix: Fix the typo once you find it.
Example:

4) The column the constraint refers to is not of the same type or width as the foreign column:

How to diagnose: Use SHOW CREATE TABLE parent to check that the local column and the referenced column both have same data type and width.
How to fix: Edit your DDL statement such that the column definition in the child table matches that of the parent table.
Example:

5) The foreign object is not a KEY of any kind

How to diagnose: Use SHOW CREATE TABLE parent to check that if the REFERENCES part points to a column, it is not indexed in any way.
How to fix: Make the column a KEY, UNIQUE KEY or PRIMARY KEY on the parent.
Example:

6) The foreign key is a multi-column PK or UK, where the referenced column is not the leftmost one

How to diagnose: Do a SHOW CREATE TABLE parent to check if the REFERENCES part points to a column that is present in some multi-column index(es), but is not the leftmost one in its definition.
How to fix: Add an index on the parent table where the referenced column is the leftmost (or only) column.
Example:

7) Different charsets/collations among the two table/columns

How to diagnose: Run SHOW CREATE TABLE parent and compare that the child column (and table) CHARACTER SET and COLLATE parts match those of the parent table.
How to fix: Modify the child table DDL so that it matches the character set and collation of the parent table/column (or ALTER the parent table to match the child’s wanted definition.
Example:

8) The parent table is not using InnoDB

How to diagnose: Run SHOW CREATE TABLE parent and verify if ENGINE=INNODB or not.
How to fix: ALTER the parent table to change the engine to InnoDB.
Example:

9) Using syntax shorthands to reference the foreign key

How to diagnose: Check if the REFERENCES part only mentions the table name. As explained by ex-colleague Bill Karwin in http://stackoverflow.com/questions/41045234/mysql-error-1215-cannot-add-foreign-key-constraint, MySQL doesn’t support this shortcut (even though this is valid SQL).
How to fix: Edit the child table DDL so that it specifies both the table and the column.
Example:

10) The parent table is partitioned

How to diagnose: Run SHOW CREATE TABLE parent and find out if it’s partitioned or not.
How to fix: Removing the partitioning (i.e., merging all partitions back into a single table) is the only way to get it working.
Example:

11) Referenced column is a generated virtual column (this is only possible with 5.7 and newer)

How to diagnose: Run SHOW CREATE TABLE parent and verify that the referenced column is not a virtual column.
How to fix: CREATE or ALTER the parent table so that the column will be stored and not generated.
Example:

12) Using SET DEFAULT for a constraint action

How to diagnose: Check your child table DDL and see if any of your constraint actions (ON DELETE, ON UPDATE) try to use SET DEFAULT
How to fix: Remove or modify actions that use SET DEFAULT from the child table CREATE or ALTER statement.
Example:

I realize many of the solutions are not what you might desire, but these are limitations in MySQL that must be overcome on the application side for the time being. I do hope the list above gets shorter by the time 8.0 is released!

If you know other ways MySQL can fail with ERROR 1215, let us know in the comments!

More information regarding Foreign Key restrictions can be found here: https://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html.

PREVIOUS POST
NEXT POST

7 Comments

  • Good post, but it seems one important detail is missing: you may find more details on why adding foreign key failed using SHOW ENGINE INNODB STATUS\G, like in this case:

    mysql> create table parent(id int primary key);
    Query OK, 0 rows affected (0.33 sec)

    mysql> CREATE TABLE child (
    -> id INT(10) NOT NULL PRIMARY KEY,
    -> parent_id INT(10) NOT NULL,
    -> FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE SET DEFAULT
    -> ) ENGINE INNODB;
    ERROR 1215 (HY000): Cannot add foreign key constraint
    mysql> show engine innodb status\G
    *************************** 1. row ***************************
    Type: InnoDB
    Name:
    Status:
    =====================================
    2017-04-06 21:26:12 1b38 INNODB MONITOR OUTPUT
    =====================================
    Per second averages calculated from the last 10 seconds
    —————–
    BACKGROUND THREAD
    —————–
    srv_master_thread loops: 2 srv_active, 0 srv_shutdown, 129 srv_idle
    srv_master_thread log flush and writes: 131
    ———-
    SEMAPHORES
    ———-
    OS WAIT ARRAY INFO: reservation count 7
    OS WAIT ARRAY INFO: signal count 7
    Mutex spin waits 3, rounds 90, OS waits 3
    RW-shared spins 4, rounds 120, OS waits 4
    RW-excl spins 0, rounds 0, OS waits 0
    Spin rounds per wait: 30.00 mutex, 30.00 RW-shared, 0.00 RW-excl
    ————————
    LATEST FOREIGN KEY ERROR
    ————————
    2017-04-06 21:26:03 1b38 Error in foreign key constraint of table test/child:
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON UPDATE SET DEFAULT
    ) ENGINE INNODB:
    Syntax error close to:
    DEFAULT
    ) ENGINE INNODB

    Way more informative than just error 1215 🙂

  • Hi,
    I just found another way when mySQL fails to create a FK : the columns of the referenced table MUST MATCH the order of the PK !
    I didn’t found anything in the web with this restriction.

  • Found another reason, maybe a stupid one, but to me it happened:
    If you want the constraint action to be “SET NULL”, then the child column needs to allow NULL-values in the table structure.

  • Thanks, thats a great info,

    Valeriy – your InnoDB status query helped me to understand why I was getting an error.

    Basically, I was trying to ‘SET NULL’ on delete and at the same time I was defining the column as NOT NULL.

Leave a Reply