P0004
PostgreSQLERRORNotablePL/pgSQL ErrorHIGH confidence

assert_failure

What this means

A PL/pgSQL ASSERT statement evaluated its condition as false, causing the function to abort. Used for invariant checking and developer assertions in PL/pgSQL code.

Why it happens
  1. 1ASSERT condition evaluated to false or NULL
  2. 2Invariant assumed by the developer is violated by actual data or state
  3. 3ASSERT used as a debugging tool and left in production code with an edge case not anticipated
How to reproduce

PL/pgSQL function or DO block containing an ASSERT statement whose condition fails

trigger — this will error
trigger — this will error
DO $
DECLARE
  total int;
BEGIN
  SELECT count(*) INTO total FROM orders;
  ASSERT total > 0, 'orders table must not be empty';
END;
$;

expected output

ERROR:  P0004: orders table must not be empty

Fix 1

Fix the condition that caused the assertion to fail

WHEN The assertion represents a genuine invariant that is now violated

Fix the condition that caused the assertion to fail
-- Investigate and correct the data or logic that violated the invariant

Why this works

Address the root cause rather than removing or disabling the assertion

Fix 2

Disable assertions for production if they are development-only checks

WHEN Assertions are not appropriate for production workloads

Disable assertions for production if they are development-only checks
-- In postgresql.conf:
-- plpgsql.check_asserts = off

Why this works

Setting plpgsql.check_asserts=off disables all ASSERT checks without removing them from code

What not to do

Do not remove ASSERT statements to fix the error without investigating why the assertion failed

Assertions exist to catch bugs; removing them hides the underlying problem

Version notes
9.5

ASSERT statement added in PostgreSQL 9.5

Sources
Official documentation ↗

https://www.postgresql.org/docs/current/errcodes-appendix.html

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors