MySQL error 1452 (Foreign Key Constraint Fails on Insert) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.
Read the constraint name and column from the message to know which FK failed. If that does not apply, verify the parent exists: `SELECT * FROM parent WHERE id = ?;` — the full checklist is below.
MySQL Error Code: 1452
Official name: Foreign Key Constraint Fails on Insert
Service: MySQL
Cannot add or update a child row: a foreign key constraint fails (%s)
-- The message names the FK (e.g. fk_orders_customer).
-- Check the offending value:
SELECT * FROM customers WHERE id = 999; -- empty = parent missing
Confirms whether the referenced row actually exists before you chase app bugs.
Validate the referenced id exists before insert, and handle the race with a retry.
const [parent] = await pool.query('SELECT id FROM users WHERE id = ?', [userId])
if (!parent.length) throw new BadRequest('user not found')
await pool.query('INSERT INTO posts (user_id, title) VALUES (?, ?)', [userId, title])
Add objects via the relationship so SQLAlchemy inserts the parent first.
user = session.get(User, user_id)
post = Post(title='Hi', author=user) # FK set from the relationship
session.add(post)
session.commit()
Wrap in a transaction and check the parent before inserting the child.
$pdo->beginTransaction();
$stmt = $pdo->prepare('SELECT 1 FROM users WHERE id = ?');
$stmt->execute([$userId]);
if (!$stmt->fetch()) { $pdo->rollBack(); throw new Exception('bad user'); }
Most often this happens when inserting or updating a child row whose foreign key value does not exist in the parent table, or when a parent row was deleted between check and insert (race) while the FK is RESTRICT.
Read the constraint name and column from the message to know which FK failed.
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.