TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท sql ยท performance ยท postgresql

Query planning and EXPLAIN

How a database turns SQL into a plan, choosing scans and joins by estimated cost from table statistics, and how EXPLAIN and EXPLAIN ANALYZE show that plan with its estimated and actual row counts.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“‘ Database indexes

๐Ÿ–จ๏ธ Cheat sheet

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):

StageWhat it does
ParserChecks syntax, resolves table and column names, builds a query tree
RewriterApplies rules, such as expanding views into their underlying queries
Planner / optimizerConsiders alternative plans and picks the one with the lowest estimated cost
ExecutorRuns 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.

Parse, plan, execute4 steps
๐Ÿ›ฐ๏ธ The sat-nav๐Ÿง‘You๐Ÿ“Address reader๐Ÿ“Š Last week's counts๐ŸงญRoute chooser๐Ÿง‘โ€โœˆ๏ธDriver๐Ÿ˜๏ธ The town
Press play and watch it happen!

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, reltuples in pg_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, and correlation between 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.

๐Ÿ”ง Going deeper

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.

Same query, different plans5 steps
๐Ÿง‘You๐ŸงญSat-nav๐Ÿ“Š Last week's counts๐Ÿ›ฃ๏ธ Every street๐Ÿ  Straight to each house
Press play and watch it happen!

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):

ScanHow it readsWins when
Seq ScanEvery page of the table, in physical orderA large fraction of rows match, or the table is small
Index ScanWalks 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 ScanAnswers from the index alone, skipping the tableEvery needed column is in the index and the pages are marked all-visible
Bitmap Index + Bitmap Heap ScanCollects matching row locations into a bitmap, then reads table pages in physical order, each onceA 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.

Four ways to read a table4 steps
๐Ÿง‘โ€โœˆ๏ธDriver๐Ÿ“’ Street directory๐Ÿ˜๏ธ The town
Press play and watch it happen!

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):

JoinHow it worksWins when
Nested LoopFor each outer row, look up matching inner rows, ideally through an indexThe outer side is small and the inner side has an index on the join key; also the only choice for non-equality conditions
Hash JoinBuild a hash table on the smaller input, then probe it with each row of the otherLarge, unsorted inputs joined on equality; the hash must fit in memory (work_mem ร— hash_mem_multiplier) or it spills to disk in batches
Merge JoinWalk two inputs sorted on the join key in stepBoth 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.

Three ways to join3 steps
๐Ÿ“ฆ Pile of parcels๐Ÿ˜๏ธ Houses๐Ÿง‘โ€โœˆ๏ธDriver pairing upโœ… Parcel and house
Press play and watch it happen!

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)2  Hash 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)5        Buckets: 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)7              Index 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..total is in planner units; rows is the estimate, width the average row size in bytes.
  • actual time is in milliseconds and, like rows, is per loop: multiply by loops for 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.

Estimates, actuals and stale statistics5 steps
๐Ÿง‘You๐Ÿ“Š Last week's counts๐ŸงญSat-nav๐Ÿง‘โ€โœˆ๏ธDriver
Press play and watch it happen!

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:

PatternWhy the index is skippedFix
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 columnThe comparison becomes id::numeric = 42.0, a cast on the columnBind 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-treeA trigram GIN index (pg_trgm), or full-text search
WHERE a = ? OR b = ?One side has no index, so only a full scan covers bothIndex 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)).

๐Ÿ”ง Going deeper

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.

From Hibernate's SQL to the plan4 steps
๐Ÿง‘You๐Ÿง‘โ€๐Ÿ’ผHibernate, your helper๐Ÿ“” Helper's diary๐Ÿ–ฅ๏ธ Preview button๐ŸงญSat-nav
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Query planning and EXPLAIN, told the same way as the story.
  1. The same sat-nav goes straight to each house for a quiet village, but drives down every street for the busy city centre. Why?
  2. The preview button guessed 10 stops, but driving it for real showed 48,000. What is the most likely cause?
  3. You have a few hundred thousand parcels and a long list of houses, neither in street order. Which way of pairing up is usually quickest?
  4. The directory is sorted by street names as written. Which trip lets the sat-nav use it?
  5. Your helper types every trip for you. How do you find out why one trip is slow?
Answer every question to check.Passing marks Query planning and EXPLAIN as done.
Got the hang of Query planning and EXPLAIN? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—ƒ๏ธ Spring and databasesStep 7 of 7

โ† Previous on the path๐Ÿฝ๏ธ The N+1 query problem (JPA and Hibernate)Last step ๐ŸŽ‰Back to the path

๐Ÿ—๏ธ Storing data at scaleStep 2 of 7

โ† Previous on the path๐Ÿ“‘ Database indexesNext on the path โ†’๐Ÿ’ก Bloom filters