Incident Response

PostgreSQL: insert or update on table violates foreign key constraint

A child row points at a parent that does not exist, or a parent is deleted while children still point at it. How to read the DETAIL line, fix the order of writes and add foreign keys to large tables safely.

· 13 min read · AG Data Team

PostgreSQL "insert or update on table violates foreign key constraint" means a row in a child table references a key that the parent table does not have. The mirror error, "update or delete on table ... violates foreign key constraint", means you tried to remove or change a parent key that child rows still point at.

ERROR:  insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL:  Key (customer_id)=(4217) is not present in table "customers".

ERROR:  update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL:  Key (id)=(4217) is still referenced from table "orders".

Both carry SQLSTATE 23503, foreign_key_violation, in the error codes appendix. The DETAIL line is the useful part: it names the key columns and the exact value. If the constraint was declared ON DELETE RESTRICT, the delete side reports "violates RESTRICT setting of foreign key constraint" with SQLSTATE 23001 instead. One quirk worth knowing: PostgreSQL leaves the values out of DETAIL ("Key is not present in table ...") when row-level security is enabled on the table or your role cannot read the key columns, so the same error can look less informative in production than in development.

Why the parent row is "not present"

In our experience the value in DETAIL is almost never a mystery once you look at how it was written. The usual causes:

A NULL in the referencing column does not trigger the error. With the default MATCH SIMPLE a row escapes the check if any referencing column is null; MATCH FULL rejects a mix of null and non-null values, as the constraints chapter explains. Declare the column NOT NULL if every child must have a parent.

How to diagnose it

Start from the constraint name in the message, then check the parent key directly:

-- what exactly does the constraint connect?
SELECT conrelid::regclass  AS child_table,
       confrelid::regclass AS parent_table,
       pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conname = 'orders_customer_id_fkey';

-- does the parent row exist (as committed data)?
SELECT id FROM customers WHERE id = 4217;

If the parent row is there when you look, the error was a timing problem: the parent was committed after the child insert, or deleted and re-created. If it is not there, the bug is in the data or in the code that produced the id.

How to fix it

  1. Write parents first, in the same transaction. That removes both the ordering and the visibility race.
  2. Use deferrable constraints for cycles. When two tables reference each other, or a loader cannot control order, declare the foreign key DEFERRABLE and use SET CONSTRAINTS to check it at commit. Per the CREATE TABLE reference, NOT DEFERRABLE is the default.
  3. Decide what deleting a parent should do. The default is NO ACTION, which raises the error, but can be deferred. RESTRICT cannot be deferred. CASCADE deletes the children, SET NULL and SET DEFAULT rewrite them. Pick deliberately: CASCADE on the wrong table turns one delete into thousands.
  4. Handle it in the application when a missing parent is a normal case, for example a stale id from a client. Catch SQLSTATE 23503 and return a clear validation error instead of a 500.
BEGIN;
INSERT INTO customers (id, name) VALUES (4217, 'Acme SIA');
INSERT INTO orders (customer_id, total) VALUES (4217, 99.00);
COMMIT;

-- circular references: make the constraint deferrable
ALTER TABLE orders
  ALTER CONSTRAINT orders_customer_id_fkey DEFERRABLE INITIALLY IMMEDIATE;

BEGIN;
SET CONSTRAINTS orders_customer_id_fkey DEFERRED;
-- rows can arrive in any order here; checked at COMMIT
COMMIT;

The pattern is similar to handling unique violations, covered in our article on duplicate key value violates unique constraint: the database is right, and the fix is in the order or the content of the writes.

Do not switch the check off. Foreign keys are enforced by internal triggers. Setting session_replication_role to replica stops triggers from firing, and pg_restore --disable-triggers does the same during a data-only restore; both need superuser rights (or, for the setting, an explicitly granted SET privilege) and both let orphaned rows in without any error. PostgreSQL 18 also allows a foreign key to be declared NOT ENFORCED, which means the database no longer checks it at all and the application is responsible. These tools have legitimate uses in replication and restores, but as a fix for 23503 they only move the problem to the next VALIDATE or the next report that joins the tables.

Foreign keys on large tables

At scale the errors are the easy part. The costs sit in locks, scans and memory:

-- 1. index the referencing column (not created automatically)
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);

-- 2. add the constraint without scanning existing rows
ALTER TABLE orders
  ADD CONSTRAINT orders_customer_id_fkey
  FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;

-- 3. find orphans that would make validation fail
SELECT o.id, o.customer_id
FROM orders o
WHERE o.customer_id IS NOT NULL
  AND NOT EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id)
LIMIT 100;

-- 4. once orphans are fixed: scan without blocking writes
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_fkey;

This two-step approach is part of a wider set of techniques in our guide to zero-downtime PostgreSQL migrations.

Key takeaways

PostgreSQL Errors Constraints Schema changes
Work with us

Foreign key errors after a migration or a data load?

We find orphaned rows, fix load order and add or validate foreign keys on large PostgreSQL tables without locking out production traffic.

Get in touch More from the blog