SQLSTATE P0004 ERROR Class P0: PL/pgSQL Error

assert_failure assertion failed — P0004

PostgreSQL error "assertion failed" (SQLSTATE P0004): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

Diagnostic Queries

Symptoms

A PL/pgSQL ASSERT statement evaluated to false (or null). PostgreSQL raises SQLSTATE P0004 (assert_failure).

  • An ASSERT condition in a function did not hold.
  • Indicates an internal invariant was violated.
  • Assertions are enabled by plpgsql.check_asserts.

What the server log shows

ERROR:  assertion failed
CONTEXT:  PL/pgSQL function recompute_totals() line 8 at ASSERT

Why PostgreSQL raises this — what the manual says

Section 41.9.1 Checking Assertions:

“If the result is false or null, then an ASSERT_FAILURE exception is raised.”

ASSERT condition verifies an invariant during development/testing. When the condition is false or null and assertions are enabled, PostgreSQL raises P0004 to flag the broken assumption.

Common causes

  • An invariant assumed by the function did not hold at runtime.
  • A logic bug producing unexpected intermediate state.
  • Assertions left enabled in an environment hitting an edge case.

How to fix it

  1. Read the CONTEXT to locate the ASSERT and investigate why the invariant failed.
  2. Fix the underlying logic/data that violated the assumption.
  3. Disable assertions in production with plpgsql.check_asserts = off if appropriate.

Related & next steps

Reference: PostgreSQL 18 Section 43.9.5 “Checking Assertions”.

Was this helpful?