sql-optimizer
Skill1 starsChanged 19 days agoMITView on GitHub
Diagnose a slow SQL query from its execution plan and propose a verified optimization — finding the real bottleneck (sequential scan, missing or unused index, bad join order, app-side N+1) and measuring the fix before and after. Use when a query is slow and you need a fix backed by EXPLAIN ANALYZE, not a guess.
11 other projects use a version of this.
Adopted by
Most recently taken up by
- JohnnyQ-commits/aqueduct-data-agenttheir own version, first seen Nov 29, 2026
- divik-09/claude-skills-collectiontheir own version, first seen Nov 29, 2026
- jaskirat1616/grok-skillstheir own version, first seen Nov 1, 2026
- Mathews-Tom/armorytheir own version, first seen Nov 1, 2026
- milad-ahmd/agent-skillstheir own version, first seen Nov 1, 2026
- JayRHa/agent-skillstheir own version, first seen Oct 15, 2026
Used with
Projects with it also use changelog-keeper, 0-template and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
JayRHaSkillchangelog-keeper
Maintains a CHANGELOG.md in the Keep a Changelog format with Semantic Versioning, grouping user-facing entries under Added/Changed/Deprecated/Removed/Fixed/Security and cutting dated releases from an Unreleased section. Use this skill when the user asks to "update the changelog", "add a changelog entry", "cut a release", "bump the version", "what changed since the last release", or to create/clean up a CHANGELOG.md or release notes.
Also in 4 projects that use this
JayRHaSkill0-template
Template for creating a new Agent Skill. Copy this folder, rename it to your skill's kebab-case name, and fill in every section. Use this as the starting point whenever you author a new skill for the AgentSkills library.
Also in 3 projects that use this
MehdibargachSkillokr-writer
Turn business goals into structured OKRs with measurable Key Results, linked initiatives, alignment check, and anti-goals. Takes a strategic priority and outputs ready-to-use OKRs.
Also in 4 projects that use this
peopleforresterSkillrefactoring-guide
Safe refactoring patterns and techniques. Use when the user wants to improve code structure, reduce duplication, or make code more maintainable without changing behavior. Emphasizes incremental changes with test coverage.
Also in 3 projects that use this
xmqywxSkillmeeting-summarizer
Transform meeting transcripts into structured summaries with action items, decisions, follow-ups, and efficiency analysis. Works with any meeting format.
Also in 3 projects that use this
- +7 more from JayRHa
Other versions11 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 11
- Mathews-Tom/armory★ 340same name
- jaskirat1616/grok-skills★ 22same name
- JayRHa/agent-skills★ 12same name
- JayRHa/AgentSkills★ 12same name
- milad-ahmd/agent-skills★ 7same name
- juanlurg/data-science-claude-skills★ 3same name
- JohnnyQ-commits/aqueduct-data-agent★ 2same name
- BleckWolf25/AIToolkit★ 1same name
- divik-09/claude-skills-collection★ 1same name
- minagayid/Agents★ 1same name
1 more not listed
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 repository168 other files it gives its agents.
- agents.mdAGENTS.md
- 3d-asset-handoff-sheetSkill
- accessibility-regression-auditorSkill
- adr-writerSkill
- agent-memory-designerSkill
- agent-trajectory-evaluatorSkill
- alerting-rules-tunerSkill
- analysis-memo-writerSkill
- annotation-disagreement-ledgerSkill
- annotation-task-spec-builderSkill
- api-deprecation-plannerSkill
- api-error-contract-designerSkill
- architecture-diagram-generatorSkill
- asset-metadata-review-ledgerSkill
- auth-flow-reviewerSkill
- avatar-video-script-writerSkill
- background-job-reliability-auditorSkill
- branch-rebaserSkill
- brand-voice-profilerSkill
- bundle-analyzerSkill
- cache-policy-designerSkill
- canary-release-plannerSkill
- caption-correction-ledgerSkill
- changelog-from-prsSkill
- chart-chooserSkill
- chunking-strategy-optimizerSkill
- circular-dependency-breakerSkill
- claude-settings-auditorSkill
- code-example-verifierSkill
- cold-email-deliverability-auditorSkill
- cold-start-optimizerSkill
- commit-splitterSkill
- competitor-teardownSkill
- component-spec-writerSkill
- connection-pool-tunerSkill
- content-repurposerSkill
- contract-obligation-registerSkill
- contract-test-designerSkill
- conventional-commitsSkill
- cors-configuratorSkill
- coverage-gap-finderSkill
- crm-export-auditorSkill
- dashboard-designerSkill
- data-retention-auditorSkill
- dataset-first-lookSkill
- dead-code-finderSkill
- deadlock-diagnoserSkill
- decision-log-reconcilerSkill
- dependency-auditSkill
- dependency-upgrade-plannerSkill
- design-brief-writerSkill
- design-critique-checklistSkill
- design-token-extractorSkill
- devcontainer-designerSkill
- distributed-tracing-instrumenterSkill
- dockerfile-optimizerSkill
- email-sequence-drafterSkill
- embedding-index-tunerSkill
- embedding-set-inspectorSkill
- entity-match-candidate-ledgerSkill
- The first 60 shown.
The file
Files
Take a slow SQL query and find out why it is slow from the database's own execution plan, then fix the actual bottleneck instead of the first thing that looks suspicious. The skill runs EXPLAIN (and EXPLAIN ANALYZE where safe), reads the plan to locate the dominant cost — a sequential scan over a large table, an index the planner refused to use, a join order that materializes millions of rows before filtering, or an app-side N+1 firing the same query in a loop — and proposes one concrete change: a rewrite, an index, a statistics refresh, or a fetch-pattern fix. Every proposal is measured before and after on the real plan, so you ship a change you have proven, not one you hoped would help.
When to use this skill
- A specific query (a slow endpoint, a report, a migration step) is too slow and you need to know exactly which operation in its plan is the cost.
- You suspect a missing index, an unused index, or a query the planner is mis-estimating, and want it confirmed from
EXPLAIN ANALYZErather than intuition. - The same query appears many times in a request trace (an N+1), and you need to prove it and collapse it into one set-based query or a batched fetch.
- A query regressed after a data-volume increase, a schema change, or a deploy, and you want the before/after plan to localize the cause.
[!NOTE]
EXPLAIN ANALYZE(Postgres / MySQL 8+) executes the query to get real row counts and timings; in SQL Server the equivalent is enabling the actual execution plan (SET STATISTICS PROFILE ONorSET STATISTICS XML ON). On a write statement (UPDATE/DELETE/INSERT) or a heavy read this has side effects and cost — wrap writes in aBEGIN; ... ROLLBACK;or run plainEXPLAINfirst. Refreshing optimizer statistics is a separate operation:ANALYZE tablein Postgres/MySQL,UPDATE STATISTICSin SQL Server. Always measure against representative data; a plan on an empty dev table tells you nothing.
Instructions
- Locate the query and capture its cost. Find the exact SQL — in a
.sqlfile, an ORM call, a migration, or a log line. RunEXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)(Postgres) /EXPLAIN ANALYZE(MySQL 8+) / the engine equivalent and save the plan as your baseline. Record total time, the dominant node, and its share of the cost. - Detect the engine and conventions — do not guess. Identify the database (Postgres, MySQL/MariaDB, SQLite, SQL Server) from the driver, connection string, or migration files, since plan syntax, index types, and hint support differ. Note that SQLite only offers a static
EXPLAIN QUERY PLAN(no runtime row counts), so before/after timing on SQLite must come from wall-clock query runs rather than plan output. Check existing indexes (\d table/SHOW INDEX FROM table/pg_indexes) and the migration history before proposing a new one — match the project's naming and migration tooling rather than hand-writingCREATE INDEXout of band. - Read the plan for the real bottleneck. Work from the most expensive node, not the top:
- Seq Scan / Full Table Scan on a large table with a selective filter → a usable index is missing or not chosen.
- Estimated vs. actual rows wildly off (e.g.
rows=10butactual rows=900000) → stale statistics; runANALYZE table/ANALYZE TABLEbefore anything else. - Index Scan present but slow → low selectivity, a non-covering index forcing heap fetches, or a leading-column mismatch.
- Nested Loop over many rows / huge intermediate result → bad join order or a missing join-key index; a
Hash Joinmay be cheaper. - Same query repeated N times in a trace → app-side N+1; the fix is in the code (eager load /
JOIN/IN (...)), not the database.
- Propose one targeted change. Pick the single highest-leverage fix: add a composite or covering index matching the filter + sort columns in the right order; rewrite to make a predicate
sargable(no function wrapping the indexed column, no leading-wildcardLIKE); replaceOFFSET-based paging with keyset pagination; or collapse an N+1 into a set-based query. Prefer a query rewrite or statistics fix over a new index when it resolves the plan — every index has write and storage cost. - Verify by re-running the plan. Apply the change (indexes inside a transaction or against a copy where possible) and re-run the identical
EXPLAIN ANALYZE. Confirm the expensive node changed (Seq Scan → Index Scan), estimates now match actuals, and total time dropped. A change that does not move the plan is not a fix — discard it. - Report before/after and flag gaps. State the baseline time, the bottleneck node, the change, and the measured new time. Note any caveat the user must own: an index that slows writes, a fix that only helps at current data volume, a rewrite that changes
NULL/ordering semantics, or an N+1 that needs an application change you cannot make from SQL alone.
[!WARNING] An index only helps if the predicate is sargable and its leading column matches.
WHERE date(created_at) = '2026-01-01'orWHERE email LIKE '%@acme.com'cannot use a normal B-tree index — the function or leading wildcard forces a scan. Fix the predicate (range on the raw column, or an expression/trailing-wildcard index) instead of adding an index the planner will ignore.
Examples
A query filtering and sorting orders for one customer is taking ~480 ms. The baseline plan shows the cost:
EXPLAIN ANALYZE
SELECT id, total, created_at
FROM orders
WHERE customer_id = 4815 AND status = 'shipped'
ORDER BY created_at DESC
LIMIT 20;
Limit (cost=38120.55..38120.60 rows=20) (actual time=478.9..478.9 rows=20 loops=1)
-> Sort (cost=38120.55..38255.7 rows=54061) (actual time=478.9..478.9 rows=20)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 28kB
-> Seq Scan on orders (cost=0.00..36680.00 rows=54061) (actual time=0.1..441.2 rows=53992 loops=1)
Filter: (customer_id = 4815 AND status = 'shipped')
Rows Removed by Filter: 1946008 <-- scanned 2M rows to keep 54k
Planning Time: 0.20 ms
Execution Time: 479.3 msThe bottleneck is the Seq Scan discarding ~1.9M rows, not the sort. A composite index on the filter columns plus the sort column lets the planner satisfy the filter, ordering, and LIMIT from the index alone:
CREATE INDEX CONCURRENTLY idx_orders_customer_status_created
ON orders (customer_id, status, created_at DESC);Re-running the identical EXPLAIN ANALYZE confirms the fix — the scan is gone and the LIMIT stops after 20 rows:
Limit (cost=0.56..33.9 rows=20) (actual time=0.05..0.31 rows=20 loops=1)
-> Index Scan using idx_orders_customer_status_created on orders
(actual time=0.04..0.29 rows=20 loops=1)
Index Cond: (customer_id = 4815 AND status = 'shipped')
Execution Time: 0.41 ms -- 479 ms -> 0.4 ms (~1100x)Report the result and the caveat: 479 ms → 0.4 ms, Seq Scan → Index Scan, no rows discarded; the new index adds a small write cost on orders inserts/updates, which is justified here since this query runs on every customer page load.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
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.

