sql-optimizer
Skill340 starsChanged 8 months agoMITView on GitHub
Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans. Interprets EXPLAIN, detects anti-patterns, rewrites queries. Triggers on: "optimize this query", "slow query", "add indexes", "explain plan", "N+1 query", "why is this query slow".
8 other projects use a version of this.
Adopted by
Most recently taken up by
- jaskirat1616/grok-skillstheir 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
- minagayid/Agentstheir own version, first seen Jul 5, 2026
- BleckWolf25/AIToolkittheir own version, first seen Jul 4, 2026
- Viprasol-Tech/sql-optimizertheir own version, first seen Jun 14, 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
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
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 3 projects that use this
pbc-osSkillsecrets-manager
Set up and configure cloud secrets management for your AI agent. Guides users through platform selection (GCP, AWS, Azure, 1Password, Doppler, HashiCorp Vault), account setup, CLI configuration, and secure credential storage.
Also in 3 projects that use this
- +7 more from JayRHa
Other versions8 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 8
- jaskirat1616/grok-skills★ 22same name
- JayRHa/agent-skills★ 12same name
- JayRHa/AgentSkills★ 12same name
- milad-ahmd/agent-skills★ 5same name
- juanlurg/data-science-claude-skills★ 3same name
- BleckWolf25/AIToolkit★ 1same name
- minagayid/Agents★ 1same name
- Viprasol-Tech/sql-optimizer★ 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 repository94 other files it gives its agents.
- AGENTS.mdAGENTS.md
- adr-writerSkill
- agent-builderSkill
- animateSkill
- api-docs-generatorSkill
- appraiseSkill
- architecture-diagramSkill
- architecture-reviewerSkill
- arxiv-figuresSkill
- arxiv-packageSkill
- arxiv-preflightSkill
- benchmark-runnerSkill
- changelog-composerSkill
- chart-claritySkill
- citation-auditSkill
- codebase-advisorSkill
- code-refinerSkill
- competitive-analyzerSkill
- concept-to-imageSkill
- debug-investigatorSkill
- decision-mapSkill
- dependency-auditSkill
- devils-advocateSkill
- domain-modelingSkill
- engineering-retroSkill
- env-validatorSkill
- estimate-calibratorSkill
- feasibility-assessorSkill
- figure-rhetoricSkill
- figure-table-qualitySkill
- filesystemSkill
- githubSkill
- gpu-optimizerSkill
- handoffSkill
- html-presentationSkill
- html-videoSkill
- humanizeSkill
- idea-validatorSkill
- immuneSkill
- intakeSkill
- kg-builderSkill
- launch-videoSkill
- learning-workspaceSkill
- lightpanda-browserSkill
- linkedin-post-styleSkill
- literature-reviewSkill
- manuscript-provenanceSkill
- manuscript-reviewSkill
- manuscript-typographySkill
- market-analyzerSkill
- marp-slidesSkill
- mcp-to-skillSkill
- md-to-pdfSkill
- migration-risk-analyzerSkill
- milestone-runnerSkill
- module-deepeningSkill
- notebooklmSkill
- package-evaluatorSkill
- package-optimizerSkill
- paper-to-skillSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
5 rules. 0 are common, 4 are distinctive, and 1 is very specific to this project.
0
Common
Most of the 8 edited versions we read keep these.
4
Distinctive
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 53
If an EXPLAIN plan is provided:
- Very specific: line 67
Check for known performance anti-patterns (see references/anti-patterns.md):
- Distinctive: line 83
Consider composite indexes for multi-column conditions.
- Distinctive: line 124
CREATE INDEX {name} ON {table}({columns}).
- Distinctive: line 158
Index discipline: Every index has write overhead.
“Common” is measured: kept by at least 6 in 10 of the 8 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 Optimizer
Systematic SQL performance analysis: parse query structure, interpret EXPLAIN plans, detect anti-patterns (N+1, full scans, cartesian joins), recommend indexes, and rewrite queries — with explanations of WHY each change improves performance, not just WHAT changed.
Reference Files
| File | Contents | Load When |
references/anti-patterns.md | Common SQL anti-patterns with detection rules and fixes | Always |
references/index-strategies.md | Index type selection, composite index ordering, covering indexes | Index recommendations needed |
references/explain-guide.md | Reading EXPLAIN output for PostgreSQL, MySQL, SQLite | EXPLAIN plan provided |
references/join-optimization.md | Join type selection, join order optimization, subquery-to-join conversion | Query contains joins or subqueries |
Prerequisites
- The SQL query to optimize
- Database engine (PostgreSQL, MySQL, SQLite) — optimization differs by engine
- Table schemas and approximate row counts (helpful but not required)
- EXPLAIN output (highly valuable when available)
Workflow
Phase 1: Query Analysis
Parse the SQL to understand its structure:
- Identify operations — SELECT columns, FROM tables, JOIN conditions, WHERE filters, GROUP BY, ORDER BY, HAVING, subqueries.
- Map table relationships — Which tables are joined? On what keys? Are there implicit cartesian products?
- Detect immediate red flags:
SELECT *— fetching unnecessary columns- Functions on indexed columns in WHERE — prevents index use
ORin WHERE — often prevents index use- Correlated subqueries — potential N+1
- Missing WHERE on DELETE/UPDATE — dangerous
Phase 2: EXPLAIN Interpretation
If an EXPLAIN plan is provided:
- Scan types — Sequential Scan (bad for large tables), Index Scan (good), Index Only Scan (best), Bitmap Index Scan (acceptable).
- Join methods — Nested Loop (good for small tables), Hash Join (good for equi-joins), Merge Join (good for sorted data).
- Row estimates — Compare estimated rows with actual rows. Large discrepancies
indicate stale statistics (
ANALYZE). - Cost hotspots — Highest-cost node is the bottleneck. Optimize there first.
- Sort operations — External sorts (disk) are expensive. Consider indexes that match ORDER BY.
Phase 3: Anti-Pattern Detection
Check for known performance anti-patterns (see references/anti-patterns.md):
| Pattern | Detection | Impact |
| SELECT * | Star in select list | Transfers unnecessary data |
| N+1 queries | Loop with query inside | N additional roundtrips |
| Function on indexed column | WHERE UPPER(name) = 'X' | Index bypass |
| Implicit type cast | String compared to integer | Index bypass |
| Missing join condition | Cartesian product | Exponential rows |
| LIKE '%prefix' | Leading wildcard | Full scan |
| OR with different columns | WHERE a=1 OR b=2 | Index bypass |
| SELECT DISTINCT as band-aid | Hides duplicate-producing join | Fix the join instead |
Phase 4: Optimization
- Index recommendations — Based on WHERE, JOIN, ORDER BY, GROUP BY columns. Consider composite indexes for multi-column conditions.
- Query rewrite — Convert correlated subqueries to JOINs, replace
IN (SELECT...)with EXISTS, use CTEs for readability without performance cost (PostgreSQL 12+ may inline CTEs). - Schema suggestions — Denormalization, materialized views, partitioning (mention only when query-level optimization is insufficient).
Phase 5: Output
Present the original query, detected issues, recommended indexes, rewritten query, and explanation of each change.
Output Format
## SQL Optimization Analysis
### Original Query
```sql
{original SQL}
```
### Issues Detected
| # | Issue | Severity | Location | Impact |
| --- | ------- | ----------------- | ------------------- | ---------------- |
| 1 | {issue} | {High/Medium/Low} | {WHERE/JOIN/SELECT} | {what it causes} |
### EXPLAIN Interpretation
{If EXPLAIN provided}
- **Bottleneck:** {node type} on `{table}` (cost: {N})
- **Rows scanned:** {N} (estimated {M})
- **Index used:** {name or "None"}
- **Key insight:** {what this reveals}
### Recommended Indexes
```sql
-- {Reason for this index}
CREATE INDEX {name} ON {table}({columns});
```
### Optimized Query
```sql
{rewritten query}
```
### Change Explanation
1. **{Change}** — {Why this improves performance. Include estimated impact.}
### Expected Improvement
- Scan type: {before} → {after}
- Estimated rows scanned: {before} → {after}
- Index usage: {before} → {after}
Configuring Scope
| Mode | Input | Depth | When to Use |
quick | Single query | Anti-pattern scan + index suggestion | Fast feedback during development |
standard | Query + schema | Full analysis with rewrites | Default for optimization requests |
deep | Query + EXPLAIN + schema + row counts | Full analysis with statistics validation | Production performance investigation |
Calibration Rules
- Measure before optimizing. Request EXPLAIN output before recommending changes. Intuition about query performance is unreliable — a "slow-looking" query may be fast with proper indexes, and a "simple" query may scan millions of rows.
- Index discipline. Every index has write overhead. Do not recommend indexes that won't be used by the actual query workload. Consider the read/write ratio.
- Explain WHY, not just WHAT. "Add an index on
users.email" is incomplete. "Add an index onusers.emailbecause the WHERE clause filters by email, currently causing a sequential scan of 1M rows" is actionable. - Preserve correctness. Query rewrites must return identical results. If a rewrite changes semantics (e.g., INNER JOIN vs LEFT JOIN), flag it explicitly.
- Database engine matters. PostgreSQL, MySQL, and SQLite have different optimizers, index types, and capabilities. Always target the specific engine.
Error Handling
| Problem | Resolution |
| No EXPLAIN output provided | Analyze query structure and anti-patterns. Note that recommendations are best-effort without EXPLAIN. |
| Unknown database engine | Ask which engine. Default anti-pattern analysis applies to all engines. |
| Query uses ORM-generated SQL | Optimize the SQL, then suggest ORM-level changes (e.g., select_related in Django, eager loading). |
| Schema not provided | Infer table structure from the query. Note assumptions. |
| Query is already optimal | State that no significant improvements are possible. Suggest non-query optimizations (caching, denormalization). |
| Complex multi-CTE query | Analyze each CTE independently, then analyze the composition. |
When NOT to Optimize
Push back if:
- The query runs infrequently and performance is acceptable (one-time admin query)
- The optimization requires schema changes that affect many consumers — suggest an ADR instead
- The real problem is application-level (N+1 from ORM loop) — fix the application code, not the SQL
- The query is auto-generated by a tool (ORM migration, BI tool) — optimize at the tool level
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.

