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.
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.
MySQL Error Code: 1215
Official name: Cannot Add Foreign Key Constraint
Service: MySQL
Cannot add foreign key constraint
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.
Validate the FK column type matches the parent PK before creating tables.
// users.id BIGINT UNSIGNED -> posts.user_id must be BIGINT UNSIGNED too
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
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);
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.
The message is terse; inspect the FK definition with `SHOW CREATE TABLE` on both tables.
This page documents fixes for: nodejs-mysql2, python-sqlalchemy, php-pdo.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official MySQL documentation linked below and adds practical troubleshooting guidance on top.