Postgres: insert or update violates foreign key constraint
The child row references a parent that is absent at check time. Fix write ordering, key types and concurrent deletes, or defer the constraint for cycles.

Introduction & Quick Summary
ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(42) is not present in table "customers".The child row points at a parent that does not exist at the moment the constraint is checked. The DETAIL line gives the exact key values, which is usually enough to tell whether the parent was never inserted, was inserted in the wrong transaction, was deleted, or holds a key of a different type than the one you passed.
Four causes, in order of frequency:
- Write ordering. The application inserts the order before the customer, or a migration seeds children before parents.
- Value mismatch. A UUID string with different case, a trailing space, or an
intthat overflowed into a different value. - Deletion or truncation. A parent was removed while children still referenced it, or
TRUNCATE customersran withoutCASCADE. - Deferred checking. A
DEFERRABLE INITIALLY DEFERREDconstraint reports the violation atCOMMIT, far from the failing statement.
| Constraint action | Parent delete | Parent update | Child orphan |
|---|---|---|---|
NO ACTION | Fails at end of statement | Fails | Prevented |
RESTRICT | Fails immediately | Fails | Prevented |
CASCADE | Deletes children | Updates children | Allowed by design |
SET NULL | Nulls the column | Nulls the column | Column must be nullable |
SET DEFAULT | Sets default value | Sets default value | Default must exist |
Core Mechanics, Signatures & Reproducible Setup
A foreign key is enforced by an internal trigger on the child table. On insert or update, Postgres looks up the child's key in the parent's unique index; a miss aborts the statement with SQLSTATE 23503. The parent must be visible inside the same transaction, so a row committed after the child insert began does not help.
Reproduce it:
CREATE TABLE customers (id bigint PRIMARY KEY, email text NOT NULL);
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (id),
total numeric(12, 2) NOT NULL
);
INSERT INTO orders (customer_id, total) VALUES (42, 19.99);
-- ERROR: insert or update on table "orders" violates foreign key constraint
-- "orders_customer_id_fkey"
-- DETAIL: Key (customer_id)=(42) is not present in table "customers".The correct order, with the parent insert made idempotent:
INSERT INTO customers (id, email) VALUES (42, 'ada@example.com')
ON CONFLICT (id) DO NOTHING;
INSERT INTO orders (customer_id, total) VALUES (42, 19.99);For cyclic references, defer the check to commit:
ALTER TABLE orders
DROP CONSTRAINT orders_customer_id_fkey,
ADD CONSTRAINT orders_customer_id_fkey
FOREIGN KEY (customer_id) REFERENCES customers (id)
DEFERRABLE INITIALLY DEFERRED;
BEGIN;
INSERT INTO customers (id, email) VALUES (42, 'ada@example.com');
INSERT INTO orders (customer_id, total) VALUES (42, 19.99);
COMMIT; -- both checks run hereFind every foreign key that references a table before deleting from it:
SELECT conname, conrelid::regclass AS child, confdeltype
FROM pg_constraint
WHERE contype = 'f' AND confrelid = 'customers'::regclass;confdeltype is a for NO ACTION, r for RESTRICT, c for CASCADE, n for SET NULL and d for SET DEFAULT.
Key Comparison Table
| SQLSTATE | Condition | Message shape |
|---|---|---|
23503 | Foreign key violation | insert or update on table ... violates foreign key |
23502 | Not null violation | null value in column ... violates not-null |
23505 | Unique violation | duplicate key value violates unique constraint |
23514 | Check violation | new row for relation ... violates check constraint |
42P01 | Undefined table | relation ... does not exist |
| Fix | When | Trade-off |
|---|---|---|
| Insert parent first | Normal application flow | Requires ordering logic |
ON CONFLICT DO NOTHING on parent | Idempotent seed or API | Hides conflicting data |
DEFERRABLE INITIALLY DEFERRED | Cyclic references | Errors move to commit |
ON DELETE CASCADE | Children are owned | Deleting a parent removes history |
ON DELETE SET NULL | Child may outlive parent | Column must be nullable |
NOT VALID then VALIDATE | Large existing table | Two-step migration |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Seed scripts in the wrong order
INSERT INTO orders (id, customer_id, total) VALUES (1, 42, 9.99);
INSERT INTO customers (id, email) VALUES (42, 'ada@example.com');Migrations that run in a single transaction still fail here, because the FK is checked per statement unless deferred. Either reorder, or wrap the seed in a deferred transaction:
BEGIN;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO orders (id, customer_id, total) VALUES (1, 42, 9.99);
INSERT INTO customers (id, email) VALUES (42, 'ada@example.com');
COMMIT;SET CONSTRAINTS ALL DEFERRED affects only constraints declared DEFERRABLE; a default constraint still fails.
Case 2: The key looks right but the type differs
DETAIL: Key (customer_id)=(a1b2c3d4-...) is not present in table "customers".When the parent key is stored as text and the child column is uuid, the lookup casts, and a value with uppercase hex or surrounding whitespace does not equal the stored form:
SELECT id FROM customers WHERE id::text ILIKE 'a1b2c3d4%';
-- 0 rows: stored as 'A1B2C3D4-...'?Compare the two values with length() and encode(convert_to(id::text, 'UTF8'), 'hex') rather than by eye. The durable fix is to use one type on both sides; a text foreign key that holds UUIDs invites this class of bug forever.
Case 3: Deleting a parent that children still reference
DELETE FROM customers WHERE id = 42;
-- ERROR: update or delete on table "customers" violates foreign key constraint
-- "orders_customer_id_fkey" on table "orders"
-- DETAIL: Key (id)=(42) is still referenced from table "orders".The direction flips: now the parent delete is rejected. Choose the intended semantics instead of deleting children manually:
ALTER TABLE orders
DROP CONSTRAINT orders_customer_id_fkey,
ADD CONSTRAINT orders_customer_id_fkey
FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;TRUNCATE customers fails similarly and needs TRUNCATE customers, orders or CASCADE, which hits every dependent table.
Case 4: Adding a foreign key to a large existing table
ALTER TABLE ... ADD FOREIGN KEY locks both tables and validates every row, blocking writes. Split it:
ALTER TABLE orders
ADD CONSTRAINT orders_customer_id_fkey
FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
-- brief lock, no scan
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_fkey;
-- SHARE UPDATE EXCLUSIVE: reads and writes continueViolating rows must be fixed before VALIDATE. Find them first:
SELECT o.id, o.customer_id
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL
LIMIT 50;Case 5: Partitioned parent tables
A foreign key can reference a partitioned table from Postgres 12 onward, but the referenced columns must be covered by a unique constraint that includes the partition key. On older versions ADD CONSTRAINT fails outright; a missing unique index errors differently from a data violation. Check both:
SHOW server_version;
SELECT conname, contype FROM pg_constraint WHERE conrelid = 'customers'::regclass;Case 6: Concurrent delete and insert
ERROR: insert or update on table "orders" violates foreign key constraint
DETAIL: Key (customer_id)=(42) is not present in table "customers".Under READ COMMITTED, a transaction can see a parent row, then another session deletes it and commits before the child insert's FK check runs. The insert fails even though the SELECT succeeded. Handle 23503 as a retryable business error when the parent lifecycle is concurrent, or take a FOR KEY SHARE lock on the parent when the read must be stable:
SELECT id FROM customers WHERE id = 42 FOR KEY SHARE;FOR KEY SHARE blocks deletes and key updates without blocking ordinary column updates, which is exactly the lock the FK check itself uses.
Common Compilation/Runtime Mistakes & Version Gotchas
- Assuming the FK is checked at commit. Only
DEFERRABLE INITIALLY DEFERREDmoves the check. A plain constraint fails inside the statement, so the previous statement in the transaction is the one to inspect. ON DELETE CASCADEas a default reflex. It converts a blocked delete into silent mass deletion of history. Confirm the child table is genuinely owned by the parent.- Nullable column with
SET NULL. If the FK column isNOT NULL,ON DELETE SET NULLfails at delete time with a not-null violation that names a different constraint than the one you were thinking about. - Soft deletes and foreign keys.
deleted_atfiltering does not affect FK checks: a soft-deleted parent still satisfies the reference. Applications that expect a soft delete to block new children need a trigger or a partial unique index plus application logic. search_pathdifferences. An unqualified table name in a migration can resolve to a different schema than the one the FK references; qualify names in migrations.- Bulk loads.
COPYinto the child before the parent fails at the first bad row and aborts the whole load unless the client uses savepoints. Load parents first, or use a staging table without the constraint and validate afterwards.
When the parent and child records come from two systems, compare the exported key columns with the diff tool before writing the migration. For a reviewable join that finds orphan rows, format it with the SQL formatter, and inspect the constraint list with the SQL schema viewer.
Primary references: foreign key constraints documents the actions, deferrability and locking behavior, and Appendix A maps 23503 to its condition name.
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.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
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.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.