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:
- Wrong write order. The child is inserted before the parent, often in ETL jobs, data imports or ORM code that flushes objects in an unexpected order.
- The parent is not committed yet. A row inserted by another transaction is not visible until that transaction commits. Two services, or two connections from one pool, can race this way: one writes the customer, the other writes the order a moment too early.
- The parent was deleted. A cleanup job or a user removed it between the read and the write.
- The id belongs to another environment. Ids copied from production into staging, or a sequence reset after a restore, point at rows that do not exist here.
- Data-only restores. Loading table data into a schema that already has foreign keys fails when a child table is loaded before its parent.
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
- Write parents first, in the same transaction. That removes both the ordering and the visibility race.
- Use deferrable constraints for cycles. When two tables reference each other, or a loader cannot control order, declare the foreign key
DEFERRABLEand use SET CONSTRAINTS to check it at commit. Per the CREATE TABLE reference,NOT DEFERRABLEis the default. - Decide what deleting a parent should do. The default is
NO ACTION, which raises the error, but can be deferred.RESTRICTcannot be deferred.CASCADEdeletes the children,SET NULLandSET DEFAULTrewrite them. Pick deliberately:CASCADEon the wrong table turns one delete into thousands. - Handle it in the application when a missing parent is a normal case, for example a stale id from a client. Catch SQLSTATE
23503and 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:
- Adding a foreign key scans the whole child table. According to the ALTER TABLE reference,
ADD FOREIGN KEYtakes aSHARE ROW EXCLUSIVElock on both the child and the referenced table, and other updates are locked out until the command commits. On a table with hundreds of millions of rows that can be a long outage. - Use NOT VALID, then VALIDATE.
NOT VALIDskips the scan, and new writes are checked straight away.VALIDATE CONSTRAINTlater scans existing rows under aSHARE UPDATE EXCLUSIVElock, which does not block normal reads and writes. - Find orphans before validating. Validation stops at the first bad row, possibly after a long scan. Run the anti-join on a replica or in key ranges first and fix or archive what it finds.
- Index the referencing column. PostgreSQL does not create it. Without it, every delete or key update on the parent scans the child table, which is how a small cleanup job on
customersends up reading all oforders. - Bulk loads and the trigger queue. Each row loaded into a table with foreign keys adds an entry to the pending trigger event list. The Populating a Database chapter warns that millions of rows can exhaust memory, and recommends dropping and re-creating foreign keys for very large loads.
- Locks on hot parent rows. The check takes a
FOR KEY SHARElock on the parent row. Per the locking documentation, that blocks deleting the parent or changing its key until the child transaction ends, so long child transactions can stall parent maintenance. - Cascading deletes in one statement.
ON DELETE CASCADEon big child tables turns one delete into a huge transaction. In our experience deleting children in batches first, then the parent, keeps WAL volume and replica lag under control.
-- 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
- SQLSTATE 23503 means a child row references a missing parent key, or a parent key is removed while children still reference it. Read the
DETAILline for the exact value. - Most cases are write order, an uncommitted parent in another transaction, or ids from another environment.
- Write parents first in one transaction, use
DEFERRABLEconstraints for cycles, and chooseON DELETEactions on purpose. - Disabling triggers or using
NOT ENFORCEDhides the error and leaves orphaned rows. - On large tables add foreign keys as
NOT VALID, clean orphans, thenVALIDATE CONSTRAINT, and always index the referencing columns.