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:
- Provide a value for the column, or add a sensible
DEFAULT. - If NULL is legitimately valid, relax the column:
ALTER TABLE t ALTER COLUMN c DROP NOT NULL;. - Backfill missing data before re-running the write.
- Identify the column from the error detail and trace the source value.
Reference: PostgreSQL error codes — Class 23 (Integrity Constraint Violation).
Thanks — noted. This helps keep the database accurate.