DBAtlas · Database operations atlas

23503: foreign_key_violation

PostgreSQL

What does it mean?

A FOREIGN KEY constraint was violated. The parent row referenced by the inserted/updated row does not exist, or the parent row being deleted still has dependent child rows.

Why does it happen?

An INSERT/UPDATE referencing a non-existent parent key, an attempt to delete/update a parent row that is still referenced, or data loaded in the wrong order (child first, then parent).

How to fix it

Insert the parent row first, then the child row. If cascading behavior is needed on delete, define the constraint with ON DELETE CASCADE or ON DELETE SET NULL. In bulk loads, load data in parent-child order. Find the referencing rows: SELECT * FROM child WHERE fk_column = value.

Open in DBAtlas →

More from this engine