Cannot add or update a child row: a foreign key constraint fails
Error 1216 (SQLSTATE 23000) is raised when an INSERT or UPDATE on a child table inserts a foreign key value that does not exist in the referenced parent table. It is the runtime enforcement error for child-side FK violations.
- 1Inserting a child row with a parent_id that does not exist in the parent table
- 2Updating a child row's foreign key column to a value that has no matching parent row
- 3Loading child rows before their parent rows (incorrect import order)
A child row is inserted with a parent_id that does not exist.
CREATE TABLE customers (id INT PRIMARY KEY); CREATE TABLE orders ( id INT PRIMARY KEY, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(id) ); INSERT INTO orders VALUES (1, 999); -- customer 999 doesn't exist
expected output
ERROR 1216 (23000): Cannot add or update a child row: a foreign key constraint fails (`mydb`.`orders`, CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`))
Fix
Insert the parent row first
WHEN When the parent row is missing.
INSERT INTO customers VALUES (999); INSERT INTO orders VALUES (1, 999); -- now valid
Why this works
InnoDB checks the parent table's index for the foreign key value before committing the child insert. The parent row must exist at the time the child row is inserted.
✕ Disable foreign_key_checks to allow the insert
This allows orphaned child rows to accumulate. When FK checks are later re-enabled, SELECT queries that JOIN to the parent will silently exclude the orphaned rows, hiding data.
Error 1216 is child-side (inserting into child with non-existent parent). Error 1217 is parent-side (deleting a parent that has children).
MariaDB Server error code 1216 / ER_NO_REFERENCED_ROW
MariaDB foreign key actions ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev