PostgreSQL: insert or update violates foreign key constraint
ERROR: insert or update on table "<t>" violates foreign key constraint "<fk>"You inserted or updated a row that points to a parent row that does not exist. The DETAIL line names the key that is missing from the parent table. Insert the parent first, fix the reference value, or defer the constraint for circular inserts.
What this error means
A foreign key says a value in the child table must exist in the parent table. When you write a child row whose reference has no matching parent, Postgres blocks it to keep the relationship consistent.
The most common cause is ordering: the code inserts the child before the parent is committed, or uses an id for a parent that was never created.
How to fix it
The parent row does not exist yet
Insert and commit the parent before the child, so the referenced key is present.
INSERT INTO customers (id, email) VALUES (1, 'a@example.com');
INSERT INTO orders (customer_id, total) VALUES (1, 42.00);The reference value is wrong
Check that the value you are inserting actually exists in the parent table.
SELECT id FROM customers WHERE id = 1;Two tables reference each other (circular insert)
Use a deferrable constraint and defer it inside the transaction so both rows can be inserted before the check runs.
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
-- insert both rows in either order
COMMIT;How to avoid it next time
- Insert parents before children, or wrap related inserts in one transaction with deferred constraints.
- Define ON DELETE and ON UPDATE actions that match how your app treats the relationship.
Frequently asked questions
Why does deleting a parent row fail instead?
That is the mirror case: a child still references the parent. It raises the same 23503 with a slightly different message and is fixed with ON DELETE CASCADE or by deleting the children first.
Can I insert child and parent in any order?
Only if the foreign key is DEFERRABLE and you defer it in the transaction. Otherwise the parent must exist when the child is inserted.
Stop struggling with SQL
Use FluentDB, the AI database client for macOS.
Related errors
Part of the PostgreSQL error reference. Last reviewed 2026-07-31.