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.

Introduction & Quick Summary
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
INSERTlist and has no default. - The application sends an explicit
null— a JavaScriptundefined, a PythonNone, a partially populated DTO. - An
UPDATEsets the column tonull, often from a PATCH-style whole-row write. - Bulk load sends empty fields as null, for example
COPYwith empty strings.
| Cause | Signature in the log | Fix |
|---|---|---|
| Missing column, no default | Failing row contains (42, null, ...) | Add column or DEFAULT |
| Explicit null from app | ORM logs email: null | Validate before insert |
UPDATE ... SET col = null | Statement in log_min_error_statement | Guard the set list |
COPY empty field | Many rows, one error aborts load | NULL '' or FORCE_NULL |
ALTER TABLE ... NOT NULL | column "x" contains null values | Backfill 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
| Constraint | SQLSTATE | Rejects | Violated by |
|---|---|---|---|
NOT NULL | 23502 | NULL | Insert/update without a value |
CHECK | 23514 | Failed predicate | Values that violate a rule |
FOREIGN KEY | 23503 | Missing parent | Dangling references |
UNIQUE | 23505 | Duplicate key | Concurrent inserts |
EXCLUDE | 23P01 | Overlapping ranges | Booking conflicts |
| Strategy | Data integrity | Migration cost | Use when |
|---|---|---|---|
NOT NULL + app validation | Strongest | Low | Required field |
NOT NULL DEFAULT | Strong | Low | Sensible fallback exists |
Nullable + CHECK on state | Medium | Low | Optional with rules |
| Nullable only | Weak | None | Genuinely unknown value |
| Trigger fills value | Strong | Medium | Derived 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:
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
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 -> 23502pg converts undefined to null. Reject the request before it reaches the database:
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:
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
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:
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 valuesExisting 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
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
DETAILas column names. It is positional, in table column order;ALTER TABLE ... ADD COLUMNshifts positions and the log can be read wrong. - Empty string versus null.
NOT NULLpermits''. A secondCHECKconstraint is what makes a field meaningful. ON CONFLICT DO NOTHINGhides the problem. It handles unique violations, not not-null ones; the statement still fails with 23502.- Identity gaps. Failed inserts consume sequence values, so
idjumps; that is expected and not evidence of a second bug. - Partitioned tables. A
NOT NULLconstraint on the parent applies to partitions, but constraints added directly on a partition can differ; checkpg_constraintwhen one partition rejects rows another accepts. - ORM defaults that never reach SQL. A Python
Optional[str] = Noneor a TypeScriptstringtype does not create a database default; onlyserver_default/DEFAULTdoes.
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 documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
pg_dump: server version mismatch, aborting because of server version
pg_dump refuses to read a newer server. Install a matching client, run it from a container or the server host, and match pg_restore too.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.