SQLSTATE 23503 ERROR Class 23: Integrity Constraint Violation

foreign_key_violation Foreign Key Violation — SQLSTATE 23503

A row references a parent key that does not exist, or a referenced parent is being deleted while children remain.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

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:

  1. Insert and commit the parent row before the child, or load tables in dependency order.
  2. Use ON DELETE CASCADE or ON DELETE SET NULL when cascading is intended.
  3. Confirm the referenced key exists by querying the parent table.
  4. 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).

Was this helpful?