Skip to main content

68 — Query Processing

PostgreSQL turns SQL into execution through stages:

SQL text
↓ parse
parse tree
↓ analyze
resolved names + types
↓ rewrite
expanded rules/views
↓ plan/optimize
plan tree
↓ execute
rows / changes

Parsing validates grammar. Analysis resolves names, types, operators, aggregates and permissions-related semantics. Rewriting applies query-rewrite rules such as view expansion. Planning considers access paths/join orders/costs. Execution runs the selected plan-node tree.

The planner can transform equivalent relational expressions. SQL source order therefore does not prescribe scan or join order except where semantics require it.


69 — Query Planner

The planner compares possible paths using estimated costs. Cost is a relative model influenced by page I/O, CPU, row counts, cache assumptions, parallelism, sorting, and configuration.

Key inputs:

  • table/index size statistics;
  • column null fraction and distinct-value estimates;
  • most-common values and histograms;
  • physical correlation;
  • extended statistics across columns;
  • query constants/parameters;
  • indexes and operator classes;
  • join graph and available algorithms.
estimated rows wrong
↓
wrong scan/join cost assumptions
↓
bad join order / algorithm
↓
large downstream cost

A 100× row-estimation error near the bottom of a plan can become more important than a visibly expensive top node.

Planner settings can disable/alter strategies for diagnostics, but production tuning should fix root causes rather than permanently force plans without evidence.


70 — EXPLAIN

EXPLAIN shows the chosen plan without executing it:

EXPLAIN
SELECT * FROM orders WHERE customer_id = 42;

EXPLAIN ANALYZE actually executes the query and reports actual timing/rows/loops:

EXPLAIN (ANALYZE, BUFFERS, WAL, SETTINGS)
SELECT ...;

Read both estimated and actual values:

Index Scan ... (cost=0.42..8.44 rows=1 width=...)
(actual time=... rows=... loops=...)
  • cost=startup..total: planner units, not milliseconds;
  • rows: estimated rows per loop;
  • actual ... rows: observed rows per loop;
  • loops: number of node executions;
  • BUFFERS: shared/local/temp page activity;
  • WAL: WAL records/bytes generated by supported execution;
  • planning/execution time: end-to-end database phases for this execution.

A node that returns 100 rows for 10,000 loops has processed about one million rows at that node; multiply by loops when reasoning.

Modifying statements warning​

EXPLAIN ANALYZE DELETE ...;

executes the delete. Wrap in a transaction and roll back only when rollback semantics truly make the test safe, or use a representative non-production environment. Triggers/sequences/external effects can make casual assumptions dangerous.


71 — Execution Plan Nodes

Common nodes:

NodeMeaning
Seq Scanread table pages and test rows
Index Scantraverse index then visit heap tuples
Index Only Scananswer from index when visibility/data permit
Bitmap Index Scanbuild matching TID bitmap
Bitmap Heap Scanvisit heap pages from bitmap
Sortorder input; may spill
Aggregatenon-group/global aggregate strategy
HashAggregatehash groups in memory/batches
GroupAggregateaggregate grouped/sorted input
Limitstop after required rows
Materializecache child results for reuse/rescans
Memoizecache parameterized lookup results
Uniqueremove duplicates from suitably processed input
Append / Merge Appendcombine child/partition paths
Gather / Gather Mergecollect parallel-worker output
Resultcompute result/no-relation expressions
Subquery Scanscan subquery result plan
CTE Scanread materialized CTE result

Never label a Seq Scan “bad” merely because it is sequential. A full scan is ideal when most rows are needed.


72 — Join Algorithms

Nested Loop​

for each outer row
find matching inner rows

Great when outer side is small and inner lookup is cheap/selective (often indexed). Disastrous when a large underestimated outer side triggers repeated expensive scans.

Hash Join​

build hash table from one input
probe it with rows from other input

Excellent for many equality joins. Build-side size/memory and batching matter.

Merge Join​

sorted input A →
compare in order
sorted input B →

Useful when both sides can be obtained sorted (perhaps from indexes) and for large ordered joins. Sort cost may dominate if inputs are not already ordered.

The planner chooses based on estimates, available ordering/indexes, equality/range semantics, memory, and cost parameters—not fixed table-size rules.


73 — Query Statistics

ANALYZE samples tables and updates planner statistics. Autovacuum also runs analyze based on change thresholds.

Statistics include:

  • null fraction;
  • average width;
  • estimated distinct count;
  • most common values/frequencies;
  • histograms;
  • physical correlation.

Inspect via pg_stats rather than relying on catalog internals directly.

Extended statistics​

Columns are often correlated:

country='PK' strongly influences city distribution

Assuming independence can badly misestimate combined predicates. CREATE STATISTICS can collect dependencies, multivariate distinct counts (ndistinct), and multivariate MCV information:

CREATE STATISTICS users_country_city_stats
(dependencies, ndistinct, mcv)
ON country, city
FROM users;
ANALYZE users;

Statistics improve estimates; they do not enforce constraints.


74 — Query Performance

Use a repeatable method:

slow query/workload
↓
measure latency + frequency + data/load context
↓
EXPLAIN (ANALYZE, BUFFERS, WAL)
↓
find expensive / multiplied / spilling node
↓
compare estimated vs actual rows
↓
identify root cause
↓
change query / index / schema / stats / config
↓
measure again under representative load

Common root causes​

  • missing or wrong index;
  • reading far more rows than returned;
  • bad cardinality estimate;
  • join explosion;
  • sort/hash spill;
  • N+1 workload outside one SQL statement;
  • lock waits mistaken for execution slowness;
  • deep offset pagination;
  • stale statistics;
  • bloat and poor cache behavior;
  • parameter-sensitive generic plan;
  • too much concurrency causing I/O/CPU saturation;
  • unnecessary repeated computation/JSON extraction;
  • network/application transfer of excessive rows.

Performance is a workload property​

A query that takes 50 ms once may be the top problem at 10,000 calls/s; a 3-second admin query once per day may be irrelevant. Use pg_stat_statements to combine latency with call frequency and total workload contribution.

Before/after example​

Bad hot path:

SELECT *
FROM events
WHERE tenant_id = $1
ORDER BY occurred_at DESC
LIMIT 100;

If the plan filters millions of rows, a candidate index is:

CREATE INDEX events_tenant_time_idx
ON events (tenant_id, occurred_at DESC);

But validate:

  1. does it remove sort/scanning?
  2. how much larger is the index?
  3. write/WAL impact?
  4. is result order deterministic (add id if needed)?
  5. is a partial index better?
  6. does production parameter distribution differ?

Interview drill: Explain why “the index exists but PostgreSQL won't use it” is not itself a bug. Discuss cost estimates, selectivity, table size, predicate/operator compatibility, casts/functions, correlation, visibility, ordering, and cached/random I/O.