SQLSTATE 54001 ERROR Class 54: Program Limit Exceeded

statement_too_complex stack depth limit exceeded — 54001

PostgreSQL error "stack depth limit exceeded" (SQLSTATE 54001): 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

Server-side recursion went deeper than max_stack_depth allows — typically deeply nested function calls or runaway recursive SQL/PL/pgSQL. PostgreSQL raises SQLSTATE 54001 (statement_too_complex).

  • A HINT suggests increasing max_stack_depth if safe.
  • Often from infinite or very deep recursion.
  • Guards against crashing the backend via stack overflow.

What the server log shows

ERROR:  stack depth limit exceeded
HINT:  Increase the configuration parameter max_stack_depth (currently 2048kB), after ensuring the platform's stack depth limit is adequate.

Why PostgreSQL raises this — what the manual says

Section 19.4.1 Memory (max_stack_depth):

“Specifies the maximum safe depth of the server’s execution stack.”

PostgreSQL checks execution stack depth against max_stack_depth. When recursion or nesting exceeds it, the statement is aborted with 54001 rather than risking a stack overflow that would crash the backend.

Common causes

  • Infinite or unbounded recursion in a function or recursive CTE.
  • Very deeply nested function/trigger calls.
  • A recursive query missing a proper termination condition.

Relevant GUC parameters

Parameter Default Effect
max_stack_depth 2MB Maximum safe server stack depth; must stay below the OS ulimit -s.

How to fix it

  1. Add a termination/base case to recursive functions or CTEs.
  2. Refactor deep recursion into iteration.
  3. If legitimately deep, raise max_stack_depth — but keep it below the OS ulimit -s.

Related & next steps

Reference: PostgreSQL 18 Section 20.4 “Resource Consumption”.

Was this helpful?