data-sql-optimization
Skill238 starsChanged 6 months agoMITView on GitHub
Optimize SQL query performance using EXPLAIN analysis, indexing strategies, and common anti-pattern fixes. Use this skill when the user needs to speed up slow queries, design indexes, fix N+1 problems, or optimize database performance — even if they say 'this query is slow', 'optimize our database', 'which indexes do we need', or 'our dashboard takes 30 seconds to load'.
2 other projects use a version of this.
Adopted by
Most recently taken up by
- joaoguirunas/team-ostheir own version, first seen Oct 21, 2026
- vasilyu1983/AI-Agents-publictheir own version, first seen Oct 13, 2026
Other versions2 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 2
- vasilyu1983/AI-Agents-public★ 94same name
- joaoguirunas/team-os★ 6same 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 repository315 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- algo-ad-biddingSkill
- algo-ad-budgetSkill
- algo-ad-ctrSkill
- algo-ad-gspSkill
- algo-ad-vcgSkill
- algo-blockchain-basicsSkill
- algo-blockchain-smart-contractSkill
- algo-ecom-bm25Skill
- algo-ecom-rankingSkill
- algo-ecom-searchSkill
- algo-forecast-arimaSkill
- algo-forecast-ensembleSkill
- algo-forecast-exponentialSkill
- algo-forecast-prophetSkill
- algo-hr-compensationSkill
- algo-hr-matchingSkill
- algo-hr-turnoverSkill
- algo-mfg-cpkSkill
- algo-mfg-doeSkill
- algo-mfg-fmeaSkill
- algo-mfg-spcSkill
- algo-net-centralitySkill
- algo-net-communitySkill
- algo-net-influenceSkill
- algo-nlp-ldaSkill
- algo-nlp-nerSkill
- algo-nlp-similaritySkill
- algo-nlp-summarizationSkill
- algo-price-bundleSkill
- algo-price-conjointSkill
- algo-price-dynamicSkill
- algo-price-elasticitySkill
- algo-price-van-westendorpSkill
- algo-rank-bayesianSkill
- algo-rank-eloSkill
- algo-rank-trueskillSkill
- algo-rank-wilsonSkill
- algo-rec-cfSkill
- algo-rec-contentSkill
- algo-rec-hybridSkill
- algo-rec-mfSkill
- algo-rec-sessionSkill
- algo-risk-altman-zSkill
- algo-risk-benfordSkill
- algo-risk-creditSkill
- algo-risk-varSkill
- algo-sc-bullwhipSkill
- algo-sc-eoqSkill
- algo-sc-newsvendorSkill
- algo-sc-routingSkill
- algo-sc-safety-stockSkill
- algo-seo-backlinkSkill
- algo-seo-contentSkill
- algo-seo-crawlSkill
- algo-seo-pagerankSkill
- algo-seo-schemaSkill
- algo-seo-technicalSkill
- algo-seo-tfidfSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 5 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 47
Composite index column order matters: Put the most selective (highest cardinality) column first.
- Distinctive: line 66
Apply fix: Add index, rewrite query, or restructure schema
- Distinctive: line 67
Verify: Run EXPLAIN ANALYZE again — confirm improvement
- Distinctive: line 68
Monitor: Check that fix didn't degrade other queries
- Distinctive: line 72
When tables exceed millions of rows:
- Distinctive: line 102
Indexes have write cost: Every INSERT/UPDATE must update all indexes.
- Very specific: line 103
Statistics can be stale: If EXPLAIN estimates are way off from actuals, run ANALYZE (PostgreSQL) or ANALYZE TABLE (MySQL) to update …
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
SQL Query Optimization
Framework
IRON LAW: Measure Before Optimizing
NEVER guess which query is slow or why. Use EXPLAIN (EXPLAIN ANALYZE in
PostgreSQL) to see the actual execution plan. The database's plan often
differs from what you expect — a query you think is efficient may do
a full table scan, and a complex-looking query may use an index perfectly.
Measure → identify bottleneck → fix → measure again.EXPLAIN Output Reading
Key metrics in EXPLAIN ANALYZE (PostgreSQL):
| Metric | What It Means | Red Flag |
| Seq Scan | Full table scan | On large tables (>100K rows) |
| Index Scan | Using an index | Expected for filtered queries |
| Nested Loop | Join method (row-by-row) | On large tables without index |
| Hash Join | Join method (hash table) | Normal for larger tables |
| Sort | Sorting results | Without index support on large sets |
| Actual Time | Milliseconds for this step | Compare to identify bottleneck |
| Rows | Actual rows processed vs estimated | Large mismatch = stale statistics |
Indexing Strategy
| When to Index | Index Type | Example |
| WHERE clause column | B-Tree (default) | CREATE INDEX idx_user_email ON users(email) |
| JOIN column | B-Tree | CREATE INDEX idx_order_user ON orders(user_id) |
| Composite filter | Composite index | CREATE INDEX idx_order_status_date ON orders(status, created_at) |
| Text search | GIN / Full-text | CREATE INDEX idx_product_name_gin ON products USING gin(name gin_trgm_ops) |
| Range queries | B-Tree | Columns used with BETWEEN, >, < |
Composite index column order matters: Put the most selective (highest cardinality) column first. INDEX(status, date) is good if you always filter by status. INDEX(date, status) is better if you always filter by date range first.
Common Anti-Patterns
| Anti-Pattern | Problem | Fix |
SELECT * | Reads all columns, prevents index-only scans | Select only needed columns |
| Subquery in WHERE | Re-executes for each row | Rewrite as JOIN or CTE |
OR in WHERE | Prevents index use | Rewrite as UNION or separate queries |
| Function on indexed column | WHERE YEAR(date) = 2024 bypasses index | WHERE date >= '2024-01-01' AND date < '2025-01-01' |
| N+1 queries | 1 query for list + N queries for details | JOIN or batch query with IN |
| Missing pagination | Fetching all rows when only showing 20 | LIMIT + OFFSET or keyset pagination |
| Implicit type conversion | WHERE id = '123' (string vs int) | Use correct type: WHERE id = 123 |
Optimization Workflow
- Identify slow queries: Database slow query log (pg_stat_statements, MySQL slow log)
- Run EXPLAIN ANALYZE on the slowest
- Find the bottleneck: Seq Scan on large table? Missing index? Expensive sort?
- Apply fix: Add index, rewrite query, or restructure schema
- Verify: Run EXPLAIN ANALYZE again — confirm improvement
- Monitor: Check that fix didn't degrade other queries
Partitioning (Large Tables)
When tables exceed millions of rows:
| Strategy | How It Works | Best For |
| Range partition | Split by date range (monthly, yearly) | Time-series data, logs |
| Hash partition | Distribute by hash of a column | Even distribution, high-throughput |
| List partition | Split by specific values | Multi-tenant, status-based |
Output Format
# Query Optimization: {Context}
## Slow Query
```sql
{the original slow query}- Execution time: {current ms}
- Rows scanned: {N}
- Problem: {what EXPLAIN revealed}
Fix Applied
{What was changed — new index, query rewrite, etc.}
Result
- Execution time: {original ms} → {optimized ms} ({X% improvement})
- Rows scanned: {original N} → {optimized N}
## Gotchas
- **Indexes have write cost**: Every INSERT/UPDATE must update all indexes. Over-indexing slows writes. Index what you query, not everything.
- **Statistics can be stale**: If EXPLAIN estimates are way off from actuals, run `ANALYZE` (PostgreSQL) or `ANALYZE TABLE` (MySQL) to update statistics.
- **Query cache hides problems**: A query may appear fast because it's cached. Test with cache cleared or cold start.
- **ORM-generated queries**: ORMs (Django, SQLAlchemy, ActiveRecord) generate SQL that may not be optimal. Always inspect the actual SQL for performance-critical paths.
- **Connection pooling**: Sometimes the bottleneck isn't the query but connection overhead. Use connection pooling (PgBouncer, ProxySQL) for high-concurrency applications.
## References
- For PostgreSQL-specific optimization, see `references/pg-optimization.md`
- For CTE vs temp table performance comparison, see `references/cte-vs-temp.md`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.

