sql-query-optimizer
Skill2 starsChanged 4 months agoMITView on GitHub
Diagnoses and rewrites slow SQL queries by reading execution plans, spotting anti-patterns, and proposing indexes, rewrites and schema changes with an estimated impact for each. Use when a query is slow, a report times out, a database is CPU- or IO-bound, or someone asks for help with EXPLAIN output, indexing strategy or query tuning on PostgreSQL, MySQL, SQL Server, Oracle, SQLite, BigQuery, Snowflake or DuckDB.
6 other projects use a version of this.
Adopted by
Most recently taken up by
- nek1987/auto-agent-harnesstheir own version, first seen Oct 11, 2026
- CreativeActtech/llm-skillstheir own version, first seen Oct 8, 2026
- SkillMedev/data-engineering-pipelinetheir own version, first seen Oct 5, 2026
- myclaude-sh/sql-query-optimizertheir own version, first seen Aug 26, 2026
- Nikoxkx/Agent-Skillstheir own version, first seen Jun 8, 2026
- ATOM00blue/agent-skills-protheir own version, first seen May 22, 2026
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- nek1987/auto-agent-harness★ 4same name
- CreativeActtech/llm-skills★ 2same name
- Nikoxkx/Agent-Skills★ 1same name
- ATOM00blue/agent-skills-pro★ 0same name
- myclaude-sh/sql-query-optimizer★ 0same name
- SkillMedev/data-engineering-pipeline★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository13 other files it gives its agents.
- AGENTS.mdAGENTS.md
- accessibility-auditorSkill
- contract-reviewerSkill
- csv-data-profilerSkill
- dependency-auditorSkill
- git-workflow-assistantSkill
- meeting-notes-to-actionsSkill
- prompt-engineering-optimizerSkill
- release-notes-generatorSkill
- rest-api-designerSkill
- security-code-reviewSkill
- technical-writing-editorSkill
- web-research-synthesizerSkill
The file
We split this skill into the rules it gives an agent
10 rules. 0 are common, 7 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 5 edited versions we read keep these.
7
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 21
Use for slow SELECTs, timeouts, lock contention, runaway DML, plan regressions, index design, and reviewing SQL before it ships.
- Distinctive: line 24
Do not use for: writing a query from scratch (that is authoring, not tuning), ORM configuration debugging, or infrastructure sizing.
- Distinctive: line 31
Never optimise blind. Ask for whatever is missing, but proceed with assumptions clearly labelled if the user cannot supply it:
- Distinctive: line 58
Before reasoning about the plan, catch the mechanical defects:
- Very specific: line 113
Add covering columns (INCLUDE in PG/SQL Server) to enable index-only scans.
- Very specific: line 114
Use partial indexes for skewed predicates: WHERE status = 'pending'.
- Distinctive: line 115
Every index costs write throughput and storage — state the tradeoff explicitly.
- Distinctive: line 116
Verify the index is actually used after creation.
- Very specific: line 117
Use CONCURRENTLY (PG) or ONLINE=ON (SQL Server) to avoid blocking prod.
- Distinctive: line 118
Before adding, check for a redundant prefix of an existing index.
“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Query Optimizer
Turn "this query is slow" into a ranked, evidence-backed remediation plan.
When to use
Use for slow SELECTs, timeouts, lock contention, runaway DML, plan regressions, index design, and reviewing SQL before it ships.
Do not use for: writing a query from scratch (that is authoring, not tuning), ORM configuration debugging, or infrastructure sizing.
Workflow
1. Gather context before theorising
Never optimise blind. Ask for whatever is missing, but proceed with assumptions clearly labelled if the user cannot supply it:
| Input | Why it matters |
| Engine + version | Plan syntax, optimiser features, hint availability |
| Full query text | Hidden subqueries and functions dominate cost |
EXPLAIN (ANALYZE, BUFFERS) or equivalent | Actual vs estimated rows is the single best signal |
| Table row counts and sizes | Distinguishes "needs an index" from "needs a rewrite" |
| Existing indexes | Prevents recommending a duplicate |
| Frequency + SLA | A 2 s query run 10 000×/min matters more than a 5 min nightly job |
| Read/write ratio | Constrains how many indexes are acceptable |
Plan commands by engine:
| Engine | Command |
| PostgreSQL | EXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT TEXT) <query> |
| MySQL 8+ | EXPLAIN ANALYZE <query> / EXPLAIN FORMAT=JSON <query> |
| SQL Server | SET STATISTICS IO, TIME ON + actual execution plan |
| Oracle | EXPLAIN PLAN FOR … then DBMS_XPLAN.DISPLAY_CURSOR(format=>'ALLSTATS LAST') |
| SQLite | EXPLAIN QUERY PLAN <query> |
| BigQuery | Execution details tab / INFORMATION_SCHEMA.JOBS |
| Snowflake | Query Profile / GET_QUERY_OPERATOR_STATS |
2. Run the static linter first
Before reasoning about the plan, catch the mechanical defects:
python3 scripts/sql_lint.py query.sql --dialect postgres --format mdIt flags the anti-patterns in the catalogue below, reports query complexity, and proposes a candidate composite index using the equality → range → sort ordering. Its output is a set of leads: a static rule cannot know your data distribution, so confirm everything against a real plan.
3. Read the plan top-down, cost bottom-up
Find the operator that dominates actual time, not estimated cost. Then check:
- Cardinality misestimation — actual rows ≫ or ≪ estimated rows (>10× off). Root cause is usually stale statistics, correlated predicates, or a function wrapping a column.
- Scan type — Seq/Full scan on a large table with a selective predicate.
- Join strategy — Nested loop over a large outer input; hash join spilling to disk; merge join forcing an expensive sort.
- Materialisation — sorts, hash aggregates, or CTEs spilling to temp files.
- Row multiplication — a join fan-out that inflates rows before filtering.
4. Match against the anti-pattern catalogue
| Anti-pattern | Symptom | Fix |
| Non-sargable predicate | WHERE YEAR(created_at)=2025, WHERE col+0=5, leading LIKE '%x' | Rewrite as a range: created_at >= '2025-01-01' AND created_at < '2026-01-01'; or add an expression index |
| Implicit type cast | Index ignored on a varchar column compared to a number | Match types, or cast the literal not the column |
SELECT * | Wide rows, no covering index possible, network cost | Project only needed columns |
OR across columns | Full scan instead of index usage | Split into UNION ALL branches, or add a composite/partial index |
| Correlated subquery in SELECT | Executed once per outer row | Rewrite as a LEFT JOIN on a pre-aggregated derived table |
DISTINCT masking a fan-out | Huge intermediate rowcount | Fix the join grain; aggregate before joining |
IN (SELECT …) with NULLs | NOT IN returns nothing / can't optimise | Use NOT EXISTS or LEFT JOIN … IS NULL |
| Offset pagination | OFFSET 100000 scans and discards | Keyset pagination: WHERE (sort_key, id) > (:k, :id) ORDER BY … LIMIT n |
| Function on join key | Hash join impossible | Store a normalised/computed column and index it |
Over-wide ORDER BY + LIMIT | Full sort of the result set | Index matching the sort order so the sort is eliminated |
| Missing predicate pushdown | Filter applied after a large aggregation/CTE | Move filters into the CTE/subquery; in PG <12 CTEs are optimisation fences — use MATERIALIZED/NOT MATERIALIZED deliberately |
| Row-by-row DML in a loop | N round-trips | Set-based single statement or batched INSERT … SELECT |
| Warehouse full-partition scan | BigQuery/Snowflake bytes-scanned is huge | Add a partition filter + clustering key; avoid SELECT * |
5. Design indexes deliberately
Order composite index columns as equality → range → sort/include:
-- WHERE tenant_id = ? AND status = ? AND created_at >= ? ORDER BY created_at DESC
CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created
ON orders (tenant_id, status, created_at DESC);Rules:
- One well-ordered composite index beats three single-column indexes.
- Add covering columns (
INCLUDEin PG/SQL Server) to enable index-only scans. - Use partial indexes for skewed predicates:
WHERE status = 'pending'. - Every index costs write throughput and storage — state the tradeoff explicitly.
- Verify the index is actually used after creation; do not assume.
- Use
CONCURRENTLY(PG) orONLINE=ON(SQL Server) to avoid blocking prod. - Before adding, check for a redundant prefix of an existing index.
6. Escalate only if rewrites and indexes are not enough
In order of increasing cost: refresh statistics → increase work_mem/sort
memory → materialised view or summary table → denormalisation → partitioning →
caching layer → sharding. Never propose sharding as a first response.
7. Report
Deliver a table of recommendations, each with: change, rationale tied to a plan
line, estimated speedup, risk, and rollback. Provide runnable DDL/SQL, and always
tell the user to re-run EXPLAIN ANALYZE to verify.
Tools
| Script | Use |
scripts/sql_lint.py | Static anti-pattern detection, complexity metrics and candidate index DDL |
python3 scripts/sql_lint.py query.sql --dialect postgres --format md
echo "SELECT * FROM t WHERE YEAR(d)=2025" | python3 scripts/sql_lint.py --min-severity highExit code 1 means at least one critical/high finding — usable as a CI gate on checked-in SQL.
Worked example
Query
SELECT * FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE YEAR(o.created_at) = 2025
AND c.country = 'FR'
ORDER BY o.created_at DESC
LIMIT 50;Plan finding — Seq Scan on orders (12.4 M rows, actual 8.1 s), then hash
join, then top-N sort. Estimated 1 200 rows, actual 486 000 rows.
Diagnosis
YEAR(o.created_at)is non-sargable → no index can be used.SELECT *pulls 41 columns, preventing an index-only scan.- The sort runs after the join over ~486 k rows.
Fix
CREATE INDEX CONCURRENTLY idx_orders_created_customer
ON orders (created_at DESC) INCLUDE (customer_id, total_amount, status);
CREATE INDEX CONCURRENTLY idx_customers_country_id
ON customers (country, id);
SELECT o.id, o.created_at, o.total_amount, o.status, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= DATE '2025-01-01'
AND o.created_at < DATE '2026-01-01'
AND c.country = 'FR'
ORDER BY o.created_at DESC
LIMIT 50;Result — index scan walks created_at DESC and stops early; sort eliminated.
8.1 s → ~15 ms. Cost: two indexes, ~180 MB, small write penalty on orders.
Quality checklist
sql_lint.pyrun and every finding either fixed or explicitly dismissed- Every recommendation cites a specific line/operator of the plan
- Rewrites are semantically identical (NULL handling, duplicates, ordering)
- No index recommended that duplicates an existing prefix
- Write-path cost of new indexes stated
- Engine-specific syntax is correct for the stated version
- Verification step (
EXPLAIN ANALYZEre-run) included - Destructive or blocking operations flagged with a safe alternative
Failure modes
| Situation | Response |
| No plan available | Give the ranked hypotheses, ask for EXPLAIN ANALYZE, do not assert a fix |
| Query is already optimal | Say so; redirect to schema, hardware or caching |
| Plan regression after a version upgrade | Compare plans, check statistics and optimiser flags before rewriting |
| Slowness is not the query | Check lock waits, connection pool saturation, IO throttling, cold cache |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

