1216ERRORTier 1 — Safe✅ HIGH confidenceCannot add or update a child row: a foreign key constraint fails
What this means
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.
Why it happens
- 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)
How to reproduce
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 existFix 1: Insert the parent row first
When the parent row is missing.
INSERT INTO customers VALUES (999);
INSERT INTO orders VALUES (1, 999); -- now validWhy 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.
What not to do
Disable foreign_key_checks to allow the insert
Why it's wrong: 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.
Version notes
All versionsError 1216 is child-side (inserting into child with non-existent parent). Error 1217 is parent-side (deleting a parent that has children).Sources
📚 Official docs: https://mariadb.com/kb/en/foreign-keys/
🔧 Source ref: MariaDB Server error code 1216 / ER_NO_REFERENCED_ROW
📖 Further reading: MariaDB foreign key actions
Confidence assessment
✅ HIGH confidence
Stable and well-documented.
See also
🔗 Related errors
📄 Reference pages