SQLSTATE 54001 ERROR Class 54: Program Limit Exceeded

statement_too_complex stack depth limit exceeded — 54001

PostgreSQL error “stack depth limit exceeded — 54001” (SQLSTATE 54001): what it means, common causes, and how to fix it.

PG 9.6, 10, 11, 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed Jun 2026 Grounded in source

Diagnostic Queries

Symptoms

Execution exceeded the stack depth limit, usually from deeply nested expressions or unbounded recursion. PostgreSQL raises SQLSTATE 54001 (statement_too_complex).

  • The stack depth limit was hit during execution.
  • Common with infinite/very deep recursion in functions.
  • Also from extremely nested expressions.

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 guards against stack overflow by capping execution depth at max_stack_depth. Deep recursion (e.g. a runaway recursive function or CTE) or extreme expression nesting exceeds it, so PostgreSQL reports 54001 to avoid a crash.

Common causes

  • Infinite or excessively deep recursion in a function/CTE.
  • Extremely nested expressions or views.
  • max_stack_depth set lower than the kernel allows.

Relevant GUC parameters

Parameter Default Effect
max_stack_depth 2MB Safe execution-stack depth; should be below the OS ulimit -s.

How to fix it

  1. Fix the recursion (add a termination condition / depth limit).
  2. Reduce expression nesting or refactor the query.
  3. Raise max_stack_depth only after increasing the OS stack limit (ulimit -s).

Related & next steps

Reference: PostgreSQL 18 Section 20.4 “Resource Consumption”.

Was this helpful?