1216ERRORTier 1 — Safe✅ HIGH confidence

Cannot add or update a child row: a foreign key constraint fails

Category: Integrity Constraint ViolationVersions: All MariaDB / MySQL versions

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

  1. 1Inserting a child row with a parent_id that does not exist in the parent table
  2. 2Updating a child row's foreign key column to a value that has no matching parent row
  3. 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.

trigger — this will ERROR
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
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 1: Insert the parent row first

When the parent row is missing.

fix
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.

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

📄 Reference pages

foreign keysON DELETE CASCADEreferential integrity
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →