You’re staring at a query that ran fine yesterday and now pins a CPU core. You copy it into an LLM, ask “make this faster,” and get back something that looks clever but uses a function on a column, kills an index, and adds a DISTINCT for good measure. Sound familiar?
The problem isn’t the model. It’s the prompt. Two very different jobs get mixed up: generating SQL from scratch and rewriting an existing query with the plan as evidence. If you already have a query and can run EXPLAIN ANALYZE, the second path is safer and faster — you’re not asking the model to guess, you’re asking it to read. If you’re writing a brand-new query against a schema you barely know, the first path is fine, but only with strict guardrails. This roundup gives you 12 prompts for both scenarios, each with a concrete example and the exact moment to use it.
First, decide which game you’re playing
Before you paste anything into a chat window, answer one question: do I have a query and a plan, or just an idea? More on the topic: “Audit Your Own Query Log Before Choosing BM25 or Embeddings for RAG”.
If the answer is “I have a slow query and I can run EXPLAIN (ANALYZE, BUFFERS) on a replica” — you’re in rewrite territory. The model should never invent a new query from scratch; it should propose a minimal diff, explain why the planner chose what it chose, and tell you what could go wrong in production.
If the answer is “I need a query that joins these three tables and I don’t know the schema well” — you’re in generation territory. Here the risk is different: the model invents columns, misreads cardinality, and writes something that works on 100 rows but collapses on 10 million. You need prompts that force it to ask questions before writing a single line.
- No query yet
- Schema unfamiliar
- Risk: invented columns
- Best for prototypes
- Query + EXPLAIN ANALYZE
- Planner output as evidence
- Risk: misread plan
- Best for production
Scenario A: You already have a query and a plan (safer, faster)
This is where LLMs earn their keep. The model doesn’t need to be a database expert if you hand it the planner’s own output and ask it to translate. The prompts below assume PostgreSQL, but the logic works for any engine that exposes a plan.
1. The “explain the plan before you touch the query” prompt
When to use: you have a query that’s slower than you’d like, and you’ve already run EXPLAIN (ANALYZE, BUFFERS). You want the model to tell you why the planner chose this path before it suggests changes.
Why it works: most LLMs will happily rewrite a query without understanding the plan. Forcing them to narrate the plan first surfaces misunderstandings early — if the model misreads a Nested Loop, you’ll see it before it writes nonsense.
Prompt:
You are a PostgreSQL performance engineer. I will give you a query and its EXPLAIN (ANALYZE, BUFFERS) output. Do not rewrite the query yet. First, explain the plan in plain English: which node is the bottleneck, what the estimated vs actual rows tell you, and where the time is spent. Then list at most three hypotheses for why the query is slow, ordered by likelihood. For each hypothesis, name the specific plan line that supports it.
Query:
<paste query>
Plan:
<paste EXPLAIN output>
Example: you paste a query joining orders and order_items and the plan shows a Seq Scan on orders with 2 million rows filtered down to 50. The model should say: “The bottleneck is the sequential scan on orders; the filter status = 'pending' matches only 50 rows but the planner estimated 200,000, which suggests stale statistics or a missing index.” That’s the kind of observation that saves you from adding an index that already exists.
2. The “minimal diff, not a rewrite” prompt
When to use: the model has explained the plan, and you want a fix — but you don’t want a completely new query that you’ll have to re-review from scratch.
Why it works: LLMs love to rewrite. A minimal diff keeps the review surface small and makes it obvious what changed. It also forces the model to justify each change against the plan. More on the topic: “Making LLMs Speak Pandas and Polars: Prompts That Clean, Join, and Speed Up Your DataFrames Without Eating RAM”.
Prompt:
Based on the plan and your hypotheses, propose a minimal change to the query or schema that addresses the bottleneck. Do not rewrite the whole query. Output a unified diff (or a short before/after snippet) and, for each change, one sentence explaining which plan line it targets. If the fix is an index, give the exact CREATE INDEX statement and say which column order you chose and why.
Example: the model suggests adding CREATE INDEX CONCURRENTLY idx_orders_status_created ON orders (status, created_at) WHERE status = 'pending'; and explains that the partial index matches the filter and avoids bloating the index with completed orders. You can run that on a replica, check the plan again, and only then promote.
3. The “read the buffers, not just the time” prompt
When to use: the query is fast on a warm cache but slow in production, or you suspect I/O is the real problem.
Why it works: EXPLAIN (ANALYZE, BUFFERS) shows shared hit and read blocks. A model that ignores buffers will miss the difference between “CPU-bound” and “waiting on disk.”
Prompt:
Here is an EXPLAIN (ANALYZE, BUFFERS) plan. Ignore the execution time for a moment. Focus on the buffer usage: which nodes show a high number of shared read blocks relative to hits? What does that tell you about cache behaviour? Then suggest one change that would reduce reads without changing the result set.
Example: the plan shows a Bitmap Heap Scan with 120,000 shared reads and 2,000 hits. The model points out that the table is being read from disk because the index doesn’t cover the selected columns, and suggests a covering index with INCLUDE. That’s a different fix from “add an index on the filter column,” and it comes directly from the buffers.
4. The “will this break prod?” prompt
When to use: you have a proposed rewrite or index and you’re about to run it on a production-like dataset. You want the model to list the risks before you hit enter.
Why it works: it forces the model to think about locks, write amplification, and plan regressions — the things that turn a 10% speedup into an outage.
Prompt:
I’m considering this change: <paste diff or CREATE INDEX>. The table has <N> rows and receives <M> writes per minute. List the production risks in order of severity: locking, downtime, write amplification, plan regression for other queries. For each risk, say whether it can be mitigated and how (e.g., CONCURRENTLY, lock_timeout, off-peak window). If you’re not sure about a number, say so instead of guessing.
Example: the model warns that a plain CREATE INDEX takes an ACCESS EXCLUSIVE lock and blocks writes for the duration; on a 50-million-row table that could be minutes. It suggests CREATE INDEX CONCURRENTLY and notes that it can’t run inside a transaction. That’s the kind of warning that keeps prod alive.
5. The “explain it to my teammate” prompt
When to use: you’ve made a change and need to justify it in a code review or incident postmortem.
Why it works: if the model can’t explain the change in plain language, you probably don’t understand it well enough either. This prompt turns the plan into a narrative.
Prompt:
Turn this before/after plan into a short explanation for a teammate who knows SQL but not this specific query. Cover: what the old plan did, what the new plan does, why it’s faster (or not), and what to watch for in the future. Keep it under 200 words. No jargon without a one-line definition.
Example: the model writes: “The old plan scanned the whole orders table because the filter wasn’t selective enough for the existing index. The new partial index lets the planner jump straight to pending orders, cutting rows read from 2 million to about 50. Watch for: if the share of pending orders grows above ~10%, the partial index may stop being useful.” That’s a review comment you can paste as-is.
Scenario B: You’re writing a query from scratch (more guardrails needed)
Here the model has more freedom and more ways to be wrong. The prompts below are designed to slow it down and make it ask questions before it writes SQL.
6. The “interview me first” prompt
When to use: you have a vague idea (“I need a report of active users by plan”) and a schema you don’t fully remember.
Why it works: it prevents the model from inventing columns. By forcing it to ask clarifying questions, you catch misunderstandings before they become syntax errors.
Prompt:
I need a SQL query for PostgreSQL. Before you write any SQL, ask me up to five questions that would change the query: table names, column types, cardinality, whether NULLs are possible, time zone, and expected result shape. Do not assume column names. After I answer, write the query with comments explaining each join and filter.
Example: you say “active users by plan last month.” The model asks: what defines “active” (last login? last payment?), is plan a column or a join, and should the month be calendar or rolling 30 days? You answer, and the query it writes actually matches your definition — instead of guessing.
7. The “show me the schema you’re assuming” prompt
When to use: you’ve pasted a schema but the model keeps referencing columns that don’t exist.
Why it works: it makes the model’s assumptions visible. You can correct them before the SQL is generated.
Prompt:
Here is my schema: <paste CREATE TABLE statements>. Before writing the query, list the tables and columns you plan to use, and flag any column you’re unsure about. If a column you need isn’t in the schema, say so instead of inventing it.
Example: the model lists users.id, users.plan_id, plans.name, and flags that it doesn’t see a last_login_at column — only created_at and updated_at. You realise you need to join an events table. That saves a round of debugging.
8. The “write it for 100 rows, then for 10 million” prompt
When to use: you’re generating a query that will run on a large table, and you want the model to think about performance from the start.
Why it works: it forces the model to consider indexes and join order, not just correctness.
Prompt:
Write the query twice: first assuming the tables have 100 rows each, then assuming the main table has 10 million rows and the join columns are indexed. For the large-table version, explain which indexes the query relies on and whether a different join order would help. If the query would require a new index, say so.
Example: the small version uses a simple JOIN and ORDER BY; the large version suggests filtering before joining and notes that ORDER BY created_at DESC LIMIT 100 can use an index on created_at. You get a query that’s less likely to surprise you at scale. More on the topic: “CI/CD Without Surprises: 12 Prompts That Make the LLM Write Pipelines, Fix Broken Builds and Explain Terraform Plans in Plain English”.
9. The “don’t use functions on columns” prompt
When to use: you’ve noticed the model loves WHERE date_trunc('day', created_at) = '2026-11-01', which kills the index.
Why it works: it makes the rule explicit and asks for a sargable alternative.
Prompt:
Rewrite this query so that no function is applied to a column in a WHERE clause or JOIN condition. Use range conditions or expression indexes instead. If an expression index is the only option, give the exact CREATE INDEX statement.
Example: the model turns WHERE date_trunc('day', created_at) = '2026-11-01' into WHERE created_at >= '2026-11-01' AND created_at < '2026-11-02', which can use a plain B-tree index on created_at. Small change, big difference.
10. The “what could go wrong with NULLs” prompt
When to use: your query involves LEFT JOIN, NOT IN, or aggregates, and you’re not sure how NULLs will behave.
Why it works: NULL semantics are a classic source of silent wrong results. The model can walk through the cases.
Prompt:
For this query, list every place where NULL values could change the result: LEFT JOIN conditions, NOT IN subqueries, aggregate functions, and comparisons. For each, say what happens if the column is NULL and how to make the behaviour explicit (COALESCE, IS NOT NULL, etc.).
Example: the model points out that WHERE id NOT IN (SELECT user_id FROM bans) returns no rows if user_id contains a NULL, and suggests NOT EXISTS instead. That’s a bug you would have shipped.
Scenario C: Both worlds — you have a query but the schema is new
Sometimes you inherit a query and a schema you don’t know. These two prompts bridge the gap.
11. The “reconstruct the intent from the query and plan” prompt
When to use: you’ve been handed a 200-line query and asked to make it faster, but you’re not sure what it’s supposed to do.
Why it works: it forces the model to explain the query’s purpose before optimising, so you can check whether the optimisation preserves the result.
Prompt:
Here is a query and its plan. First, explain in plain English what the query returns and which business question it answers. Then list any parts that look redundant or suspicious (unused joins, filters that don’t affect the result). Only after that, suggest performance improvements.
Example: the model notices that a LEFT JOIN to addresses is never used in the SELECT or WHERE, and removing it cuts the plan in half. You confirm with the author and delete it.
12. The “generate the EXPLAIN for me” prompt
When to use: you can’t run EXPLAIN right now (no access, or it’s a read-only replica) but you want a rough idea of what the planner might do.
Why it works: the model can’t run the query, but it can reason about indexes and cardinality if you give it the schema and statistics. Treat its output as a hypothesis, not a fact.
Prompt:
I can’t run EXPLAIN right now. Based on this schema and these row-count estimates, predict the plan PostgreSQL would likely choose for this query. Name the access method for each table and the join order. Then list the top two reasons the plan might differ in reality (statistics, data distribution, configuration).
Example: the model predicts a Hash Join with a Seq Scan on the smaller table, but notes that if the smaller table is actually larger than estimated, the planner might switch to a Nested Loop. You use that to decide which statistics to refresh before running the real EXPLAIN.
The prompt that keeps you out of trouble
If you remember one thing: never ask an LLM to “optimise” a query without giving it the plan. The model is a translator, not a mind reader. When you hand it EXPLAIN ANALYZE output, you turn a guessing game into a reading comprehension exercise — and that’s where it actually helps.
Start with prompt #1 on your slowest query today. If the model can’t explain the plan in plain English, it has no business rewriting your SQL. And if you want more prompts for reading plans and tuning indexes, the blog has a deeper set: Stop Guessing at Indexes: Prompts That Make an LLM Read EXPLAIN ANALYZE Like a DBA.
For the MySQL side of the same problem, there’s EXPLAIN MySQL Without the Guesswork: How to Read a Slow Query Plan and Not Wreck the Index in Production.
And if your migrations are the thing that keeps you up at night, Your Migration Passed on Staging — That's Not Evidence: LLM Prompts That Prove ALTER TABLE Safety Before Prod covers the locking and rollback prompts that pair well with the ones above.
Pick one prompt, run it on a query you already know is slow, and see whether the model earns its keep. If it doesn’t, you’ve lost five minutes. If it does, you’ve saved an afternoon — and maybe an incident.