FULL AI ANALYSIS

PostgreSQL prepared statements pick a generic plan after ANALYZE on a partitioned table, causing 10× slower execution

Generated Oct 3, 2026, 12:35:03 AM

Analysis summary

PostgreSQL can create a cached 'generic' plan for prepared statements to save prepare time; that plan does not take account of specific parameter values, so if table statistics change (ANALYZE) and data distribution is skewed across partitions, the generic plan can become suboptimal. This is a known tradeoff between planning time and plan quality. Solutions include forcing the planner to create custom plans, changing application prepare behavior, or tuning planner settings.

Possible causes

Planner uses generic cached plans for prepared statements that are not appropriate after statistics change

100%

Application connection pooling prevents re-preparing statements with current statistics

95%

Skewed data distribution across partitions causing large differences between optimal custom and generic plans

85%

PostgreSQL planner configuration defaults favor generic plans for this query shape

25%

Suggested fixes

1

Diagnostic step 1

Collect EXPLAIN (ANALYZE, VERBOSE) for both the prepared (generic) and simple/custom plans to confirm differences and capture estimated vs actual row counts.

2

Diagnostic step 2

Modify the application to avoid long-lived prepared statements for highly selective queries (e.g., reprepare per-connection or use parameter passing mode that forces custom plans), or explicitly close and reprepare statements after maintenance windows.

3

Diagnostic step 3

Test setting plan_cache_mode = 'force_custom_plan' (if available in your PostgreSQL minor release) in a safe staging environment to evaluate impact; this forces per-execution planning at the cost of CPU.

4

Diagnostic step 4

Consider refactoring queries to be more stable in selectivity (e.g., rewrite to include partition key constants where possible) or add partial indexes on common query patterns.

5

Diagnostic step 5

If changes are unclear or impact is large, engage a DBA to review query patterns and recommend whether architectural changes (partition pruning improvements, use of prepared statements, or upgrade path) are most appropriate.