Optimize a SQL Query With an AI Agent: Start From the Plan

Give an AI agent the EXPLAIN plan, schema and row counts, not just the query. Steps, checks and pitfalls for PostgreSQL and MySQL.

Updated · Markdown version

To get a useful optimization from an AI agent, send it the query's execution plan along with the table definitions, indexes and row counts, not the SQL alone. With the plan in hand, the agent can point to the node that costs the most time and propose a change that you can test against the same plan.

Steps

  1. Capture the plan on a copy or inside a transaction. In PostgreSQL, run EXPLAIN (ANALYZE, BUFFERS) SELECT ...;. Plain EXPLAIN only plans the statement, but ANALYZE executes it. If the query writes data, wrap the command as BEGIN; EXPLAIN (ANALYZE, BUFFERS) ...; ROLLBACK;.
  2. For MySQL, start with `EXPLAIN SELECT ...;`. The MySQL 8.4 output reference covers type, key, rows, filtered and Extra. Use EXPLAIN ANALYZE only when you intend to execute the statement: it reports actual timing, rows and loops in TREE format, and MySQL also permits it for multi-table UPDATE and DELETE statements.
  3. Collect the context the planner used. Include the table definitions, the indexes on each table and approximate row counts. Without these, the agent can only guess which index would help.
  4. Refresh statistics if the row estimates look wrong. In PostgreSQL, run ANALYZE tablename;, then re-run the plan and compare estimated rows with actual rows.
  5. Send the full output to the agent. Ask it to name the node with the largest actual time, multiplying by loops first, and to explain which filter or join causes it. Ask for one change at a time.
  6. Apply the change and re-run the plan. Confirm that the slow node changed, Execution Time dropped, and the result set still matches the original.

Check that it worked: the same query returns the same rows, the plan no longer scans the large table at the node you named, and the timing holds across two or three runs.

Pitfalls

  • Per-loop numbers read as totals. A nested loop's inner node can show a small actual time that repeats loops times. Multiply before comparing nodes, or the agent will target the wrong node.
  • Estimates far from actuals. Stale statistics are a common cause, so run ANALYZE and compare again. The PostgreSQL docs describe sampling but do not state that every gap is a stale-statistics problem, so treat that as a hypothesis to test.
  • LIMIT distorts the numbers. Nodes under a LIMIT stop early, so their displayed estimates assume a full run. Do not judge them by estimated cost alone.
  • Writes during analysis. A plan run with ANALYZE on an UPDATE or DELETE changes data. Use the transaction wrapper from step 1 every time.
  • Flags without context. In MySQL, Using filesort or type = ALL is not always a problem on a small table. Check the rows column first, and reject index suggestions that add write cost without a measured gain.
  • Plans from different data sizes. A plan from a development database with a few hundred rows can choose a different join than production. Capture the plan on data close to production volume.

When to use a skill instead

A one-off question about a single slow query works fine as an ad hoc prompt, as long as you paste the plan and schema. A reusable skill is a better fit when you review many queries and want the same checks each time, such as the transaction wrapper, the single-change rule and the rollback step. sql-and-database-helper is a related skill on this site that writes, reviews and migrates SQL for PostgreSQL, MySQL and SQLite. It fits when the request involves an index, a schema change or a query review. If you only need to read a plan you already have, you can skip the skill.

FAQ

Does EXPLAIN ANALYZE change my data? Yes, when the statement writes. PostgreSQL executes the statement under ANALYZE, so an UPDATE or DELETE takes effect. Wrap the command in BEGIN and ROLLBACK to measure it safely.

Why do estimated and actual row counts differ? PostgreSQL bases its estimates on sampled statistics, which change after each ANALYZE. A LIMIT, a lossy index scan or a merge join can also make the numbers look different without any estimation error.

What does Using filesort mean in MySQL EXPLAIN? It means MySQL needs an extra pass to return rows in sorted order. An index that matches the ORDER BY columns can often remove that pass, which you can confirm by re-running EXPLAIN.

Platform Score is our assessment under a published method. It is not a safety guarantee.

Terms this guide uses

This item is a worked example in the AI glossary for:

Next steps

  1. Plan a Database Migration with an AI Agent: Rollback Checks Read next.
  2. Format SQL with an AI agent without changing its meaning Read next.
  3. All guides by topic Browse everything.

Sources

This page is not offered to search engines yet: The content file does not mark this page indexable yet.