Twelve Prompts That Read EXPLAIN ANALYZE Better Than You Do — and the Three Moments When You Should Not Trust Them

A plan node called Nested Loop with rows=1 actual and rows=14000 estimated. You paste the plan into an LLM, it says "add an index on orders.customer_id", you add it, and the query gets slower — because the real problem was a stale pg_statistic after a bulk load, and the index just gave the planner a new way to be wrong. That is the whole tension of using LLMs on PostgreSQL: they are excellent at reading a plan out loud, and dangerous at prescribing a fix without the numbers that only your database has.

Below are twelve prompts that work — sorted by how much you can trust them. Reading a plan, finding an N+1, drafting an index, untangling a deadlock, reviewing a migration: same tool, very different reliability. The article is built around that line, not around prompt count. Each prompt comes with a real input sketch and, more importantly, with what to check in the answer before you run anything on production.

Where the LLM is a fast pair of eyes (and where it is guessing)

Before the prompts, the honest map. Three tiers:

Task Reliability What you must verify
Explaining what a plan node does High Nothing beyond the plan text itself
Naming the first bottleneck in a plan Medium-high That the plan came from real data, not a dev copy
Suggesting an index Medium That the column order matches your WHERE + ORDER BY
Estimating index cost/benefit Low Everything — run it on a replica
Deadlock analysis from logs High That the log is complete, not truncated
Migration safety review Medium Locks on your actual table size

Read the table as "where to spend your skepticism". The LLM never sees your data distribution, your bloat, your autovacuum settings, or the ten other queries competing for the same buffers. It sees what you paste. So the prompt's job is to force it to reason from the pasted evidence and flag what it cannot see. More on the topic: “Prompts That Read a P&L Like a CFO: Unit Economics, Scenarios and Anomaly Hunting vs. Building the Model by Hand”.

The one rule that saves you a rollback An LLM answer about a query plan is a hypothesis, not a diagnosis. Any recommendation that changes the schema gets tested on a replica with production-sized data before it touches the primary.

Prompt 1: Turn a raw plan into plain language, node by node

Start here because it is the safest and the most useful. Most engineers can read Seq Scan and Index Scan; fewer can explain why a Hash Join has Batches: 8 and what that means for work_mem.

Prompt:

You are a PostgreSQL performance engineer. Below is the output of EXPLAIN (ANALYZE, BUFFERS) from PostgreSQL 16. Walk through the plan from the innermost node to the outermost. For each node tell me: (1) what it physically does, (2) whether its actual rows differ from estimated rows by more than 10x, (3) how many buffers it touched and whether that suggests it read from disk or cache. Do not suggest any indexes yet. End with a one-sentence summary of where the time goes.

Plan:

<paste plan here>

Example input: a plan with Hash Join (cost=... rows=1200 width=64) (actual time=0.4..812 rows=118000 loops=1) and Batches: 8 Memory Usage: 4097kB.

What to check in the answer: the model should catch that 1200 estimated vs 118000 actual is a ~98x misestimate and that Batches: 8 means the hash table spilled to disk because it did not fit in work_mem. If it praises the plan's cost numbers instead of the actual rows, it is pattern-matching, not reading — rerun with the prompt telling it to ignore cost estimates entirely.

Prompt 2: Make it name the first bottleneck, not all of them

LLMs love to list ten findings. You need the one that matters. This prompt forces a ranking and, crucially, forbids the model from inventing statistics it cannot see.

Prompt:

From the EXPLAIN ANALYZE output below, identify the SINGLE node that accounts for the largest share of total execution time. Show the arithmetic: node actual time x loops, divided by the top-level actual time. Then list at most two secondary issues. For every claim, cite the exact line from the plan. If a claim would require knowing my data distribution, row counts, or table bloat — which you cannot see — say so explicitly instead of guessing.

<paste plan>

What to check: the arithmetic. A node with actual time=0.05..12 loops=20000 costs roughly 240 seconds of wall time even though 12 ms looks tiny — the model should multiply by loops. If it does not, it will point you at the wrong node every time. This is the single most common LLM mistake on plans.

On the same subject there is a deeper walkthrough of plan reading: Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First.

Prompt 3: Diagnose an N+1 from an application log, not from the plan

N+1 is invisible in a single plan — you see one fast query, executed 3000 times. The prompt has to work from the log.

Prompt:

Below are 40 lines from my PostgreSQL log (log_min_duration_statement = 0) captured over 10 seconds. Group identical query shapes (ignore literal values) and count executions. Tell me which shape is a likely N+1: high execution count, low individual duration, same WHERE column repeated with different values, and no prepared-statement reuse. Then show what the batched version would look like as a single query with ANY($1) or a JOIN, and what ORM-level change (eager loading, join fetch) would prevent it.

Log:

<paste>

What to check: whether the model correctly normalized the literals. If it treats WHERE id = 51 and WHERE id = 52 as different shapes, the count is meaningless. Also watch for it recommending a JOIN when the parent query returns 200k rows — that turns an N+1 into a fan-out and makes things worse.

Prompt 4: Draft an index — with the column order argued, not guessed

This is where trust drops. Ask for the reasoning, not the CREATE INDEX.

Prompt:

Given this query and the plan below, propose at most two index candidates. For each: list the exact column order and justify it against the WHERE clauses (equality columns first, then range, then ORDER BY), state whether a partial index on the status filter would be smaller and whether it would be used, and tell me what write cost I add per INSERT/UPDATE on a table with ~50M rows and ~2k writes/sec. If a candidate depends on selectivity I cannot confirm from the plan, say which statistic (n_distinct, correlation) I should check with a query on pg_stats.

Query:

SELECT id, total FROM orders WHERE customer_id = $1 AND status = 'open' ORDER BY created_at DESC LIMIT 20;

Plan:

<paste>

Example answer you should expect: (customer_id, status, created_at DESC) as the composite, plus an optional partial WHERE status = 'open' if open orders are a small fraction. If the model suggests (created_at, customer_id) because "ORDER BY comes first", it has the rule backwards — equality predicates pin the leading columns.

Check the statistics before you believe the index Run `SELECT attname, n_distinct, correlation FROM pg_stats WHERE tablename='orders';` — if `correlation` on `created_at` is near 1, a plain btree on it is already cheap to range-scan, and your composite may buy nothing.

Prompt 5: Stress-test the index suggestion against the planner's own logic

A second pass, deliberately adversarial. You are asking the model to argue against itself.

Prompt:

You previously suggested an index on (customer_id, status, created_at DESC). Now argue the opposite: under what conditions would PostgreSQL ignore this index and still choose a Seq Scan? Consider low selectivity of status, table size below the planner's cost threshold, high correlation, and the LIMIT pushing the planner toward an index-only scan. For each condition give a rough row-count threshold where the plan flips. Then tell me the EXPLAIN command I should run on a replica to confirm.

What to check: the model should mention random_page_cost and effective_cache_size as levers that change the flip point, and that an index-only scan needs VACUUM to keep the visibility map fresh. If it claims a specific percentage without saying "depends on your random_page_cost", it is reciting blog posts.

Prompt 6: Untangle a deadlock log into a lock-ordering story

Deadlock logs are terse and the LLM is genuinely good here — the pattern is textual and self-contained.

Prompt:

Below is a PostgreSQL deadlock report from the server log. Reconstruct the sequence: which transaction held which lock, which one waited, and where the cycle closed. Then tell me the minimal application-level fix: consistent lock ordering, shorter transactions, or SELECT ... FOR UPDATE NOWAIT with retry. Name the exact two statements that must be reordered and show the corrected order.

Log:

ERROR: deadlock detected

DETAIL: Process 4211 waits for ShareLock on transaction 8891; blocked by process 4212.

Process 4212 waits for ShareLock on transaction 8890; blocked by process 4211.

What to check: that it identifies the cycle correctly (A waits for B, B waits for A) and does not blame a missing index. Deadlocks are about order, not speed. Also confirm the retry advice includes a random backoff — retrying immediately reproduces the deadlock.

Prompt 7: Review a migration for locks before it runs at 3 a.m.

This one earns its keep. ALTER TABLE... ADD COLUMN... DEFAULT behavior changed in PostgreSQL 11, but SET NOT NULL and type changes still take heavy locks.

Prompt:

Review this migration for lock risk on a table with 80M rows and constant write traffic. For each statement tell me: the lock level it takes (ACCESS EXCLUSIVE, SHARE, etc.), whether it rewrites the table, and how long the lock is held. Flag any statement that blocks reads or writes. For risky ones, give the safe multi-step equivalent (add nullable column, backfill in batches, add constraint NOT VALID, then VALIDATE CONSTRAINT).

ALTER TABLE users ADD COLUMN last_seen timestamptz NOT NULL DEFAULT now();

ALTER TABLE users ALTER COLUMN email TYPE varchar(320);

CREATE INDEX idx_users_email ON users(email);

What to check: the model should flag ALTER COLUMN TYPE as a full rewrite holding ACCESS EXCLUSIVE for minutes on 80M rows, and recommend CREATE INDEX CONCURRENTLY for the index. If it says the ADD COLUMN with default rewrites the table, it is working from PostgreSQL 10 knowledge — since 11 that default is stored in the catalog and is cheap. More on the topic: “PostgreSQL Row-Level Security for Multi-Tenant Apps: How RLS Policies Actually Work and Where Tenant Isolation Quietly Fails”.

Prompt 8: Find the query that is eating the connection pool

Under load, the database does not crash from one slow query — it crashes when 200 connections each wait on a lock. This prompt works from pg_stat_activity.

Prompt:

Below is a snapshot of pg_stat_activity filtered to state = 'active' and 'idle in transaction'. Identify: (1) queries in 'idle in transaction' longer than 30 seconds — these hold locks and block vacuum, (2) the longest-running active query, (3) how many connections are in each wait_event_type. Then tell me which single setting or code change would most reduce connection pressure, and whether PgBouncer in transaction mode would help or break my prepared statements.

<paste rows: pid, state, wait_event_type, query_start, query>

What to check: whether it distinguishes idle in transaction from idle. The first is a bug in your app (a transaction left open), the second is just a pooled connection. Confusing them leads to pointless idle_session_timeout tuning. Also verify the PgBouncer advice — transaction pooling breaks session-level SET and PREPARE.

Prompt 9: Explain why the plan changed after a deploy

Two plans, same query, before and after. The LLM is good at diffing them.

Prompt:

Here are two EXPLAIN ANALYZE outputs for the same query, taken before and after a deploy. Diff them node by node. Tell me what changed: row estimates, join strategy, scan type, buffer counts. Then list the possible causes in order of likelihood — new statistics from autovacuum, changed data volume, a new index the planner now prefers, or a changed `work_mem`. Do not recommend a fix until you have named the cause.

What to check: if the plan changed from Nested Loop to Hash Join with the same data, the most likely cause is a statistics refresh — ANALYZE ran and the estimates moved. If the model jumps to "add an index" without naming the cause, stop it and rerun.

Prompt 10: Size the risk of a missing index on writes

Every index you add taxes every write. Ask for the trade-off in numbers.

Prompt:

I am considering adding an index to a table with 50M rows receiving 2000 INSERTs/sec and 500 UPDATEs/sec. The index is a btree on one integer column. Estimate the additional write cost qualitatively: extra page writes per insert, WAL volume increase, and the effect on autovacuum. Tell me what I should measure with pg_stat_user_indexes and pg_statio_user_indexes over 24 hours to confirm the index is used at all. If the index is never used, what does idx_scan = 0 tell me?

What to check: the model cannot give you exact bytes — it should not try. It should point you at idx_scan and idx_tup_read and warn that an unused index still costs write throughput. If it hands you a confident "adds 15% write overhead", that number is invented.

Prompt 11: Read a vacuum and bloat signal before it becomes an outage

Bloat is the slow leak that makes a plan flip from index to seq scan overnight.

Prompt:

Below is output from pg_stat_user_tables and a bloat estimate query. Which tables have dead tuples far exceeding live tuples, and which have not been autovacuumed for longer than my autovacuum_naptime would suggest? For the worst table, tell me whether a manual VACUUM (not FULL) is enough or whether the visibility map is the issue preventing index-only scans. Do not recommend VACUUM FULL on a live table without telling me the lock it takes.

What to check: that it says VACUUM FULL takes an ACCESS EXCLUSIVE lock and blocks everything — the safe alternative is pg_repack or a new table with a swap. If the answer skips the lock warning, it is unsafe advice.

Prompt 12: Ask the model what it cannot see

A closing prompt, deliberately self-limiting. Use it on any answer from the previous eleven.

Prompt:

You just gave me a recommendation about my PostgreSQL query. List every fact you assumed that was not present in the text I pasted: data distribution, table size, index existence, server settings, concurrent load. For each assumption, tell me the exact SQL query I should run to check it, and what result would change your recommendation.

What to check: this is the honesty test. A good model lists five or six assumptions and hands you queries against pg_stats, pg_class, pg_indexes, and pg_settings. A weak one says "I assumed nothing" — and that answer tells you to distrust everything above it.

What the LLM sees vs what decides the plan
In the pasted text (reliable)
  • Plan node types and actual rows
  • Loops and multiplied cost
  • Deadlock cycle in the log
  • Lock level of a DDL statement
Not visible (guesswork)
  • Column distribution and n_distinct
  • Table bloat and visibility map
  • random_page_cost and work_mem
  • Concurrent load and connection pressure

The tasks where the LLM genuinely earns its place

After running these for a while, the split is clear. The model is reliable at turning a plan into prose, at finding the loop-multiplied cost, at reading a deadlock cycle, and at flagging lock levels in a migration. Those are self-contained: the evidence is in the text you paste.

It is unreliable at anything that needs your data distribution. "Will this index help?" and "why is this estimate off by 100x?" are questions about your pg_statistic, your bloat, your random_page_cost. The model will answer confidently, and the answer will be wrong in a way that looks right.

The verification habit that pays for itself For every schema change an LLM recommends, run it on a replica with production-sized data, then compare `EXPLAIN (ANALYZE, BUFFERS)` before and after. If the plan does not improve, the recommendation was a guess — no matter how well-argued.

If you want the full plan-reading workflow these prompts sit inside, the deeper collection is here: 14 SQL Prompts That Turn EXPLAIN ANALYZE Into a PostgreSQL Query Tuning Plan.

The pattern generalizes beyond databases: LLMs are strongest when the evidence is in front of them and weakest when the answer depends on context they cannot see. That is true of a backup restore test as much as a query plan — Your Backup Is a Hope, Not a Plan: LLM Prompts That Measure RPO/RTO and Find the Hole Before You Lose the Database.

Start with prompt 1 and prompt 6 — they are nearly free to trust. Treat prompts 4 and 5 as a brainstorm with a skeptical colleague, not a verdict. And keep one rule in your head every time the model says "add an index": the planner already knows more about your data than the model ever will. Your job is to give the model the plan, take its hypothesis, and let the replica decide.

← All posts

Ask AI about this article

Ask a question about this article — ASI Biont will answer based on its text.