1216
MySQLERRORCommonIntegrity Constraint ViolationHIGH confidence

Cannot 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
  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
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

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 the parent row first
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

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 versions

Error 1216 is child-side (inserting into child with non-existent parent). Error 1217 is parent-side (deleting a parent that has children).

Sources
Official documentation ↗

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

← All MySQL errors