PostgreSQL Error 22004: Null Value Not Allowed Fix
In this article
PostgreSQL error 22004 (null_value_not_allowed) means a function or operation received a NULL where NULL is explicitly forbidden—not merely a column that allows NULLs, but a context that requires a non-null value. The fix is to find which expression produced the NULL and either prevent it (with COALESCE, a default, or a WHERE filter) or change the schema/function so NULL is acceptable. You do not need to restart the server; this is a query or data issue.
What You'll Need
- Access to a PostgreSQL client (psql, pgAdmin, DBeaver, or your application's SQL console) with permission to read the relevant tables and function definitions.
- The full error message and the SQL statement that triggered it—PostgreSQL usually includes the function name or the failing expression in the DETAIL or CONTEXT line.
- Basic familiarity with SELECT, UPDATE, and function calls.
Step-by-Step
- Read the entire error output, not just the first line. A typical message looks like:
ERROR: null value not allowed SQL state: 22004followed byCONTEXT: PL/pgSQL function my_func() line 5 at assignmentorDETAIL: .... The CONTEXT line names the function or the exact SQL fragment. If you only see the SQLSTATE, enable verbose error reporting in your client or check the server log—the log records the statement and context. - Identify the expression that returned NULL. Common sources: a column that is actually NULL for some rows, a subquery with no matching row, a LEFT JOIN where the right side is missing, a function like
NULLIForarray_positionthat returns NULL, or a PL/pgSQL variable that was never assigned. Run the SELECT part of your statement withWHERE column IS NULLto confirm which rows are affected. - Decide whether NULL is legitimate for your data. If the business rule says the value must always exist, fix the data and add a constraint. If NULL is acceptable, change the function or query to handle it. Do not blindly replace NULL with a dummy value—that hides data quality problems.
- For queries, wrap the expression with COALESCE or filter NULLs. Example:
SELECT COALESCE(amount, 0) FROM invoices;orSELECT ... WHERE amount IS NOT NULL;. For string concatenation, useCOALESCE(name, '')becauseNULL || 'x'yields NULL. - For PL/pgSQL functions, initialize variables and guard assignments. Declare variables with a default:
v_total numeric := 0;. Before assigning from a query, useSELECT ... INTO STRICTonly when you expect exactly one row; otherwise handleNO_DATA_FOUND. If a function parameter is declaredSTRICT, calling it with NULL raises 22004—remove STRICT or ensure callers pass non-null values. - For INSERT/UPDATE, supply defaults or add NOT NULL constraints carefully. If a column is NOT NULL and you insert NULL, PostgreSQL raises 23502 (not_null_violation), not 22004—so 22004 usually points to a function or cast, not a plain column constraint. Check casts:
NULL::integeris fine, but some domain types andCAST(NULL AS domain_with_not_null)can raise 22004. - Test the fix on a copy of the data or inside a transaction. Run
BEGIN; ... ROLLBACK;to verify without committing. Confirm the statement returns rows and no error, then commit. - Add a regression check. If the error came from application code, add a test that passes NULL to the same function or query so the handling is verified. For database-side logic, consider a CHECK constraint or a trigger that rejects NULL early with a clearer message.
Common Mistakes
- Confusing 22004 with 23502. 23502 is a NOT NULL column violation; 22004 is a null value passed to a context that forbids it (strict functions, certain domains, array operations). Fixing the wrong one wastes time.
- Using
= NULLinstead ofIS NULL.WHERE col = NULLnever matches; it returns no rows and can make you think data is missing. - Replacing NULL with 0 or empty string everywhere. This can corrupt reports and hide missing data. Prefer filtering or explicit defaults only where the business rule allows.
- Ignoring the CONTEXT line. The function name and line number usually point directly to the failing assignment; skipping it leads to guessing.
- Assuming the error is in the client. 22004 is raised by the server; the client only displays it. Check server logs if the client output is truncated.
Tips
- Use
psqlwith\set VERBOSITY verboseto see the full error detail and context. - For array functions, note that
array_positionreturns NULL when the element is not found—wrap it with COALESCE if you need a sentinel. - When writing PL/pgSQL, prefer
SELECT ... INTOwith an explicitIF NOT FOUNDcheck rather than relying on STRICT. - Document which functions are STRICT; callers must never pass NULL to them.
- Keep a small test script that runs your critical functions with NULL inputs to catch regressions early.
Troubleshooting
If the error persists after adding COALESCE, check whether the NULL is coming from a different layer: a view, a trigger, or a function called inside your statement. Run EXPLAIN (VERBOSE, ANALYZE) on the query to see the actual expressions evaluated. If the error appears only in production, compare the data: run the same query with WHERE ... IS NULL on both environments to find the offending rows. If you cannot modify the function, wrap the call in a CASE expression that returns a safe value when the input is NULL. If the error comes from a domain type with a NOT NULL constraint, either relax the domain or ensure the cast receives a non-null value. Finally, check that your client is not silently converting empty strings to NULL—some drivers do this depending on settings.
Frequently Asked Questions
What does SQLSTATE 22004 mean exactly?
It is the null_value_not_allowed condition: a NULL was supplied where the SQL standard or PostgreSQL requires a non-null value, such as a strict function argument or a domain with NOT NULL.
Is 22004 the same as a NOT NULL constraint violation?
No. A NOT NULL column violation is 23502. 22004 comes from functions, domains, or operations that reject NULL, not from a plain column constraint.
Can I fix 22004 without changing code?
Sometimes—if the NULL comes from data, updating the rows to non-null values may resolve it. Otherwise you must change the query or function to handle NULL.
Why does my function raise 22004 only for some rows?
Because only those rows produce NULL for the expression passed to the strict function or domain. Use IS NULL filters to find them.
Does COALESCE always fix 22004?
Only when the NULL is the direct cause. If the error comes from a strict function receiving NULL, COALESCE around the argument works. If it comes from a domain cast, you may need to adjust the domain or the cast.
Where can I see the full error context?
In psql set VERBOSITY verbose; in other clients check the server log, which records the statement, function, and line number.