1951
MySQLERRORCriticalConstraintHIGH confidence
Cannot add or update a child row: a foreign key constraint fails
Production Risk
High — data integrity violation; insert the parent record first.
What this means
An INSERT or UPDATE on a child table was blocked because the referenced parent row does not exist. This is the companion error to 1950.
Why it happens
- 1Inserting a row into a child table with a foreign key value that does not exist in the parent table.
- 2Updating the foreign key column to a value not present in the parent table.
How to reproduce
trigger — this will error
trigger — this will error
INSERT INTO orders (customer_id, total) VALUES (9999, 100); -- customer 9999 does not exist
expected output
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (mydb.orders, CONSTRAINT fk_cust FOREIGN KEY (customer_id) REFERENCES customers (id))
Fix
Insert the parent row first
Insert the parent row first
INSERT INTO customers (id, name) VALUES (9999, 'New Customer'); INSERT INTO orders (customer_id, total) VALUES (9999, 100);
Why this works
Always ensure the referenced parent record exists before inserting the child.
What not to do
✕
Version notes
Sources
Official documentation ↗
MySQL 8.0 — 1951 ER_NO_REFERENCED_ROW_2
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev