MySQL Error 1215: Cannot Add Foreign Key Constraint

MySQL error 1215 (Cannot Add Foreign Key Constraint) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

MySQL Error Code 1215 MySQL Last verified 2026-08-19

Quick Answer

The message is terse; inspect the FK definition with `SHOW CREATE TABLE` on both tables. If that does not apply, ensure both columns share the exact same type, length, and collation (e.g. INT(11) vs BIGINT) — the full checklist is below.

Error Code

MySQL Error Code: 1215
Official name: Cannot Add Foreign Key Constraint
Service: MySQL

What does this error mean?

Cannot add foreign key constraint

Common Causes

How to Fix

  1. The message is terse; inspect the FK definition with `SHOW CREATE TABLE` on both tables
  2. Ensure both columns share the exact same type, length, and collation (e.g. INT(11) vs BIGINT)
  3. Make sure the referenced column is indexed — MySQL adds an index automatically when you reference a primary key
  4. Confirm both tables are ENGINE=InnoDB: `SHOW TABLE STATUS LIKE 'orders';`
  5. If the referenced column is UNIQUE/PRIMARY, an index exists; otherwise add one first

Code Examples

Compare the two columns sql
SHOW CREATE TABLE users;
SHOW CREATE TABLE orders;
-- user_id in orders must equal id in users: same type, length, charset

Type, length, collation, and index requirements are all visible side by side.

Framework-Specific Fixes

nodejs-mysql2

Validate the FK column type matches the parent PK before creating tables.

// users.id BIGINT UNSIGNED  ->  posts.user_id must be BIGINT UNSIGNED too
python-sqlalchemy

Let the ORM derive the FK column type from the referenced column to keep them identical.

class Order(Base):
    __tablename__ = 'orders'
    user_id = Column(ForeignKey('users.id'), nullable=False)  # type inherited
php-pdo

Run the ALTER in the CLI first; it shows the real error details the app swallows.

// test in CLI:
// ALTER TABLE orders ADD CONSTRAINT fk FOREIGN KEY (user_id) REFERENCES users(id);

You Might Also Like

Frequently Asked Questions

Why am I seeing MySQL error 1215?

Most often this happens when the referenced column is not indexed (MySQL requires an index on the referenced columns), or when data type / length / character set mismatch between the FK column and the referenced column.

How do I fix MySQL error 1215?

The message is terse; inspect the FK definition with `SHOW CREATE TABLE` on both tables.

Which frameworks have documented fixes for error 1215?

This page documents fixes for: nodejs-mysql2, python-sqlalchemy, php-pdo.

Official Sources

This page is based on the official MySQL documentation linked below and adds practical troubleshooting guidance on top.