Optimize slow SQL from its execution plan: EXPLAIN-driven index and rewrite suggestions that return identical rows, re-measured before you ship.
--- name: query-optimizer description: Speeds up a slow SQL query by reading its execution plan (EXPLAIN / EXPLAIN ANALYZE in PostgreSQL and MySQL, EXPLAIN QUERY PLAN in SQLite, the actual execution plan in SQL Server), then proposing indexes or rewrites that return the same rows, and re-checking the plan and timing. Use when a query, report or endpoint is slow, an ORM generates N+1 queries, or someone asks which index to add. compatibility: Needs the query, the table definitions with existing indexes, and ideally read access to a non-production copy of the database with realistic data volume. metadata: version: "1.2.0" --- # SQL Query Optimizer Plan first, rewrite second, and prove that the rewrite returns exactly the same rows. ## Inputs to collect - The exact SQL (with parameter values or types), the database engine and version. - `CREATE TABLE` statements and existing indexes, approximate row counts. - Current timing and how often the query runs; read/write ratio of the tables (indexes slow writes). ## Workflow 1. **Get the plan.** - PostgreSQL: `EXPLAIN (ANALYZE, BUFFERS) <query>`. ANALYZE executes the query; for writes, wrap it in `BEGIN; ... ROLLBACK;`. - MySQL 8: `EXPLAIN ANALYZE <query>` (or `EXPLAIN FORMAT=TREE`). - SQLite: `EXPLAIN QUERY PLAN <query>`. - SQL Server: the actual execution plan (`SET STATISTICS XML ON`) plus `SET STATISTICS IO, TIME ON`. 2. **Read it.** Look for full scans of large tables (`Seq Scan`, `SCAN <table>`, `type: ALL`), big gaps between estimated and actual rows (stale statistics), sorts or hashes spilling to disk, nested loops over large inputs, and functions applied to indexed columns. 3. **Pick the smallest fix.** - Index the filter/join columns the plan scans (`CREATE INDEX idx_orders_customer_id ON orders(customer_id)`); for multi-column filters put equality columns first, then range/sort columns. In PostgreSQL use `CREATE INDEX CONCURRENTLY` on busy tables. - Make predicates sargable: `WHERE created_at >= '2026-01-01'` instead of `WHERE year(created_at) = 2026`; compare columns to values of the same type; use an expression index if a function is unavoidable. - Select only needed columns instead of `SELECT *` when it enables a covering index or cuts transfer. - Replace per-row ORM queries (N+1) with one query using `IN (...)` or a join, or the ORM's eager loading. - Refresh statistics (`ANALYZE`) when estimates are far off. 4. **Rewrites must preserve results.** `IN (subquery)` and `EXISTS` return each outer row once; a `JOIN` returns one row per match and can duplicate rows when the joined key is not unique. Prefer `EXISTS` for semi-joins. Modern planners often produce the same plan for `IN` and `JOIN`, so a rewrite is not automatically faster — keep it only if the plan or timing improves. 5. **Verify.** Re-run the plan, time several runs, and compare results (`SELECT count(*)` and a checksum or `EXCEPT` both ways between old and new query). 6. **Hand off** the migration (index DDL) for review; do not create indexes on production yourself. ## Output format ``` Query: <name> Engine: <db/version> Before: <plan summary> · <time over N runs> Change: <index DDL or rewritten SQL> · why (plan line it fixes) · write-cost trade-off After: <plan summary> · <time> · results identical: yes (how checked) ``` ## Limitations - Plans depend on data distribution; results from a tiny dev database may not hold in production. - Every index costs write time and storage; do not add indexes the plan does not use. ## Example (SQLite) Before: `EXPLAIN QUERY PLAN SELECT o.id, o.total FROM orders o WHERE o.customer_id IN (SELECT id FROM customers WHERE country='US')` → `SCAN o`. Fix: `CREATE INDEX idx_orders_customer_id ON orders(customer_id);` → plan becomes `SEARCH o USING INDEX idx_orders_customer_id (customer_id=?)`. Rewrite check: replacing the `IN` with a `JOIN` to a table where `customer_id` repeats returned more rows than the original, so the agent keeps `IN`/`EXISTS`.
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A reporting query that lists orders from US customers has slowed down as the orders table grew past 100,000 rows.
This is slow on SQLite: SELECT o.id, o.total FROM orders o WHERE o.customer_id IN (SELECT id FROM customers WHERE country='US'); orders has 100k rows, customers 20k, no indexes besides primary keys. Should I rewrite it as a JOIN?
Before plan from EXPLAIN QUERY PLAN: `SCAN o` with a list subquery over customers. Proposed change: `CREATE INDEX idx_orders_customer_id ON orders(customer_id);`. After plan: `SEARCH o USING INDEX idx_orders_customer_id (customer_id=?)`, with timings from repeated runs. On the JOIN question, the agent explains that a JOIN can duplicate orders when the joined key is not unique and that the planner may already treat IN as a semi-join. It keeps IN (or EXISTS) unless the plan improves, and shows a row-count comparison. The index DDL is handed off as a migration rather than applied to production.
AI Agent Skills are reusable workflow packages that extend your AI coding assistant with multi-step capabilities. Install query-optimizer by following these steps.
SKILL.md inside, in the location documented by your client. Do not assume every AI application reads the same directory.Requires an Agent Skills-compatible client; supported locations and activation vary by version. Read the SKILL.md setup guide. MCP connects tools and data and does not, by itself, install a skill.