Stop Guessing at Indexes: Prompts That Make an LLM Read EXPLAIN ANALYZE Like a DBA

A query that was fine last quarter now takes four seconds. The reflex is to add an index on the column in the WHERE clause, or paste the SQL into a chat window and ask the model to "optimize" it. Both moves skip the only artifact that says what actually happened: the execution plan. EXPLAIN ANALYZE does not describe what the query might do — it runs it and reports how many rows each node returned and how long it really took. Below are prompts that make an LLM work from that evidence instead of from the shape of your SQL.

Where the time actually goes: guessing vs reading the plan
Guessing from the query text
  • Add an index on the WHERE column
  • Ask the LLM to rewrite the SQL
  • Bump work_mem and hope
  • Ship, watch latency, repeat
Reading EXPLAIN ANALYZE first
  • Find the node with the biggest actual time gap
  • Check estimated vs actual rows
  • Name the mechanism: seq scan, nested loop, misestimate
  • Change one thing, re-measure, check neighbors

Why asking for a rewrite first is the expensive mistake

An index added on a guess costs write throughput on every insert, disk, and vacuum time — and if the plan was already using a nested loop over a misestimated row count, the new index changes nothing. A rewrite suggested from the query text alone is worse: the model cannot see that your filter matches 40% of the table, so the "better" version it hands you is a coin flip dressed as advice. More on the topic: “Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First”.

The order matters: read the plan, name the node that eats the time, explain why it eats it, only then touch SQL, an index, or a setting. Each prompt below locks the model into one step of that sequence. More on the topic: “Twelve Prompts That Read EXPLAIN ANALYZE Better Than You Do — and the Three Moments When You Should Not Trust Them”.

Step 1: make the model read the plan before it says a word about indexes

Use this the moment you paste a plan. It forbids premature advice and forces a structured read. More on the topic: “Six Prompts That Read Your Time Series Better Than the Chart — Trend, Seasonality, Anomalies and the Breakpoint You Keep Missing”.

Prompt:

You are a PostgreSQL performance engineer. Below is the output of EXPLAIN (ANALYZE, BUFFERS, VERBOSE) for a single query. Do NOT suggest indexes, rewrites, or settings yet.

1. List every node in the plan tree with: node type, actual rows, actual time, and loops.
2. Compute the share of total execution time each node accounts for (actual time x loops / total runtime).
3. Point to the single node that dominates. Quote its line from the plan.
4. State in one sentence what that node is doing mechanically.
Plan:

<paste plan here>

Example: a plan where the top node shows 4,120 ms and a Nested Loop underneath shows actual time=0.8..3100 rows=1 loops=18000 — the model should flag the loop, not the outer node, because 3100 ms × 18000 loops is where the time went.

Always run with BUFFERS Plain EXPLAIN ANALYZE hides I/O. Adding BUFFERS shows `shared hit` vs `shared read`, which is often the difference between "the query is slow" and "the data was not in cache."

Step 2: catch the cardinality lie

Most "the plan is wrong" stories are estimation failures. The planner thought a filter would return 10 rows and it returned 80,000 — so it picked a nested loop that then ran 80,000 times.

Prompt:

For each node in this plan, compare `rows=` (estimated) with `actual rows=`. Compute the ratio actual/estimated. Flag every node where the ratio exceeds 10x or falls below 0.1x. For each flagged node, explain which of these is the likely cause and why: stale or missing ANALYZE statistics, a correlation between columns that the planner assumes is independent, a function or cast that hides the column's distribution, or a type mismatch between the filter value and the column. Do not propose a fix yet — only the diagnosis.

Plan:

<paste plan here>

A classic hit: WHERE status = 'active' AND created_at > now() - interval '1 day' on a table where "active" rows are always the recent ones. The planner multiplies two selectivities as if independent and lands an order of magnitude off. The prompt makes the model say that out loud instead of naming an index.

Step 3: turn the diagnosis into one testable hypothesis

Now you allow a fix — but exactly one, with a predicted effect you can measure.

Prompt:

Based on the diagnosis above, propose exactly one change. Format it as: (a) the change in SQL or DDL; (b) the node in the plan you expect to change; (c) the direction and rough magnitude of that change (e.g. "nested loop replaced by hash join, expected runtime under 300 ms"); (d) how to verify it with a single EXPLAIN ANALYZE run. Do not propose alternatives. We will test this one first.

Example output you should accept: CREATE STATISTICS on the two correlated columns, with the prediction that the nested loop collapses to a hash join. If the model suggests three indexes "to try," reject it — you cannot attribute a win to any of them.

Step 4: check that the fix does not break the neighbors

An index or a rewrite that helps this query can slow down the twelve others hitting the same table. This prompt forces the model to think about the blast radius.

Prompt:

We are about to apply this change: <DDL or rewrite>. List the query patterns on the same table that this change could affect negatively, and for each, what symptom to watch for in pg_stat_statements (mean_exec_time, calls, rows). Give me a one-line check I can run before and after to confirm nothing regressed.

A partial index on status = 'active' looks free until you remember the reporting job that scans the whole table — the planner may stop using the existing full index for it.

Step 5: when the plan is fine but the query is still slow

The plan can be correct and the query still slow because it returns 50,000 rows to the client, or because it runs 400 times a second. This prompt redirects the model away from the plan.

Prompt:

The plan shows no node dominating and no cardinality misestimate. Given this query, its runtime, and how often it is called, tell me whether the bottleneck is: the number of rows returned to the application, the number of executions per second, lock contention, or I/O that BUFFERS reveals as `read` rather than `hit`. Ask me for the one extra number you need to decide.

That last line is the point: the model should request pg_stat_statements.calls or the row count returned, not invent an answer.

What the whole sequence buys you

A single prompt that says "optimize this query" produces a plausible-sounding guess. The five steps above produce a traceable chain: this node, this estimate error, this one change, this measured result, this check on the neighbors. When the change does not help, you know exactly which link broke — and you have not added an index that will cost you on every write for a year.

Next time a query crawls, resist the rewrite. Paste the EXPLAIN ANALYZE, run step 1, and let the plan tell you where the time went.

More on the topic: "14 SQL Prompts That Turn EXPLAIN ANALYZE Into a PostgreSQL Query Tuning Plan".

← All posts

Ask AI about this article

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