Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres: null value in column violates not-null constraint

A required column arrived empty. Read the failing row, send the value, add a default, or relax the constraint only if null is a real state.

~5 min readSQL
#PostgreSQL#SQL#Constraints#Errors
A Postgres row crate with an empty required slot rejected at a cyan not-null gate, an amber default card beside it

Introduction & Quick Summary

text
ERROR: null value in column "email" of relation "users" violates not-null constraint DETAIL: Failing row contains (42, null, Jane Doe, 2026-11-24 07:02:11+09). SQL state: 23502 (not_null_violation)

A row reached the table with a NULL in a column declared NOT NULL, and Postgres rejected the whole statement. Nothing was partially written: the insert or update failed atomically.

The DETAIL line is the useful part. It prints the failing row in column order, so you can see which value is missing and what else was sent. null in a position that should hold a value, or an unexpected trailing value, usually identifies the bug before you read any code.

Four causes cover nearly all cases:

  • The column is missing from the INSERT list and has no default.
  • The application sends an explicit null — a JavaScript undefined, a Python None, a partially populated DTO.
  • An UPDATE sets the column to null, often from a PATCH-style whole-row write.
  • Bulk load sends empty fields as null, for example COPY with empty strings.
CauseSignature in the logFix
Missing column, no defaultFailing row contains (42, null, ...)Add column or DEFAULT
Explicit null from appORM logs email: nullValidate before insert
UPDATE ... SET col = nullStatement in log_min_error_statementGuard the set list
COPY empty fieldMany rows, one error aborts loadNULL '' or FORCE_NULL
ALTER TABLE ... NOT NULLcolumn "x" contains null valuesBackfill first, then constrain

Core Mechanics, Signatures & Reproducible Setup

NOT NULL is a column constraint checked on every insert and on every update that touches the row. Its check happens after defaults and BEFORE triggers, so a trigger that clears a column can cause the violation even though the INSERT supplied a value. Generated columns cannot be null if their expression never yields null.

Reproduce it:

CREATE TABLE users ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL, name text, created_at timestamptz NOT NULL DEFAULT now() ); INSERT INTO users (name) VALUES ('Jane Doe'); -- ERROR: null value in column "email" of relation "users" -- violates not-null constraint -- DETAIL: Failing row contains (1, null, Jane Doe, 2026-11-24 07:02:11+09).

The statement aborted; id was consumed from the identity sequence, so the next successful insert gets 2. Identity and serial sequences are not rolled back, which is normal and visible in the gap.

The correct fixes, in order of preference:

-- 1. Send the value INSERT INTO users (email, name) VALUES ('jane@example.com', 'Jane Doe'); -- 2. Give the column a default so omission is valid ALTER TABLE users ALTER COLUMN email SET DEFAULT 'unset@example.invalid'; -- 3. Allow null only if "no email" is a real state ALTER TABLE users ALTER COLUMN email DROP NOT NULL;

Option 3 is a schema decision, not a bug fix. If the column is required by the domain, keep the constraint and fix the writer.

Key Comparison Table

ConstraintSQLSTATERejectsViolated by
NOT NULL23502NULLInsert/update without a value
CHECK23514Failed predicateValues that violate a rule
FOREIGN KEY23503Missing parentDangling references
UNIQUE23505Duplicate keyConcurrent inserts
EXCLUDE23P01Overlapping rangesBooking conflicts
StrategyData integrityMigration costUse when
NOT NULL + app validationStrongestLowRequired field
NOT NULL DEFAULTStrongLowSensible fallback exists
Nullable + CHECK on stateMediumLowOptional with rules
Nullable onlyWeakNoneGenuinely unknown value
Trigger fills valueStrongMediumDerived or inherited value

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: The column is simply absent from the statement

INSERT INTO users (name) VALUES ('Jane Doe');

Application code that builds the column list dynamically misses fields when a form is partially filled. Make the statement explicit and let the database enforce the rest:

python
columns = ("email", "name") values = ("jane@example.com", "Jane Doe") sql = f"INSERT INTO users ({', '.join(columns)}) VALUES ({', '.join(['%s'] * len(columns))})"

In an ORM, this appears as a model whose required property was never assigned. EF Core throws before the database, Hibernate sends null and gets 23502 — either way, validating at the boundary produces a 400 instead of a 500.

Case 2: undefined becoming null

javascript
const payload = { email: req.body.email, name: req.body.name }; // req.body.email is undefined for FormData or a JSON body without the key await db.query("INSERT INTO users (email, name) VALUES ($1, $2)", [payload.email, payload.name]); // email -> null -> 23502

pg converts undefined to null. Reject the request before it reaches the database:

javascript
if (typeof req.body.email !== "string" || req.body.email.length === 0) { return res.status(422).json({ error: "email required" }); }

An empty string is not null, so email = '' passes NOT NULL and fails every later CHECK. Add both constraints when the field must be meaningful:

ALTER TABLE users ADD CONSTRAINT users_email_not_blank CHECK (length(btrim(email)) > 0);

Case 3: A partial update that clears a required column

UPDATE users SET email = $1, name = $2 WHERE id = $3;

A PATCH endpoint that forwards every field of a JSON body sets email = NULL when the client omitted it. Build the statement from the keys that were actually sent:

javascript
const fields = Object.keys(body); // ["name"] const sets = fields.map((f, i) => `${f} = $${i + 2}`); await db.query(`UPDATE users SET ${sets.join(", ")} WHERE id = $1`, [id, ...fields.map((f) => body[f])]);

Only allow known column names — the same code path is a SQL injection vector if fields comes from the request unchecked.

Case 4: Bulk copy with empty fields

bash
psql -c "\copy users (email, name) FROM 'users.csv' WITH (FORMAT csv)"

An empty field in a CSV is read as an empty string, not null — unless the loader treats it as null. COPY has both directions:

sql
COPY users (email, name) FROM STDIN WITH (FORMAT csv, NULL '', FORCE_NULL (email));

NULL '' declares the null marker; FORCE_NULL converts an empty quoted field to null. Without either, an empty field becomes '', which passes NOT NULL and can still break downstream logic, so know which behavior you want.

Case 5: Adding a NOT NULL column to a live table

ALTER TABLE users ADD COLUMN plan text NOT NULL; -- ERROR: column "plan" of relation "users" contains null values

Existing rows have no value. Since Postgres 11, adding a column with a non-volatile default is a metadata-only operation:

ALTER TABLE users ADD COLUMN plan text NOT NULL DEFAULT 'free';

If the default must later be dropped, do it in a second statement after the backfill is verified:

ALTER TABLE users ALTER COLUMN plan DROP DEFAULT;

For a value that depends on existing rows, backfill in batches and add the constraint with NOT VALID where the type allows it — CHECK supports NOT VALID, NOT NULL does not, so use CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT after the backfill.

Case 6: A trigger that nulls the value

sql
CREATE FUNCTION scrub_email() RETURNS trigger AS $$ BEGIN IF NEW.email LIKE '%@example.invalid' THEN NEW.email := NULL; -- violates NOT NULL on the same row END IF; RETURN NEW; END $$ LANGUAGE plpgsql;

The INSERT supplied a value and still fails, which is confusing in application logs. BEFORE triggers run before constraint checks, so the failing row in DETAIL shows null while the query text shows the original value. Check pg_trigger before blaming the client:

SELECT tgname, tgrelid::regclass FROM pg_trigger WHERE NOT tgisinternal;

Common Compilation/Runtime Mistakes & Version Gotchas

  • Catching 23502 and retrying. The same data fails identically; retries only add load. Map it to a validation error instead.
  • Reading DETAIL as column names. It is positional, in table column order; ALTER TABLE ... ADD COLUMN shifts positions and the log can be read wrong.
  • Empty string versus null. NOT NULL permits ''. A second CHECK constraint is what makes a field meaningful.
  • ON CONFLICT DO NOTHING hides the problem. It handles unique violations, not not-null ones; the statement still fails with 23502.
  • Identity gaps. Failed inserts consume sequence values, so id jumps; that is expected and not evidence of a second bug.
  • Partitioned tables. A NOT NULL constraint on the parent applies to partitions, but constraints added directly on a partition can differ; check pg_constraint when one partition rejects rows another accepts.
  • ORM defaults that never reach SQL. A Python Optional[str] = None or a TypeScript string type does not create a database default; only server_default / DEFAULT does.

Use the SQL formatter to rewrite the failing insert with every column explicit, and inspect the table's constraints with the schema designer before deciding between a default and a schema change. If the row arrives as JSON, the JSON formatter shows the missing key clearly.

Primary references: Constraints — Not-Null Constraints explains when the check runs, and COPY documents NULL and FORCE_NULL handling.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.