MySQL 1452: Cannot add or update a child row: fix
The child column holds a value that no parent row has. Compare types and collations, check order of inserts and use a deferred or nullable key.

Introduction & Quick Summary
An insert that has worked for months fails after a data change:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`shop`.`orders`, CONSTRAINT `fk_orders_customer` FOREIGN KEY (`customer_id`)
REFERENCES `customers` (`id`))Quick answer: orders.customer_id holds a value that no row in customers.id provides. InnoDB checks the parent table on every insert and update of the child, and refuses the write. Either the parent row is missing, the value is a placeholder such as 0, or the parent was deleted while the child still references it.
-- is the parent there?
SELECT id FROM customers WHERE id = 4821;
-- which children point nowhere?
SELECT o.id, o.customer_id
FROM orders o LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL;The fix follows from which of those is true: create the parent, correct the value, or change the constraint's action so a deleted parent does not leave children behind. This guide covers reading the message, finding orphan rows at scale, ordering writes inside a transaction, and adding a foreign key to a table that already contains bad data.
Core Mechanics, Signatures & Reproducible Setup
InnoDB enforces a foreign key by looking up the referenced key in the parent table for each inserted child row. The parent column must be indexed, and the child column needs an index too; the constraint can restrict, cascade or nullify the child on parent changes.
CREATE TABLE customers (
id BIGINT UNSIGNED PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
) ENGINE=InnoDB;
CREATE TABLE orders (
id BIGINT UNSIGNED PRIMARY KEY,
customer_id BIGINT UNSIGNED NOT NULL,
total DECIMAL(10,2) NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB;
INSERT INTO orders VALUES (1, 4821, 19.90);
-- ERROR 1452 (23000): Cannot add or update a child row ...
INSERT INTO customers VALUES (4821, 'ryu@example.com');
INSERT INTO orders VALUES (1, 4821, 19.90); -- OKThe message names the child table, the constraint and both column lists, which is everything needed to write the diagnostic query. SHOW CREATE TABLE orders returns the same definition, and SHOW ENGINE INNODB STATUS adds the latest foreign key error under LATEST FOREIGN KEY ERROR when the client truncates the message.
SHOW ENGINE INNODB STATUS\G
-- LATEST FOREIGN KEY ERROR
-- ------------------------
-- 2026-11-28 07:00:12 0x... Error in foreign key constraint ...
-- Cannot find or open table `shop`.`customers` ...Key Comparison Table
| Error | Happens when | Meaning |
|---|---|---|
| 1452 | insert or update of the child | parent value does not exist |
| 1451 | delete or update of the parent | children still reference it |
| 1215 | CREATE TABLE with the key | referenced column is not indexed or types differ |
| 1216 | adding a constraint | old table has no matching parent key |
| 1701 | TRUNCATE on a parent | table is referenced by a foreign key |
| Action | On parent delete or update | Use when |
|---|---|---|
RESTRICT / NO ACTION | statement fails with 1451 | children must be cleaned first |
CASCADE | children deleted or updated | ownership relationship |
SET NULL | child column set to null | optional relationship, column nullable |
SET DEFAULT | not supported by InnoDB | never |
| no constraint | nothing checked | rarely correct |
| Cause of 1452 | Quick check | Fix |
|---|---|---|
| parent row missing | SELECT ... WHERE id = ? | insert or correct the parent |
placeholder 0 or '' | inspect distinct child values | use NULL and make the column nullable |
| import loaded children first | migration or dump order | load parents first |
| parent deleted later | LEFT JOIN for orphans | delete or reassign children |
| truncated parent table | row count of parent | restore data |
| wrong database or schema | SELECT DATABASE() | point at the right schema |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Read the constraint, then query the value
The message gives table, constraint, child column and parent column. Query the exact value that failed, which the statement's parameters already tell you:
SELECT id, customer_id FROM orders ORDER BY id DESC LIMIT 5;
SELECT COUNT(*) FROM customers WHERE id = 4821;For an update that touches many rows, find the rows that would break:
SELECT o.id, o.customer_id
FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id);NOT EXISTS and LEFT JOIN ... IS NULL return the same set; the join version reads better when several columns are compared.
2. Orphan rows after a bulk import
Bulk loading with LOAD DATA or a restored dump often inserts children before parents, and the failure appears at the end of a long run. Sort the input by dependency, or disable checks for the duration of the load and verify afterwards:
SET SESSION foreign_key_checks = 0;
LOAD DATA INFILE '/tmp/orders.csv' INTO TABLE orders
FIELDS TERMINATED BY ',' IGNORE 1 LINES;
SET SESSION foreign_key_checks = 1;
-- verification after the load: must return 0
SELECT COUNT(*) FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL;foreign_key_checks is a session variable, so the setting does not leak to other connections, but it also means a load that leaves orphans will not report them. Verification is not optional with this pattern.
3. Insert order and transactions
Within one transaction, insert the parent first. With AUTO_INCREMENT, use LAST_INSERT_ID() so the child gets the generated key:
START TRANSACTION;
INSERT INTO customers (email) VALUES ('ryu@example.com');
SET @cid := LAST_INSERT_ID();
INSERT INTO orders (customer_id, total) VALUES (@cid, 19.90);
COMMIT;MySQL checks foreign keys per statement, not at commit time, so there is no deferred-constraint trick as in PostgreSQL. If the application creates an order and a customer in the same request, the order must be written after the customer insert succeeds, even inside one transaction.
4. Sentinels: 0, empty string and NULL
Legacy schemas often use 0 to mean "no customer". Since no customer row has id 0, every such row fails the constraint. The clean fix is a nullable column with NULL:
ALTER TABLE orders MODIFY customer_id BIGINT UNSIGNED NULL;
UPDATE orders SET customer_id = NULL WHERE customer_id = 0;
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE SET NULL;NULL is exempt from the check, which makes it the only sentinel that works with a foreign key. Empty strings and 0 are ordinary values and must exist in the parent table.
5. Adding a constraint to a table with existing data
Adding the key validates every existing row, and one orphan stops the migration:
-- find all orphans before touching the schema
SELECT COUNT(*) AS orphans FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id WHERE c.id IS NULL;
-- clean, then add
DELETE o FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE c.id IS NULL;
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id);On a large table the validation takes a metadata lock; do it during a maintenance window or with ALGORITHM=INPLACE, LOCK=NONE where the operation supports it. Designing the schema alongside the migration keeps column types aligned from the start — the SQL schema designer shows the referenced keys, and the SQL formatter helps compare a generated migration with the version that ran.
6. Type and engine mismatches
A constraint that cannot even be created usually returns 1215 rather than 1452, but mismatched types still produce 1452 at insert time when values compare differently than expected. BIGINT UNSIGNED against INT on the parent, or a different collation on VARCHAR columns, are the usual pairs:
SHOW CREATE TABLE orders\G
SHOW CREATE TABLE customers\G
SHOW TABLE STATUS LIKE 'orders'\G -- Engine must be InnoDBBoth tables must be InnoDB; a MyISAM parent is not checked at all and gives inconsistent behaviour after a conversion.
Common Compilation/Runtime Mistakes & Version Gotchas
- Turning checks off permanently.
foreign_key_checks = 0in a config file or connection initialisation silently disables integrity for every session. - Expecting deferrable constraints. MySQL and MariaDB check per statement; there is no
DEFERRABLE INITIALLY DEFERRED. - Making the child column nullable as the only fix. It removes the error but also removes the guarantee that an order has a customer; use it only when the relationship really is optional.
- Ignoring the parent index. A referenced column without a unique index fails at creation with 1215, which is a different fix from 1452.
- Version notes.
SET DEFAULTis parsed and rejected by InnoDB;ON UPDATE CASCADEworks but changes the child value silently. MySQL 8.0.16 and later enforceCHECKconstraints, which adds a second class of failures next to the foreign key ones. - Restoring dumps.
mysqldumpwrites tables in dependency order and wraps the file withforeign_key_checks=0; a hand-edited dump or a partial restore loses that, and the first child insert fails.
Official documentation: InnoDB foreign key constraints and foreign keys.
Official references
primary documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
pg_dump: server version mismatch, aborting because of server version
pg_dump refuses to read a newer server. Install a matching client, run it from a container or the server host, and match pg_restore too.
MySQL: ERROR 1040 (HY000) Too many connections
The server is out of slots because pools are too large or leaking. Read the counters, size pools against replicas, then raise the limit.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.