PostgreSQL Error 23502: Not Null Violation

PostgreSQL error 23502 (Not Null Violation) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

SQLSTATE 23502 PostgreSQL Last verified 2026-08-19

Quick Answer

Read the error for the exact column that received NULL. If that does not apply, provide an explicit non-null value in the INSERT or fix the application mapping — the full checklist is below.

Error Code

SQLSTATE: 23502
Official name: Not Null Violation
Service: PostgreSQL

What does this error mean?

A NOT NULL constraint was violated by inserting or updating a column with a NULL value.

Common Causes

How to Fix

  1. Read the error for the exact column that received NULL
  2. Provide an explicit non-null value in the INSERT or fix the application mapping
  3. Add a DEFAULT or use COALESCE in an UPDATE if nulls can legitimately arrive
  4. Backfill existing NULLs before adding a NOT NULL constraint via migration

Code Examples

Backfill then add NOT NULL sql
UPDATE users SET email = 'unknown@example.com' WHERE email IS NULL;
ALTER TABLE users ALTER COLUMN email SET NOT NULL;

Never add NOT NULL to a column containing NULLs; backfill first or the constraint fails for existing rows.

Framework-Specific Fixes

prisma

Mark fields as required (non-optional) in schema.prisma; the client will type-check before sending NULL.

model User {
  id    Int    @id @default(autoincrement())
  email String // required, cannot be null
}
django

Use null=False with a default, or validate in clean() before save().

class MyModel(models.Model):
    email = models.EmailField(null=False, default='')
sqlalchemy

Declare nullable=False on the column; the ORM rejects None before reaching the DB.

class User(Base):
    __tablename__ = 'users'
    email = Column(String, nullable=False)

You Might Also Like

Frequently Asked Questions

Why am I seeing PostgreSQL error 23502?

Most often this happens when omitting a required column in an INSERT statement, or when passing NULL/undefined from the application for a NOT NULL column.

How do I fix PostgreSQL error 23502?

Read the error for the exact column that received NULL.

Which frameworks have documented fixes for error 23502?

This page documents fixes for: prisma, django, sqlalchemy.

Official Sources

This page is based on the official PostgreSQL documentation linked below and adds practical troubleshooting guidance on top.