What causes poor query plans and how do you fix them?
Answer
Common causes of poor plans: (1) Stale statistics: run ANALYZE tablename or wait for autovacuum. Increase default_statistics_target for better estimates on skewed columns: ALTER TABLE t ALTER COLUMN c SET STATISTICS 500;. (2) Incorrect row estimates: check EXPLAIN ANALYZE for large discrepancies between estimated and actual rows. (3) Wrong cost parameters: random_page_cost (default 4.0) is too high for SSDs — set to 1.1. (4) Correlation issues: the planner doesn't know about multi-column correlations — use extended statistics: CREATE STATISTICS stat1 ON col1, col2 FROM table;. (5) Bad join ordering: use SET join_collapse_limit = 1 to force explicit ordering. (6) CTE optimization fence (pre-v12): move CTEs inline or use MATERIALIZED/NOT MATERIALIZED hints.
Previous
What is the query planner in PostgreSQL and how does it work?
Next
What is logical replication in PostgreSQL?
More PostgreSQL Questions
View all →- Advanced What is the query planner in PostgreSQL and how does it work?
- Advanced What is logical replication in PostgreSQL?
- Advanced How do you implement row-level security (RLS) in PostgreSQL?
- Advanced What is table bloat in PostgreSQL and how do you fix it?
- Advanced How does PostgreSQL handle deadlocks?