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_depthset 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
- Fix the recursion (add a termination condition / depth limit).
- Reduce expression nesting or refactor the query.
- Raise
max_stack_depthonly after increasing the OS stack limit (ulimit -s).
Related & next steps
Reference: PostgreSQL 18 Section 20.4 “Resource Consumption”.
Thanks — noted. This helps keep the database accurate.