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:
| Node | Meaning |
|---|---|
| Seq Scan | read table pages and test rows |
| Index Scan | traverse index then visit heap tuples |
| Index Only Scan | answer from index when visibility/data permit |
| Bitmap Index Scan | build matching TID bitmap |
| Bitmap Heap Scan | visit heap pages from bitmap |
| Sort | order input; may spill |
| Aggregate | non-group/global aggregate strategy |
| HashAggregate | hash groups in memory/batches |
| GroupAggregate | aggregate grouped/sorted input |
| Limit | stop after required rows |
| Materialize | cache child results for reuse/rescans |
| Memoize | cache parameterized lookup results |
| Unique | remove duplicates from suitably processed input |
| Append / Merge Append | combine child/partition paths |
| Gather / Gather Merge | collect parallel-worker output |
| Result | compute result/no-relation expressions |
| Subquery Scan | scan subquery result plan |
| CTE Scan | read 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:
- does it remove sort/scanning?
- how much larger is the index?
- write/WAL impact?
- is result order deterministic (add
idif needed)? - is a partial index better?
- 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.