Reading PostgreSQL EXPLAIN Plans With LLMs in October 2026: Paste the Real Plan, Make the Model Quote Its Evidence, and Prove Every Fix With a Second Run
A slow query is one of the few performance problems that comes with its own explanation. Run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL and the database tells you exactly what it did: which tables it scanned, which indexes it used or ignored, how many rows it expected, how many it actually found, and where the time went. The trouble is that a real plan can run to dozens of nested lines, and reading one well takes practice.
That makes plan reading a good job to share with a large language model. A model is patient with long, indented output, it knows the vocabulary (Seq Scan, Nested Loop, Hash Join, Bitmap Heap Scan), and it can point you at the suspicious line faster than you can scroll. But it is also happy to recommend an index you do not need, or to "fix" a query in a way that quietly changes its results. This guide covers a workflow that keeps the model useful: give it the real plan, make it explain before it prescribes, and prove every change with a second plan.
Step 1: Capture the right plan, not just any plan
Plain EXPLAIN shows only the planner's estimates. That is the planner's guess, and the most common cause of a slow query is that the guess was wrong. You want the version that actually ran the query and recorded what happened:
EXPLAIN (ANALYZE, BUFFERS, VERBOSE, SETTINGS)
SELECT o.id, o.total, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'pending'
AND o.created_at > now() - interval '7 days'
ORDER BY o.created_at DESC
LIMIT 50;
A few practical notes before you paste anything into a model:
- ANALYZE really executes the statement. For a
SELECTthat is fine. For anUPDATE,DELETE, orINSERT, wrap it in a transaction and roll it back:BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE ...; ROLLBACK; - Run it where the data looks like production. A plan from a laptop database with 500 rows tells you almost nothing about a table with 40 million. Use a staging copy or a read replica when you can.
- Run it twice. The first run may read from disk and the second from cache.
BUFFERSshows "shared hit" (found in memory) versus "read" (fetched from disk), which helps you tell a cold-cache problem from a bad plan. - Check for sensitive values.
VERBOSEoutput and filter lines can include literal values from your query, such as email addresses or IDs. Replace them with placeholders if the model you are using is not approved for that data.
If you prefer a structured format, EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) gives the same information as JSON. Models read both well; the text format is shorter and easier for you to check against afterward.
Step 2: Give the model the context a plan does not contain
A plan shows what happened, but not what the query is for or what the schema looks like. Without that, a model has to guess, and guesses are where bad advice comes from. Paste these together:
- The exact query text.
- The full plan output, not a trimmed excerpt. The line you think is irrelevant is often the one that matters.
- The table definitions and existing indexes. In
psql,\d ordersprints both. - Your PostgreSQL major version, because planner features differ between versions.
- Rough table sizes and how often the query runs. A query that runs once a night has different priorities from one that runs on every page load.
- Constraints: "we cannot change the query, it comes from an ORM", or "this table takes heavy writes, so extra indexes have a cost".
Then ask for an explanation first, not a fix:
Here is a PostgreSQL 17 query, its EXPLAIN (ANALYZE, BUFFERS) output,
and the table definitions. Before suggesting any change:
1. Walk through the plan from the innermost node outward.
2. Identify the node(s) where most of the actual time is spent.
3. Point out any node where estimated rows and actual rows differ by
more than 10x, and say what might cause it.
4. Only then, list possible fixes, ranked by how confident you are,
with the trade-off of each.
Quote the plan lines you are referring to.
Asking the model to quote plan lines is the most useful part of that prompt. It forces the answer to be anchored in your actual output, and it lets you check each claim in seconds instead of trusting a summary.
Step 3: Know the patterns the model should be looking for
You will get more out of the conversation if you recognize the common problems yourself. Most slow plans come down to a handful of patterns.
A card catalog is an index: it only helps if you look things up the way it was sorted. Database indexes work the same way. Image: Card catalog at the Indiana State Library - interior view of catalog cards.jpg by TBurmeister (WMF), CC BY-SA 4.0, via Wikimedia Commons.
Estimates that are far from reality
Every node shows rows= twice: once in the estimate (the first set of parentheses) and once in the actual figures. When the planner expects 12 rows and gets 180,000, it may choose a nested loop that would have been fine for 12 and is terrible for 180,000. Common causes include stale statistics (fix with ANALYZE orders;), columns whose values are correlated in ways the planner does not know about (extended statistics via CREATE STATISTICS can help), and filters on expressions the planner cannot estimate well.
A sequential scan that reads far more than it returns
A line like Seq Scan on orders ... Rows Removed by Filter: 3998211 means the database read four million rows to keep a few hundred. That is often a missing or unusable index. But a sequential scan is not automatically wrong: on a small table, or when the query really needs most of the rows, it can be the fastest option.
Loops that multiply
Inside a nested loop, the inner node's actual time and rows are per loop. A line showing actual time=0.040..0.050 rows=1 loops=250000 looks cheap until you multiply: a quarter of a million index lookups adds up. Models sometimes miss the loops= multiplier, so check that any time figure they quote accounts for it.
Sorts and hashes spilling to disk
Look for Sort Method: external merge Disk: ... or a Hash node with more than one batch. Those mean the operation did not fit in work_mem and used temporary files. The fix might be an index that returns rows already in order, a smaller result set, or a modest work_mem increase for that session. Be careful with raising it globally, since the setting applies per sort or hash operation, and a single complex query can run several at once.
An index that exists but is not used
If you have an index on created_at but the query filters on date(created_at), or compares a text column to a number, the index usually cannot help. Wrapping an indexed column in a function or a type cast is one of the most common reasons a "perfectly indexed" query still scans.
Step 4: Treat every suggested fix as a hypothesis
The model's suggestions will usually fall into a few categories, and each one deserves its own kind of skepticism.
- "Add an index." Often right, but indexes are not free. Each one slows down writes to the table and takes disk space. Ask the model which exact query predicates the index serves and in which column order. For the example above, a composite index such as
(status, created_at DESC)could serve both the filter and theORDER BY ... LIMIT, letting the database stop after 50 rows. On a busy production table, build it withCREATE INDEX CONCURRENTLYso you do not block writes. - "Rewrite the query." Check that the rewrite returns the same rows. Swapping an
INfor a join can introduce duplicates, changingNOT INtoNOT EXISTSchanges how NULLs behave, and dropping aDISTINCTcan change results. Run the old and new queries and compare the output, not just the speed. - "Change a setting." Suggestions like lowering
random_page_costor disabling a join type can make one query faster and others slower. Test settings at the session level withSETfirst. Settings such asenable_nestloop = offare diagnostic tools for understanding the planner, not production fixes. - "Update statistics." Cheap and low-risk. If estimates were badly off, run
ANALYZEon the involved tables and capture the plan again before trying anything else.
A good follow-up prompt when you get a list of fixes: "For each suggestion, tell me what in the plan would look different if it worked." That gives you a concrete thing to check, such as the sequential scan turning into an index scan or the sort node disappearing.
A prediction is not a measurement. Time the query again before you trust a fix. Image: Ca 1970 mechanical stopwatch by Herwins Switzerland.jpg by R. Henrik Nilsson, CC BY 4.0, via Wikimedia Commons.
Step 5: Prove it with a second plan
Never accept a fix based on the model's prediction. Apply the change in a non-production environment, run the same EXPLAIN (ANALYZE, BUFFERS) again, and paste both plans back into the conversation:
Here is the plan before and after adding the index.
Compare them node by node. Did the change do what we expected?
Is anything now worse, such as a new sort, more buffers read,
or a different join strategy?
Compare more than the total execution time. Look at buffers read, because a query that got faster only because the data was cached will be slow again tomorrow. Try a few different parameter values too. A plan that is fast for status = 'pending', which might be rare, could be slow for status = 'shipped', which might be most of the table.
Step 6: Keep a record of what you learned
Once a fix holds up, write down the before and after plans, the change you made, and why. A short note in the migration that adds the index ("supports the pending-orders dashboard query; replaced a 2-second sequential scan") saves the next person from dropping it as "unused" or adding a duplicate. If you have pg_stat_statements enabled, check it over the following days to confirm the query's average time actually dropped in production, not just in your test.
What the model is good at, and what it is not
In practice, a model is a strong reading partner for query plans. It can explain unfamiliar node types, spot estimate mismatches across a long plan, and suggest plausible causes quickly. It is weaker at anything that depends on facts outside the text you gave it: how your data is distributed, what your write load looks like, which other queries share the table, and how much memory your server really has. Those are the details that decide whether a fix is a good idea.
So keep the division of labor clear. Let the model read the plan and propose hypotheses. Let the database, through a second EXPLAIN ANALYZE and a check that results are unchanged, be the judge of whether a hypothesis was right.
Quick checklist
- Capture
EXPLAIN (ANALYZE, BUFFERS)on realistic data, and roll back any write statement. - Paste the full plan, the query, the table definitions with indexes, and your PostgreSQL version.
- Ask for an explanation that quotes plan lines before asking for fixes.
- Check estimates against actual rows, and multiply per-loop figures by
loops. - Treat indexes, rewrites, and setting changes as hypotheses with costs.
- Verify with a second plan, compare the result rows, and test more than one parameter value.
- Document the change so the fix survives the next cleanup.
Comments
Post a Comment