MySQL ERROR 1451: Cannot delete or update a parent row means InnoDB refused to delete a row, or change its key, because rows in another table still reference it through a foreign key.
mysql> DELETE FROM customers WHERE id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`shop`.`orders`, CONSTRAINT `fk_orders_customer` FOREIGN KEY (`customer_id`)
REFERENCES `customers` (`id`))
The server error reference lists it as ER_ROW_IS_REFERENCED_2, SQLSTATE 23000, with a short instruction: delete the children first. The part in parentheses is the useful bit. It names the child table (orders), the constraint and the columns, so you already know where the blocking rows live. It is the mirror image of ERROR 1452 Cannot add or update a child row, where the child references a parent that does not exist.
Why MySQL refuses
A foreign key declared without an ON DELETE or ON UPDATE clause behaves as RESTRICT. According to the foreign key documentation, NO ACTION is the same thing in InnoDB: the operation is rejected immediately if a matching child row exists. Unlike some other databases, InnoDB has no deferred checking, so you cannot delete the parent first and fix the children before commit. The order inside the transaction matters.
Statements that hit 1451 unexpectedly
- REPLACE. The REPLACE documentation explains that when a new row conflicts on a primary or unique key, the old row is deleted before the new one is inserted. That delete is checked like any other, so
REPLACE INTO customers ...fails with 1451 on a customer that has orders.INSERT ... ON DUPLICATE KEY UPDATEupdates the row in place and does not have this problem as long as the key itself does not change. - Updating a referenced key.
UPDATE customers SET id = ...or changing a referenced unique column such as an email is an update of the parent key and fails the same way. Updates of other columns are fine. - Self-referencing tables. In a category tree where
parent_idreferencesidof the same table, deleting a whole subtree can fail depending on the order in which InnoDB visits the rows. In our experience deleting leaves first, for example withORDER BYon depth or id in descending order, is the reliable approach. - TRUNCATE and DROP. These are not row deletes, so they report different codes:
TRUNCATEon a referenced table gives ERROR 1701 "Cannot truncate a table referenced in a foreign key constraint", andDROP TABLEgives ERROR 3730 "Cannot drop table ... referenced by a foreign key constraint".
How to find the blocking rows
For a single failing statement the error text is enough. For a cleanup job you want the full list of child tables and their rules. Run this before writing purge logic:
-- which tables point at customers, and what do they do on delete?
SELECT rc.TABLE_NAME, rc.CONSTRAINT_NAME, k.COLUMN_NAME,
rc.DELETE_RULE, rc.UPDATE_RULE
FROM information_schema.REFERENTIAL_CONSTRAINTS rc
JOIN information_schema.KEY_COLUMN_USAGE k
ON k.CONSTRAINT_SCHEMA = rc.CONSTRAINT_SCHEMA
AND k.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
AND k.TABLE_NAME = rc.TABLE_NAME
WHERE rc.CONSTRAINT_SCHEMA = 'shop'
AND rc.REFERENCED_TABLE_NAME = 'customers';
-- which child rows block this delete?
SELECT id FROM orders WHERE customer_id = 1 LIMIT 20;
SHOW ENGINE INNODB STATUS also has a LATEST FOREIGN KEY ERROR section, described in the InnoDB monitor documentation. It shows the statement, the constraint and the parent and child index records, which helps when the failing statement came from an application and the error message was lost in a log.
How to fix it
- Delete children first, in the same transaction. Work from the deepest table up: line items, then orders, then the customer.
- Change the rule if the data model says so. If an order really has no meaning without its customer,
ON DELETE CASCADEis honest. If orders must survive,ON DELETE SET NULLkeeps them with an empty reference (the column must allowNULL). Changing the rule means dropping and re-creating the constraint. - Soft delete. For customers, users and products, a
deleted_atcolumn is often a better answer than a delete: history and invoices keep pointing at a real row. - Replace REPLACE. Use
INSERT ... ON DUPLICATE KEY UPDATEfor upserts on parent tables.
-- children first, then the parent, in one transaction
START TRANSACTION;
DELETE FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE customer_id = 1);
DELETE FROM orders WHERE customer_id = 1;
DELETE FROM customers WHERE id = 1;
COMMIT;
-- or change the rule (drop and re-create the constraint)
ALTER TABLE orders DROP FOREIGN KEY fk_orders_customer;
ALTER TABLE orders ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
ON DELETE CASCADE;
Be careful with CASCADE and with switching checks off. The documentation notes that cascaded foreign key actions do not activate triggers, so audit or cleanup logic written as AFTER DELETE triggers on the child table silently does not run for cascaded rows. SET foreign_key_checks = 0 makes the 1451 go away, but the parent is deleted and the children stay as orphans. The documentation is explicit that re-enabling the variable does not scan the table data, so nothing will tell you later. Use it for reloading dumps and dropping tables, which is what it is meant for, not to get past a delete.
Purging parents on large tables
A cleanup that works on a test copy can hurt production once the tables are big:
- A cascade is still one statement.
DELETE FROM customers WHERE created_at < ...withON DELETE CASCADEdeletes every matching order and line item inside the same transaction. That means row locks on all of them, a large undo log, a long rollback if it is killed, and on a replica one huge transaction that holds back everything behind it. Delete children in batches first, then the parents. - Each parent delete looks up children. InnoDB requires an index on the foreign key columns and creates one automatically if needed, so the lookup is an index probe, not a scan. On a purge of millions of parents it still adds up. Measure on realistic data.
- Locks reach across tables. MySQL extends metadata locks to tables related by a foreign key, so DDL on
customerscan wait for a long transaction onorders, and the other way round. - Changing the rule rebuilds the table. Per the online DDL documentation, dropping a foreign key is an in-place, metadata-only change, but adding one uses
ALGORITHM=INPLACEonly whenforeign_key_checksis disabled. Otherwise MySQL rejectsINPLACEwith ERROR 1846 and onlyCOPYis supported. If you add it with checks disabled, existing rows are not validated, so check for orphans with aLEFT JOINbeforehand. More on running these changes safely is in our guide to ALTER TABLE without downtime.
-- delete children in small chunks, repeat until 0 rows affected
DELETE FROM orders
WHERE customer_id IN (SELECT id FROM customers_to_purge)
ORDER BY id
LIMIT 5000;
-- then the parents, also in chunks
DELETE FROM customers
WHERE id IN (SELECT id FROM customers_to_purge)
ORDER BY id
LIMIT 5000;
The batch size depends on row width, indexes and replica capacity; in our experience a few thousand rows per statement, with a short pause and a replica lag check between batches, keeps both the primary and the replicas responsive.
Key takeaways
- ERROR 1451 (23000) means child rows still reference the parent you are deleting or re-keying. The message names the child table and the constraint.
- InnoDB checks immediately and has no deferred constraints: delete children first, in the same transaction.
REPLACEand updates of referenced keys also trigger 1451;TRUNCATEandDROPreport 1701 and 3730.ON DELETE CASCADEskips child triggers, andforeign_key_checks = 0leaves orphans that are never re-checked.- On large tables purge children in batches before parents, and plan constraint changes as table rebuilds unless checks are disabled.