Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readSQL
#PostgreSQL#Foreign Keys#Constraints#Data Integrity
A Postgres child row crate pointing at an empty cyan parent slot, an amber 23503 plate and a lock gate

Introduction & Quick Summary

text
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 int that overflowed into a different value.
  • Deletion or truncation. A parent was removed while children still referenced it, or TRUNCATE customers ran without CASCADE.
  • Deferred checking. A DEFERRABLE INITIALLY DEFERRED constraint reports the violation at COMMIT, far from the failing statement.
Constraint actionParent deleteParent updateChild orphan
NO ACTIONFails at end of statementFailsPrevented
RESTRICTFails immediatelyFailsPrevented
CASCADEDeletes childrenUpdates childrenAllowed by design
SET NULLNulls the columnNulls the columnColumn must be nullable
SET DEFAULTSets default valueSets default valueDefault 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 here

Find 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

SQLSTATEConditionMessage shape
23503Foreign key violationinsert or update on table ... violates foreign key
23502Not null violationnull value in column ... violates not-null
23505Unique violationduplicate key value violates unique constraint
23514Check violationnew row for relation ... violates check constraint
42P01Undefined tablerelation ... does not exist
FixWhenTrade-off
Insert parent firstNormal application flowRequires ordering logic
ON CONFLICT DO NOTHING on parentIdempotent seed or APIHides conflicting data
DEFERRABLE INITIALLY DEFERREDCyclic referencesErrors move to commit
ON DELETE CASCADEChildren are ownedDeleting a parent removes history
ON DELETE SET NULLChild may outlive parentColumn must be nullable
NOT VALID then VALIDATELarge existing tableTwo-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

text
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 continue

Violating 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

text
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 DEFERRED moves the check. A plain constraint fails inside the statement, so the previous statement in the transaction is the one to inspect.
  • ON DELETE CASCADE as 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 is NOT NULL, ON DELETE SET NULL fails 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_at filtering 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_path differences. 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. COPY into 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 documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.