Your Index Guess Is a Coin Flip: Prompts That Make an LLM Read EXPLAIN ANALYZE and Name the Bottleneck First

Your endpoint got slower at 3 a.m., someone added an index, the dashboard went green, and two weeks later your write latency doubled because the table now carries six overlapping indexes. This is the most common way "fast" gets bought in PostgreSQL: by gut feeling, not by reading the plan. Below are the prompts for the other route — hand the EXPLAIN ANALYZE output to an LLM, let it name the actual bottleneck (seq scan, cardinality misestimate, N+1 from the ORM), and only then touch DDL.

Step 1: Decide whether you even need the plan

Two situations, two answers. A rarely-run report on a 40,000-row table? Add the index, time it, move on — the cost of a wrong guess is a few seconds. A query on the hot path of a table that grows by a million rows a month? Any index you add without reading the plan is a tax on every INSERT and UPDATE, and the odds it removes the real bottleneck are not in your favour. 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”.

A rule of thumb: if the query is in the top 5 by total time in pg_stat_statements and the table is growing, you read the plan first. Everything else can wait. More on the topic: “Six Prompts That Read Your Time Series Better Than the Chart — Trend, Seasonality, Anomalies and the Breakpoint You Keep Missing”.

The cheapest diagnostic you already have Run EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) — the BUFFERS flag shows shared hits versus reads, which tells you whether the time is spent on disk or on CPU. Without it, the plan hides half the story.

Step 2: The first prompt — read the plan, do not fix anything yet

The fastest way to waste a good LLM answer is to ask "how do I speed this up". The model jumps to CREATE INDEX before it has read the tree. Ask for a diagnosis first, with a hard ban on suggestions.

Prompt:

You are a PostgreSQL 16 performance reviewer. Below is EXPLAIN (ANALYZE, BUFFERS) output for a slow query, plus the table definitions and indexes.

Do NOT propose any changes yet. Answer only:

1. Which node consumes the largest share of actual time? Quote the exact line.
2. Is the bottleneck disk I/O, CPU, or lock/wait (based on BUFFERS and timing)?
3. For every scan node: does the planner's estimated rows differ from actual rows by more than 10x? List the nodes where it does.
4. Is there a node whose actual time is under 1 ms and whose estimated cost is high — a sign of a misestimate upstream?
5. Output a single sentence: "The bottleneck is ___, and the reason is ___."

Plan:

<paste output>

Schema:

<paste \d table and \d+ indexes>

Usage example: on a 12M-row orders table, the plan shows Seq Scan on orders (actual time=0.02..8400 rows=3) while the planner estimated 240,000 rows. The model names the bottleneck: a cardinality misestimate caused by a stale WHERE status = 'pending' statistic. That is a different fix from an index — and the next prompt targets it.

Step 3: The cardinality prompt — when the estimate is the bug

An index on a column the planner thinks matches 240,000 rows will be ignored. That is why adding indexes "by intuition" so often changes nothing. The fix is statistics, not DDL.

Prompt:

The plan shows an estimated-rows vs actual-rows ratio worse than 10x on these nodes: <list nodes>. The predicate involved is <predicate>. Walk through the likely causes in order: (a) column statistics stale, (b) correlation between columns not captured (extended statistics), (c) value distribution skewed and the planner sampling too few rows, (d) type mismatch forcing an implicit cast that kills index use. For each cause, name the one command that verifies it and the one command that fixes it. Show the exact SQL to run, with the table and column names from my schema.

Usage example: the model returns ANALYZE orders; to verify staleness, then CREATE STATISTICS orders_status_created (dependencies) ON status, created_at FROM orders; for the correlated pair, then ANALYZE orders; again. No index added — and the plan switches to an index scan on its own.

The index was never the problem When actual rows differ from estimated rows by orders of magnitude, the planner is choosing between plans based on a wrong map. Fixing statistics is cheaper than any index and cannot slow down your writes.

Step 4: The index-cannibalisation prompt

Before adding an index, ask whether the ones you have are already fighting each other. A table with (user_id), (user_id, created_at) and (user_id, status, created_at) carries three indexes where one would do — each costing write throughput.

Prompt:

Here are all indexes on the table <name>, with their definitions and pg_stat_user_indexes numbers (idx_scan, idx_tup_read). Identify: (1) indexes never scanned since the last stats reset and their size; (2) indexes whose leading columns are a strict prefix of another index — which one is redundant; (3) indexes that could be merged into one with the same query coverage. Output a table with columns: index name, size, scans, verdict (keep / drop / merge into X), and the specific query patterns that justify the verdict.

Usage example: the model flags orders_user_id_idx as never scanned and fully covered by orders_user_created_idx, which has 1.2M scans. Dropping the first saves disk and one index write per INSERT — a change that makes the database faster, not just the query.

Step 5: The N+1 prompt — when the plan is fine but the query count is not

Sometimes each individual query is fast and the endpoint is still slow, because the ORM fires 400 of them. The plan will look healthy; the log will not.

Prompt:

Below is a slice of PostgreSQL logs (log_min_duration_statement = 0) for one HTTP request, plus the ORM model definitions. Group the statements by normalized shape (strip literals). For each shape: how many times it ran, total time, and whether it is inside a loop that could be replaced by a single JOIN or a prefetch. Then rewrite the worst shape as one SQL query, and show the ORM change (selectinload / prefetch_related / equivalent) needed to produce it.

Usage example: 380 identical SELECT * FROM products WHERE id = $1 statements, 4 ms each, totalling 1.5 s of the request. The model returns one SELECT... WHERE id = ANY($1) and the loader call that generates it.

Step 6: The subquery-to-JOIN prompt, with the trap spelled out

Rewriting a correlated subquery as a JOIN is the classic advice — and the classic way to silently change row counts when the joined table has duplicates. Make the model prove the rewrite is equivalent before it offers it.

Prompt:

This query uses a correlated subquery: <query>. Rewrite it as a JOIN only if the rewrite is provably row-for-row equivalent. Before showing the rewrite: (1) state whether the joined table can produce more than one row per key; (2) if it can, show the aggregate or DISTINCT that makes it safe; (3) compare the expected output of the original and the rewrite on these sample rows: <rows>. If the rewrite is not equivalent, say so and leave the subquery alone.

Usage example: the model spots that payments has multiple rows per order_id and the original subquery returns one arbitrary value. It refuses the naive JOIN and offers LEFT JOIN LATERAL (SELECT... ORDER BY created_at DESC LIMIT 1), which is both faster and correct.

Step 7: Prove the hypothesis on a test database

Every prompt above ends in a hypothesis. The last one turns it into a measurement, not an opinion.

Prompt:

I am about to apply this change: <DDL or rewritten query>. Give me: (1) the exact commands to capture a baseline before the change (pg_stat_statements reset, timing the query 10 times, recording the plan); (2) the same for after; (3) what result would falsify the hypothesis — what number, if it does not move, means the change did not work. Keep it to commands I can paste into psql on a staging copy.

Usage example: the model returns a \timing on block, a repeated run of the query, and a falsification rule: "if mean execution time does not drop by at least 30% and the plan still shows a Seq Scan, the index is not being used — check the predicate type." That last clause is what saves you from shipping a useless index to production.

Test on a copy, not on production Restore a recent dump into staging, run the baseline and the change there. An index that looks harmless on 40,000 rows can lock a 12M-row table for minutes when built without CONCURRENTLY.

What you actually get out of this

The point is not that an LLM is a DBA. The point is that reading the plan takes twenty minutes of focused attention most of us do not have at 3 a.m., and the model will read it every time without skipping the BUFFERS line. Two habits follow: never propose an index before the plan names the bottleneck, and never trust a rewrite until it has been timed on a copy. Everything else — the prompts, the flags, the statistics — is in service of those two habits.

Guess the index vs read the plan first
Index by intuition
  • Fast to try, no reading required
  • Writes get slower with every added index
  • Cardinality misestimates go unnoticed
  • Redundant indexes pile up
  • Works for small, rarely-run queries
Read the plan first
  • Twenty minutes of focused reading
  • Bottleneck named before any DDL
  • Statistics fixed before indexes
  • Indexes audited for overlap
  • Pays off on hot-path, growing tables
← All posts

Ask AI about this article

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