PostgreSQL error: violates foreign key constraint

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".

-- direzione opposta:
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".

A foreign key failed in one of its two directions: a child row points at a parent that is not there, or a parent row is being removed while children still reference it. The wording tells you which — "is not present in" versus "is still referenced from" — and the DETAIL names the exact key value.

What this error means

A foreign key is a promise checked at both ends:

Common causes

How to diagnose it

The DETAIL gives you the constraint name, the key value, and both table names. From there:

-- Il vincolo, per esteso:
\d orders

-- Orfani già presenti (per capire l'ampiezza del problema nei load):
SELECT o.*
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL;

How to fix it

🔍 Related reading: Choosing the right index — PostgreSQL does not automatically index the referencing side of a foreign key; deletes on the parent scan the child without one.