SQLSTATE 23502 ERROR Class 23: Integrity Constraint Violation

not_null_violation Not Null Violation — SQLSTATE 23502

A NULL was written to a column defined NOT NULL.

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

Symptoms

A NULL was written to a column defined NOT NULL.

  • The error is written to the server log and returned to the client carrying SQLSTATE 23502.
  • 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 not_null_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

An INSERT or UPDATE left a NOT NULL column without a value.

Common causes:

  • The column was omitted from an INSERT and has no DEFAULT.
  • An explicit NULL was supplied.
  • A default expression failed to produce a value.
  • An ETL/source gap left the field empty.

Diagnostic Queries

Recovery

Steps to resolve 23502:

  1. Provide a value for the column, or add a sensible DEFAULT.
  2. If NULL is legitimately valid, relax the column: ALTER TABLE t ALTER COLUMN c DROP NOT NULL;.
  3. Backfill missing data before re-running the write.
  4. Identify the column from the error detail and trace the source value.

Reference: PostgreSQL error codes — Class 23 (Integrity Constraint Violation).

Was this helpful?