How to Fix Postgres Error 22004 Null Value Not Allowed

Published
Length
3 min read

Luis Felipe Dias

All posts

The postgres error 22004 null value not allowed happens when a function or expression receives an illegal null input. You fix it by filtering out null values or providing a fallback default before the operation runs. This failure belongs to the data exception class in the database engine. The engine uses the internal macro ERRCODE_NULL_VALUE_NOT_ALLOWED to stop the query right away. Stopping the query prevents corrupt records from entering your tables. Teams see this error during data imports,

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

The postgres error 22004 null value not allowed happens when a function or expression receives an illegal null input. You fix it by filtering out null values or providing a fallback default before the operation runs.

This failure belongs to the data exception class in the database engine. The engine uses the internal macro ERRCODE_NULL_VALUE_NOT_ALLOWED to stop the query right away. Stopping the query prevents corrupt records from entering your tables. Teams see this error during data imports, JSON processing, or custom function calls.

What causes postgres error 22004 null value not allowed

Database engines enforce strict rules on how functions handle missing values. Many built-in functions and procedural routines expect a real value to work. When a query passes a null value into those places, the engine raises sqlstate 22004.

Note that this code differs from a standard table column constraint violation. A missing value in a required table column triggers a different integrity code. Code 22004 points to data expressions, procedural variables, or array and document builders. For example, passing a null key into a document builder fails right away.

Custom functions also trigger this error when they reject null inputs. If a routine sets a variable marked as not null, a missing value stops execution. Outer joins often create unexpected nulls when rows do not match across tables. If your query feeds those joined columns into a strict function, the query fails.

How to diagnose and fix the error in production

Start by reading the server log to find the exact query that failed. The log message shows the line number or function name that rejected the null input. Once you find the query, inspect all column and variable passed into that step.

To check the source rows safely, use a read-only role with limited privileges. In PostgreSQL, the SELECT privilege lets a role read specific columns of a table or view. Granting read rights only on the suspect columns keeps sensitive fields safe during debugging. If those columns hold emails or phone numbers, masking rewrites matched fields in results.

End-to-End Encryption: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Check the source tables for missing values in the columns used by your query. Run a simple count query to see how many rows contain null data. Look closely at left joins or subqueries that return empty results for certain keys. An empty subquery result turns into a null value inside the main query.

Fix the query by wrapping suspect inputs in a fallback expression before calling the function. A fallback expression replaces any null value with a safe default value. You can also add a filter clause to skip rows with missing data.

Never fix this failure by granting broad superuser rights or dropping safety checks. Also check who can run functions in your database. By default, the special role PUBLIC gets rights to run new functions and procedures. The object owner can revoke these defaults so only approved group roles run data routines.

How to prevent null data exceptions in your app

Good input validation in your app stops bad data before it reaches the database. Check every payload in your app code to make sure required fields exist. When a user leaves an optional field blank, send a clear default value instead.

Test your database functions with missing values in a staging setup before shipping changes. Write unit tests that pass empty results and unmatched join rows into your queries. Catching a null exception during testing saves your team from middle-of-the-night alerts.

Add query and result controls beside Postgres

Grants and pools govern who logs into PostgreSQL. Yet every query in an open session still runs with that role's full scope. In practice, hoop.dev sits inline in the wire protocol beside your database as a sidecar for your Postgres. For every plain or prepared query an agent or human runs against production, hoop.dev decides to pass, mask, block, or escalate it for review.

When a tool or agent sends SQL, hoop.dev Postgres controls block banned statements before execution or hold risky ones for human approval via an AI Analyzer you configure. Matched sensitive columns in result rows are masked in memory before they reach the caller. Each query and decision is logged per listener, which generates evidence for SOC 2, HIPAA, and GDPR audits. View the binary on GitHub.

Frequently asked questions

How is sqlstate 22004 different from a not null constraint error?

Sqlstate 22004 happens inside data expressions, functions, or procedural variables that forbid null inputs. A table column not null constraint violation uses sqlstate 23502 instead.

Can a left join cause postgres error 22004 null value not allowed?

Yes, a left join returns null values for columns when the right table has no match. Passing those unmatched columns into a strict function triggers error 22004.

How can developers inspect rows causing error 22004 without broad database privileges?

Admins can grant the SELECT privilege on specific columns to a group role for debugging. This lets developers check for null values in target columns without reading the whole table.

The query runs. The emails stay hidden.