0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Concurrency and Schema
Reading EXPLAIN ANALYZE
EXPLAIN shows how PostgreSQL intends to execute a query, and EXPLAIN ANALYZE runs it and shows what actually happened. It is the single most important tool for understanding slow queries, yet its output is dense and easy to misread. This section explains the shape of a plan, how rows flow from the leaves to the root, how to read the indentation, and which node types appear most often, so that the rest of the lesson can focus on numbers and diagnosis.
Plans are trees of nodes
Every query plan is a tree. Leaf nodes read data: sequential scans, index scans, bitmap heap scans, function scans and values lists. Interior nodes combine or transform rows from their children: joins, sorts, aggregates, limits, hashes and gathers for parallel workers. The root node produces the final result rows. In text output each node starts on a line with an arrow, and its children are indented below it, so reading a plan means reading the tree from the innermost, most indented nodes outward.
Pull based execution
The executor runs plans by demand. The root asks its child for a row, that child asks its own children, and so on, each node producing one row at a time when asked. A Limit node stops asking once it has enough rows, which is why a plan with LIMIT 10 over an index scan can finish after reading only ten rows, while the same plan without the limit reads everything. Some nodes, like Sort and Hash, must consume all of their input before producing anything, which makes them blocking points in the pipeline.
EXPLAIN versus EXPLAIN ANALYZE
Plain EXPLAIN plans the query without running it and shows estimated costs and row counts. EXPLAIN ANALYZE runs the query, really executing it including any writes, and adds actual times, row counts and loops for every node. For INSERT, UPDATE or DELETE, wrap EXPLAIN ANALYZE in a transaction and roll it back to avoid changing data. Comparing estimates with actuals is the core of plan diagnosis, so EXPLAIN ANALYZE is what to run whenever the query can be executed safely.
Useful options
The options most worth using are BUFFERS, which shows pages read from cache and from disk per node and is on by default with ANALYZE since version 18, VERBOSE, which shows output columns and schema qualified names, SETTINGS, which lists non default planner settings, WAL for write queries, and FORMAT JSON or YAML for tools. The combination EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS) gives a complete picture. Version 17 added SERIALIZE to measure the cost of converting results for the client, and MEMORY to show planner memory use.
Common scan nodes
Seq Scan reads every page of a table. Index Scan descends an index and fetches heap rows in index order. Index Only Scan returns rows from the index where pages are all visible. Bitmap Index Scan builds a bitmap of matching pages, and Bitmap Heap Scan reads them in physical order with a recheck. Each scan line shows the table and index names, and below it the conditions it applied: Index Cond for conditions used to search the index, Filter for conditions checked on each fetched row, and Recheck Cond for bitmap scans.
Common join and aggregate nodes
Nested Loop runs its inner child once per outer row. Hash Join builds a hash table from one child, shown under a Hash node, and probes it with rows from the other. Merge Join walks two sorted inputs in step. Aggregation appears as HashAggregate, GroupAggregate for sorted input, or plain Aggregate for a single result row. Sort, Incremental Sort, Unique, Limit, Append for partitions and unions, Gather and Gather Merge for parallel workers, and Memoize for cached inner lookups complete the common vocabulary.
Where conditions appear
The location of a condition in the plan matters. A condition in Index Cond narrows the index search and reduces rows read. A condition in Filter is applied after rows are fetched, so the node still reads and discards them, shown as Rows Removed by Filter with ANALYZE. A Join Filter is applied after matching on the join condition. Seeing an important selective condition in Filter rather than Index Cond is one of the most common signs of a missing or misused index.
Subplans and CTEs
Correlated subqueries can appear as SubPlan nodes executed once per outer row, which is often slow, or as hashed SubPlans that build a hash once. InitPlan nodes run once before the main plan, for example for uncorrelated scalar subqueries. Since version 12, common table expressions are inlined into the main query unless they are referenced more than once or declared MATERIALIZED, in which case they appear as CTE Scan over a materialized result, which the planner cannot push conditions into.
Graphical and text tools
The text format is compact but hard to scan for long plans. Tools such as explain.depesz.com, explain.dalibo.com and pgMustard parse plans, highlight expensive nodes, compute exclusive time per node and flag large misestimates. The JSON format is what these tools read best. They do not replace understanding the output, but they speed up finding where the time went in a plan with dozens of nodes.
Reading the header line of each node
Each node line packs a lot into one row: the node type, sometimes the scan direction such as Backward, the relation and alias, then the estimate in parentheses and, with ANALYZE, the actuals in a second set of parentheses. Learning to scan these lines quickly, picking out node type, rows estimated, rows actual and loops, is most of the skill of reading plans. The detail lines beneath a node, such as conditions, sort keys and buffers, then explain why the node behaved as it did.
Parallel plan structure
A parallel plan has a Gather or Gather Merge node near the top of a subtree, with Workers Planned and Workers Launched. Below it, nodes prefixed with Parallel, such as Parallel Seq Scan and Parallel Hash Join, divide their work among the leader and workers. If Workers Launched is less than Workers Planned, the server ran out of parallel worker slots, limited by max_parallel_workers and max_worker_processes, and the query ran with less parallelism than the planner expected, which can explain occasional slowness under load.
Append and partitions
For partitioned tables and UNION ALL, an Append node lists one child per partition or branch. Partitions pruned at planning time do not appear at all, and those pruned at execution time, when a parameter value is only known at run time, are reported as Subplans Removed. Seeing every partition scanned for a query that should touch one is a sign that the partition key condition is not in a form the planner can use for pruning, such as a function applied to the partition key.
Plans for writes
UPDATE, DELETE and INSERT plans have a ModifyTable node at the root, shown as Update, Delete or Insert on the table, over a subplan that finds the rows to modify. The subplan is read like any SELECT plan. For INSERT ON CONFLICT, the plan shows the conflict arbiter index and, with ANALYZE, how many tuples conflicted. Time reported in triggers below the plan, including constraint triggers for foreign keys, is often where slow writes really spend their time.
Views and functions in plans
Views are expanded into the query before planning, so a plan never shows a view node; it shows the underlying tables, which can surprise readers who expect to see the view. SQL functions that are simple enough are inlined in the same way, while PL/pgSQL functions appear only as a Function Scan or an expression, hiding their internal queries from the outer plan.
A plan is a tree of nodes executed on demand from the root. Start reading at the deepest leaves, follow rows upward, note blocking nodes such as Sort and Hash, and check whether selective conditions sit in Index Cond or in Filter. Use EXPLAIN ANALYZE with BUFFERS, inside a rolled back transaction for writes.