SQL Query Optimizer

Reads a slow query and its EXPLAIN plan, finds the bottleneck, and proposes a safe rewrite or index that preserves the results.

Reviewed Jul 7, 2026Data & SQLby AI World InformationMIT

What this skill does

Key features

  • Reads the query alongside its EXPLAIN (or EXPLAIN ANALYZE) plan
  • Pinpoints the bottleneck: sequential scans, bad join order, or a missing index
  • Proposes a rewrite or index that keeps the result set identical
  • Reports before/after cost or timing from the plans you provide

Use cases

  • Speeding up a report query that times out in production
  • Deciding which index would actually help a hot query
  • Understanding why the planner chose a sequential scan

SKILL.md

The skill definition — its metadata and the exact instructions an agent follows. Copy it into a SKILL.md file in your agent's skills folder.

namesql-optimizer
descriptionAnalyze a slow SQL query and its EXPLAIN plan, then suggest semantics-preserving rewrites or indexes.
allowed-toolsRead, Grep, Bash(psql -c EXPLAIN:*)
outputdiagnosis + proposed index/rewrite + before/after
destructivenever

Musts

  • Read the query and its EXPLAIN (or EXPLAIN ANALYZE) plan before proposing anything.
  • Run EXPLAIN, never the raw query, when investigating; never issue destructive or schema-altering statements.
  • Identify the single dominant bottleneck (scan, join, sort, or missing index) before suggesting a fix.
  • Propose only rewrites and indexes that preserve the exact result set and ordering semantics.
  • Show the before/after plan cost or timing so the improvement is verifiable.

Guidelines

  • Prefer a targeted index or predicate rewrite over restructuring the whole query.
  • Call out when an index would help reads but cost writes, so the user can decide.
  • If the plan is missing, ask for EXPLAIN output rather than guessing at row counts.
  • Preserve NULL handling, duplicates, and ordering when rewriting.

Output format

## Bottleneck
<the dominant cost node from the plan>

## Proposed change
<index DDL or rewritten query>

## Why it preserves results
<explanation>

## Before / after
- Before: <cost or ms from plan>
- After:  <cost or ms from plan>

FAQ

Will it run destructive statements?
No. It works from EXPLAIN plans and read-only queries you approve, and never issues DROP, DELETE, UPDATE, or schema-altering statements. Note that EXPLAIN ANALYZE actually executes the query, so it is used only on read (SELECT) queries — never on writes.
How does it know the change is faster?
It compares the EXPLAIN plans you provide before and after. It reports the planner's cost or ANALYZE timing rather than inventing numbers.

Before running any skill, read its instructions and the tools it's allowed to use, and test it on a safe target first. See LLM security best practices.