What is the query planner in PostgreSQL and how does it work?
Answer
The PostgreSQL query planner (optimizer) converts a parsed SQL query into an efficient execution plan. It uses statistics from pg_statistic (collected by ANALYZE) to estimate row counts and data distribution for each plan alternative. The planner generates multiple candidate plans using a dynamic programming algorithm (for ≤ 8 tables) or a genetic algorithm (GEQO, for many tables). It estimates cost in arbitrary units combining seq_page_cost, random_page_cost, and cpu_*_cost parameters. It considers join orderings, join algorithms (Nested Loop, Hash Join, Merge Join), scan types (Seq Scan, Index Scan, Index Only Scan, Bitmap Scan), and parallelism. Use EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) to inspect the chosen plan and identify bad estimates caused by stale statistics or correlation issues.
Previous
What are generated columns in PostgreSQL?
Next
What causes poor query plans and how do you fix them?