1452
MariaDBERRORCommonForeign KeyHIGH confidence

Cannot insert — child row has no matching parent

What this means

ER_NO_REFERENCED_ROW_2 (1452) is returned when inserting or updating a child row with a foreign key value that does not exist in the parent table. SQLSTATE 23000.

How to reproduce
trigger — this will error
trigger — this will error
INSERT INTO orders (customer_id, amount)
VALUES (9999, 100.00);
-- customer_id 9999 does not exist in customers

expected output

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

Fix

Insert the parent row first

WHEN The parent should exist.

Insert the parent row first
-- Ensure parent exists first
INSERT IGNORE INTO customers (id, name) VALUES (9999, 'New Customer');
INSERT INTO orders (customer_id, amount) VALUES (9999, 100.00);

Why this works

INSERT IGNORE skips the parent insert if the customer already exists, then the child insert can proceed.

What not to do

Use SET FOREIGN_KEY_CHECKS=0 to bypass the constraint

This inserts the child row with a dangling reference, creating an orphaned record that breaks JOINs and application logic.

Sources
Official documentation ↗

MySQL 8.0 — 1452 ER_NO_REFERENCED_ROW_2

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MariaDB errors