Asking the sat-nav
You get in the car and type where you want to go. The sat-nav does three jobs, one after the other.
First it reads what you typed and checks that it makes sense: do these streets exist? Then it works out a route, choosing between many ways to get there. Only then does the driving start, following that route turn by turn.
The middle job is the clever one, the route chooser, and it has a name: the query planner. You only say where you want to go. The sat-nav decides how to get there.
Parse, plan, execute
SQL is declarative: it says what rows you want, not how to find them. Every query goes through the same stages (PostgreSQL names shown):
| Stage | What it does |
|---|---|
| Parser | Checks syntax, resolves table and column names, builds a query tree |
| Rewriter | Applies rules, such as expanding views into their underlying queries |
| Planner / optimizer | Considers alternative plans and picks the one with the lowest estimated cost |
| Executor | Runs the chosen plan, a tree of nodes, and streams rows back to the client |
The same query can be answered by very different plans: read the whole table or use an index, join A to B or B to A, hash or sort. The difference between a good plan and a bad one can easily be 100ร or 1000ร in run time, which is why the planner matters as much as the indexes you build.
Last week's counts
The sat-nav can't see the town right now. Instead it keeps a notebook of counts made last week: how many houses each street has, which streets are the most crowded, how many different streets each area has. These counts are called statistics.
For every possible route it adds up a guess, in its own made-up "sat-nav minutes", and picks the smallest. Ask to stop at the few houses in a quiet village and it drives straight to each one. Ask to stop at every house in the busy city centre and the same sat-nav simply drives down every street in order, because the counts say zigzagging to thousands of houses one at a time would take far longer.
Statistics and cost
PostgreSQL's planner is cost-based. It estimates how many rows each step will produce (its cardinality)
from statistics gathered by ANALYZE and stored in pg_statistic (readable through the pg_stats view):
- table size: pages and row count (
relpages,reltuplesinpg_class); - per column: fraction of nulls,
n_distinct, the most common values with their frequencies, a histogram of the remaining values in equal-population buckets, andcorrelationbetween value order and physical order.
From those it computes a selectivity for each condition, multiplies it by the row count, and prices each plan
with cost constants. Costs are in arbitrary units anchored to reading one page sequentially: seq_page_cost = 1.0,
random_page_cost = 4.0, cpu_tuple_cost = 0.01. They are not milliseconds.
So the same query shape gets different plans for different values. WHERE city = 'Leeds' (1% of rows) favours an
index (or bitmap) scan; WHERE city = 'London' (40%) favours reading the whole table, because thousands of random page reads cost
more than one sequential pass.
Independence assumption: by default the planner treats conditions on different columns as independent and
multiplies their selectivities. For correlated columns (city and postcode) that underestimates badly;
CREATE STATISTICS builds extended statistics (dependencies, distinct counts, MCV lists) across columns.
More detail for skewed columns: ALTER TABLE ... ALTER COLUMN ... SET STATISTICS n keeps more common values and
histogram buckets for one column (the global setting is default_statistics_target).
Many joins: the planner searches join orders with dynamic programming for small queries (within
join_collapse_limit, 8 by default) and switches to the genetic query
optimizer (GEQO) once a query has geqo_threshold (12 by default) or more FROM items.
Ways to visit the houses
Say your trip is "stop at every house with a red door". The sat-nav knows a few ways to do it.
It can drive down every street in town and look at each door. Slow, but steady, and best when most doors are red. It can look up red doors in the town's street directory and drive straight to each one, which is great for a handful of houses but means zigzagging if there are hundreds. If the directory already tells you everything you wanted to know, it doesn't drive at all. And for a medium number, it sticks a pin in the map for every red door first, then drives the streets in order, visiting each pinned house once. Each of these is a different scan.
Scan types
The leaves of every plan are scans, and choosing among them is the planner's first decision (see database indexes for how the index itself works):
| Scan | How it reads | Wins when |
|---|---|---|
| Seq Scan | Every page of the table, in physical order | A large fraction of rows match, or the table is small |
| Index Scan | Walks the B-tree, then fetches each matching row from the table (random reads) | Few rows match, or rows are needed in index order |
| Index Only Scan | Answers from the index alone, skipping the table | Every needed column is in the index and the pages are marked all-visible |
| Bitmap Index + Bitmap Heap Scan | Collects matching row locations into a bitmap, then reads table pages in physical order, each once | A medium number of rows, or combining several indexes |
An Index Only Scan still visits the table for pages the visibility map doesn't mark as all-visible; EXPLAIN ANALYZE
reports them as Heap Fetches. Keeping tables vacuumed keeps that number low.
Pairing up two lists
Many trips use two lists at once: a pile of parcels, and the houses they go to. The sat-nav must pair every parcel with its house, and it knows three ways.
With only a few parcels, it takes them one by one and looks each house up in the directory. With lots of parcels, it first writes every house onto cards in labelled boxes, then for each parcel opens just the right box, which needs space on the dashboard for all the cards. And if both lists are already in street order, it reads down both at once, like zipping a zip. Pairing two lists is called a join.
Join algorithms
For each join the planner picks an algorithm and an order (which input is outer, or which is hashed):
| Join | How it works | Wins when |
|---|---|---|
| Nested Loop | For each outer row, look up matching inner rows, ideally through an index | The outer side is small and the inner side has an index on the join key; also the only choice for non-equality conditions |
| Hash Join | Build a hash table on the smaller input, then probe it with each row of the other | Large, unsorted inputs joined on equality; the hash must fit in memory (work_mem ร hash_mem_multiplier) or it spills to disk in batches |
| Merge Join | Walk two inputs sorted on the join key in step | Both sides already sorted (by an index or an earlier sort), or the result is needed sorted on the join key anyway |
The cost of a nested loop grows with outer rows ร inner lookup cost. That's why a bad row estimate on the outer side is the most common cause of a slow plan: the planner expects 10 rows, picks a nested loop, and gets 100,000.
Preview the route, or drive it
The sat-nav has a button that shows the route on screen without moving the car, with its guess for every road. That button is EXPLAIN. A second button drives the route for real and writes the actual time and number of stops next to each guess, so you can see where it was wrong.
Read the route from the innermost line outward: those stops happen first, and their results feed the lines above.
When a guess says "10 stops" and the real number is 48,000, the notebook of counts is out of date: a huge new estate was built on that road since it was last counted. Count again and the sat-nav picks a sensible route.
EXPLAIN and EXPLAIN ANALYZE
EXPLAIN shows the chosen plan without running it. EXPLAIN ANALYZE executes the statement and adds real
timings and row counts to each node:
1EXPLAIN ANALYZE2SELECT c.name, o.total3FROM customers c JOIN orders o ON o.customer_id = c.id4WHERE c.city = 'Leeds';
Output from PostgreSQL 17; 18 also prints Buffers lines and shows actual rows with two decimals.
1Hash Join (cost=12.50..2128.30 rows=480 width=40) (actual time=0.310..9.820 rows=512 loops=1)2Hash Cond: (o.customer_id = c.id)3-> Seq Scan on orders o (cost=0.00..1736.00 rows=100000 width=16) (actual time=0.010..4.900 rows=100000 loops=1)4-> Hash (cost=11.90..11.90 rows=48 width=32) (actual time=0.200..0.200 rows=50 loops=1)5Buckets: 1024 Batches: 1 Memory Usage: 11kB6-> Index Scan using idx_customers_city on customers c (cost=0.29..11.90 rows=48 width=32) (actual time=0.020..0.150 rows=50 loops=1)7Index Cond: (city = 'Leeds'::text)8Planning Time: 0.250 ms9Execution Time: 10.100 ms
How to read it:
- Inside-out: the most indented nodes produce rows first and feed their parent. Here the index scan fills the hash, the seq scan probes it, and the Hash Join returns the result.
cost=startup..totalis in planner units;rowsis the estimate,widththe average row size in bytes.actual timeis in milliseconds and, likerows, is per loop: multiply byloopsfor the node's total.- Compare estimated vs actual rows at every node. Within a few times is fine; off by 100ร or more means the planner chose with wrong information, and the plan above that node is suspect.
Add BUFFERS to see pages hit in cache versus read from disk (PostgreSQL 18 includes it with ANALYZE by default).
Because EXPLAIN ANALYZE really runs the statement, wrap INSERT, UPDATE or DELETE in BEGIN โฆ ROLLBACK.
Stale statistics are the classic cause of huge misestimates: after a bulk load or a big delete, the numbers in
pg_stats describe a table that no longer exists. Autovacuum runs ANALYZE automatically once enough rows have
changed, but after a large batch job run ANALYZE orders; yourself.
When the directory can't help
The street directory is sorted by the street names exactly as they're written. Some questions make it useless, and the sat-nav falls back to driving every street:
- asking for streets whose name in capitals is "ELM ROAD": the directory isn't sorted by capitals;
- asking for house "12.0" when the directory lists "12": it has to rewrite every entry before comparing;
- asking for streets ending in "lane": the directory is sorted by the first letters;
- asking for "red door or a garden gnome" when only doors are in the directory.
In a Java program a helper called Hibernate often types the destination for you, so you can't see what was asked. Make it keep a diary of everything it types, copy the trip into the preview button, and you'll spot the problem.
Plans that miss the index, and finding them from Java
An index on email stores the column's values in order. Anything that hides the raw column from the planner
prevents its use:
| Pattern | Why the index is skipped | Fix |
|---|---|---|
WHERE lower(email) = ? | The index holds email, not lower(email) | An expression index: CREATE INDEX ON users (lower(email)) |
WHERE id = 42.0 on an integer column | The comparison becomes id::numeric = 42.0, a cast on the column | Bind the column's own type (Integer or Long, not BigDecimal) |
WHERE name LIKE '%son' | A leading wildcard has no prefix to seek in a B-tree | A trigram GIN index (pg_trgm), or full-text search |
WHERE a = ? OR b = ? | One side has no index, so only a full scan covers both | Index both (the planner can combine them with BitmapOr), or UNION two queries |
A prefix match (LIKE 'son%') can use a B-tree only with the C collation or a text_pattern_ops index.
With JPA, Hibernate writes the SQL, so the first step is seeing it. In Spring Boot (Hibernate 6):
1logging.level.org.hibernate.SQL=DEBUG2logging.level.org.hibernate.orm.jdbc.bind=TRACE
The first logger prints each statement with ? placeholders; the second prints the bound values. Paste the SQL and
values into psql behind EXPLAIN ANALYZE. Or let the server do it: load the auto_explain
module (shared_preload_libraries), set auto_explain.log_min_duration (it is -1, off, by default) and
auto_explain.log_analyze = on, and it logs the plan of every statement that runs at least that long, which also
catches what only happens in production. The same SQL log is how you spot
the N+1 query problem: one query for a list, then one more for every row in it.
1// Generates: select ... from users u1_0 where lower(u1_0.email)=lower(?)2@Query("select u from User u where lower(u.email) = lower(:email)")3Optional<User> findByEmailIgnoreCase(@Param("email") String email);
That query needs the expression index above; a plain index on email won't be used. Without the @Query, Spring
Data's derived IgnoreCase uses upper(...), so the index must match: CREATE INDEX ON users (upper(email)).
Generic and custom plans: a prepared statement can be planned for its actual parameter values (a custom plan)
or once for any value (a generic plan). With the default plan_cache_mode = auto, PostgreSQL uses custom plans
for the first five executions, then switches to the generic plan if its estimated cost isn't much higher than the
average custom one. PgJDBC only switches to a server-side prepared statement from the prepareThreshold-th execution
(5 by default), so a query can be fast for its first runs and change plan later. A generic plan is a problem for skewed
data: right for a rare value, wrong for one that matches half the table. plan_cache_mode = force_custom_plan
replans every time, at some CPU cost.
Don't fight the planner with switches: SET enable_seqscan = off is useful to see what the alternative plan
would cost, not as a fix. PostgreSQL has no built-in query hints; correct the statistics, the indexes or the query
instead.