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

> Canonical: https://skillalmanac.com/learn/optimize-a-sql-query-with-an-ai-agent | Updated: 2026-11-23 | Index status: not offered to search engines

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

## Facts

- 2026-11-21: PostgreSQL EXPLAIN without ANALYZE plans the statement but does not execute it; EXPLAIN ANALYZE executes it and adds actual time and row counts (https://www.postgresql.org/docs/current/sql-explain.html)
- 2026-11-21: PostgreSQL EXPLAIN ANALYZE runs INSERT, UPDATE and DELETE for real, so the docs suggest wrapping it in BEGIN and ROLLBACK (https://www.postgresql.org/docs/current/sql-explain.html)
- 2026-11-21: PostgreSQL BUFFERS reports shared block hits and reads, and is included by default with ANALYZE (https://www.postgresql.org/docs/current/sql-explain.html)
- 2026-11-21: PostgreSQL planner row estimates come from sampled statistics, and actual time and rows are per loop, so multiply by loops for totals (https://www.postgresql.org/docs/current/using-explain.html)
- 2026-11-21: MySQL 8.4 EXPLAIN type ALL means a full table scan per combination of prior rows, and Extra can show Using filesort or Using temporary (https://dev.mysql.com/doc/refman/8.4/en/explain-output.html)
- 2026-11-23: MySQL 8.4 EXPLAIN ANALYZE executes the statement and reports actual timing, rows and loops in TREE format; it supports SELECT, TABLE, and multi-table UPDATE and DELETE statements (https://dev.mysql.com/doc/refman/8.4/en/explain.html)

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](/skills/skill-almanac/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.

## Related skills

- [sql-and-database-helper](https://skillalmanac.com/skills/skill-almanac/sql-and-database-helper.md): Platform Score 57/100 (provisional)

## Related guides

- [Plan a Database Migration with an AI Agent: Rollback Checks](https://skillalmanac.com/learn/plan-a-database-migration-with-an-ai-agent.md)
- [Format SQL with an AI agent without changing its meaning](https://skillalmanac.com/learn/format-sql-with-an-ai-agent.md)
- [How to Use an AI Agent on a First Task You Can Check](https://skillalmanac.com/learn/how-to-use-an-ai-agent.md)
- [Check a Resume for ATS Problems With an AI Agent](https://skillalmanac.com/learn/check-a-resume-for-ats-with-an-ai-agent.md)
- [Draft a Cloud Migration Plan with AI: Inventory First](https://skillalmanac.com/learn/draft-a-cloud-migration-plan-with-ai.md)

## Sources

- https://www.postgresql.org/docs/current/sql-explain.html
- https://www.postgresql.org/docs/current/using-explain.html
- https://dev.mysql.com/doc/refman/8.4/en/explain-output.html
- https://dev.mysql.com/doc/refman/8.4/en/explain.html

Platform Scores report our assessment under a published method. They are not a safety guarantee.
