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
- Capture the plan on a copy or inside a transaction. In PostgreSQL, run
EXPLAIN (ANALYZE, BUFFERS) SELECT ...;. PlainEXPLAINonly plans the statement, butANALYZEexecutes it. If the query writes data, wrap the command asBEGIN; EXPLAIN (ANALYZE, BUFFERS) ...; ROLLBACK;. - For MySQL, start with `EXPLAIN SELECT ...;`. The MySQL 8.4 output reference covers
type,key,rows,filteredandExtra. UseEXPLAIN ANALYZEonly when you intend to execute the statement: it reports actual timing, rows and loops in TREE format, and MySQL also permits it for multi-tableUPDATEandDELETEstatements. - 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.
- 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. - Send the full output to the agent. Ask it to name the node with the largest actual time, multiplying by
loopsfirst, and to explain which filter or join causes it. Ask for one change at a time. - Apply the change and re-run the plan. Confirm that the slow node changed,
Execution Timedropped, 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 timethat repeatsloopstimes. Multiply before comparing nodes, or the agent will target the wrong node. - Estimates far from actuals. Stale statistics are a common cause, so run
ANALYZEand 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
ANALYZEon an UPDATE or DELETE changes data. Use the transaction wrapper from step 1 every time. - Flags without context. In MySQL,
Using filesortortype = ALLis not always a problem on a small table. Check therowscolumn 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.
Related skills in this catalog
Platform Score is our assessment under a published method. It is not a safety guarantee.
Related guides
Terms this guide uses
This item is a worked example in the AI glossary for:
Sources
- https://www.postgresql.org/docs/current/sql-explain.html (accessed 2026-11-23)
- https://www.postgresql.org/docs/current/using-explain.html (accessed 2026-11-23)
- https://dev.mysql.com/doc/refman/8.4/en/explain-output.html (accessed 2026-11-23)
- https://dev.mysql.com/doc/refman/8.4/en/explain.html (accessed 2026-11-23)
This page is not offered to search engines yet: The content file does not mark this page indexable yet.