FluentDBFluentDB
PostgreSQL errors

PostgreSQL: null value violates not-null constraint

ERRORSQLSTATE 23502not_null_violation
ERROR: null value in column "<col>" of relation "<t>" violates not-null constraint

A column marked NOT NULL received a null on insert or update. Either the write left it out, there is no default to fill it, or you are adding NOT NULL to a column that still holds nulls. Supply the value, add a DEFAULT, or backfill first.

What this error means

A NOT NULL constraint requires every row to have a value in that column. When a write would leave it null, Postgres rejects the row and prints the failing row in the DETAIL line.

It also appears at migration time: running ALTER TABLE ... SET NOT NULL fails if existing rows already contain nulls in that column.

How to fix it

01

The insert or update omits the column

Provide a value for it in the statement.

sql
INSERT INTO users (email, name) VALUES ('a@example.com', 'Ada');
02

The column should fill itself

Give the column a DEFAULT so writes that omit it still get a value.

sql
ALTER TABLE users ALTER COLUMN created_at SET DEFAULT now();
03

You are adding NOT NULL to a column with existing nulls

Backfill the nulls to a sensible value, then add the constraint.

sql
UPDATE users SET name = 'unknown' WHERE name IS NULL;
ALTER TABLE users ALTER COLUMN name SET NOT NULL;

How to avoid it next time

  • Give required columns a DEFAULT where a sensible one exists, so callers cannot forget them.
  • When tightening a column to NOT NULL, always backfill first in the same migration.
Varies by version

Before Postgres 9.5 the message omitted the table: null value in column "col" violates not-null constraint, without of relation "t".

Frequently asked questions

How do I find which rows are null before adding the constraint?

Query the column directly: SELECT count(*) FROM t WHERE col IS NULL; Backfill those rows, then set NOT NULL.

Should the column be nullable instead?

If null is a legitimate value for that data, drop the NOT NULL constraint rather than inventing a placeholder value.

Stop struggling with SQL

Use FluentDB, the AI database client for macOS.