Symptoms
A row references a parent key that does not exist, or a referenced parent is being deleted while children remain.
- The error is written to the server log and returned to the client carrying
SQLSTATE 23503. - Any driver (libpq, JDBC, psycopg, npgsql, pgx) surfaces this code in its error object so you can branch on it programmatically.
- PL/pgSQL can trap it by name:
EXCEPTION WHEN foreign_key_violation THEN.
Environment
Severity: ERROR | PostgreSQL versions: 12, 13, 14, 15, 16, 17
Reproduce with the exact statement and read the full message in the server log (raise log_min_messages / set log_min_error_statement for more context).
Root Cause
A FOREIGN KEY was not satisfied — on INSERT/UPDATE the parent key is missing, or on DELETE/UPDATE of the parent there are still child rows.
Common causes:
- Inserting a child before its parent.
- Deleting a parent that still has children.
- A wrong or stale key value.
- Loading tables in the wrong dependency order.
Diagnostic Queries
Recovery
Steps to resolve 23503:
- Insert and commit the parent row before the child, or load tables in dependency order.
- Use
ON DELETE CASCADEorON DELETE SET NULLwhen cascading is intended. - Confirm the referenced key exists by querying the parent table.
- For bulk loads with a DEFERRABLE FK, defer checks:
SET CONSTRAINTS ALL DEFERRED;inside the transaction.
Reference: PostgreSQL error codes — Class 23 (Integrity Constraint Violation).
Thanks — noted. This helps keep the database accurate.