1451
MySQLERRORNotableForeign KeyHIGH confidence

Cannot delete — parent row referenced by child

What this means

ER_ROW_IS_REFERENCED_2 (1451) is returned when deleting a parent row that has matching rows in a child table via a FOREIGN KEY constraint. SQLSTATE 23000.

How to reproduce
trigger — this will error
trigger — this will error
DELETE FROM customers WHERE id = 1;
-- customer_id = 1 is referenced in the orders table

expected output

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails

Fix 1

Delete child rows first

WHEN Child data should be removed along with the parent.

Delete child rows first
DELETE FROM orders WHERE customer_id = 1;
DELETE FROM customers WHERE id = 1;

Why this works

Deleting child rows removes the FK references, allowing the parent delete to proceed.

Fix 2

Use ON DELETE CASCADE

WHEN Child rows should automatically be deleted with the parent.

Use ON DELETE CASCADE
ALTER TABLE orders
  ADD CONSTRAINT fk_customer
  FOREIGN KEY (customer_id) REFERENCES customers(id)
  ON DELETE CASCADE;

Why this works

CASCADE propagates the DELETE to child rows automatically at the engine level.

What not to do

Disable foreign key checks to force the delete

SET FOREIGN_KEY_CHECKS=0 bypasses referential integrity and leaves orphaned rows that cause data corruption downstream.

Sources
Official documentation ↗

MySQL 8.0 — 1451 ER_ROW_IS_REFERENCED_2

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

← All MySQL errors