sql-optimization-patterns
Skill36 starsChanged 6 months agoMITView on GitHub
Transforms slow PostgreSQL queries into fast operations through systematic EXPLAIN ANALYZE, indexing strategies, N+1 elimination, cursor pagination, and materialized views. Use when diagnosing slow queries, optimizing database performance, or designing index strategies — always profile before optimizing.
10 other projects use a version of this.
Adopted by
Most recently taken up by
- enes9103/my-claude-agents-skillstheir own version, first seen Sep 28, 2026
- socialadsmentor/sam-agentic-harnesstheir own version, first seen Sep 3, 2026
- TheHiddenDeveloper/jarvis-skillstheir own version, first seen Aug 19, 2026
- dallay/agents-skillstheir own version, first seen Aug 13, 2026
- tranhieutt/software_development_departmenttheir own version, first seen Apr 30, 2026
- scops/sql-optimization-patternstheir own version, first seen Apr 2, 2026
Other versions10 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 10
- tranhieutt/software_development_department★ 72same name
- xfstudio/skills★ 9same name
- Harmeet10000/skills★ 7same name
- scops/sql-optimization-patterns★ 4same name
- socialadsmentor/sam-agentic-harness★ 4same name
- ai4brands-design/claude-skills★ 2same name
- CodeWithBehnam/cc-docs★ 2same name
- dallay/agents-skills★ 2same name
- enes9103/my-claude-agents-skills★ 0same name
- TheHiddenDeveloper/jarvis-skills★ 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 repository157 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- a2ui-angularSkill
- accessibility-auditSkill
- adk-deploy-guideSkill
- adk-dev-guideSkill
- adk-eval-guideSkill
- adk-observability-guideSkill
- agentic-ai-coding-standardSkill
- agentic-ai-devSkill
- ai-auditSkill
- ai-chatSkill
- ai-decision-recordSkill
- ai-incident-responseSkill
- ai-launch-checkSkill
- ai-playbookSkill
- angular-best-practicesSkill
- angularSkill
- angular-spaSkill
- angular-ui-patternsSkill
- api-design-principlesSkill
- app-store-optimizationSkill
- architect-reviewSkill
- architecture-decision-recordsSkill
- architecture-designSkill
- asc-cli-usageSkill
- asc-crash-triageSkill
- asc-id-resolverSkill
- asc-release-flowSkill
- asc-signing-setupSkill
- asc-submission-healthSkill
- asc-testflight-orchestrationSkill
- browser-testingSkill
- changelog-generatorSkill
- claude-actions-auditorSkill
- clean-codeSkill
- codebase-onboardingSkill
- code-explainerSkill
- code-reviewerSkill
- code-simplifierSkill
- comment-analyzerSkill
- database-schema-designerSkill
- ddd-architectSkill
- decision-frameworksSkill
- dedup-code-agentSkill
- deployment-ci-cdSkill
- design-systemSkill
- dockerSkill
- documentation-generationSkill
- domain-finderSkill
- error-detectiveSkill
- eval-guideSkill
- feature-forgeSkill
- firebase-basicsSkill
- firebase-hosting-basicsSkill
- fixing-accessibilitySkill
- fixing-motion-performanceSkill
- flutter-animationsSkill
- flutter-genuiSkill
- flutter-mobileSkill
- flutter-security-expertSkill
- The first 60 shown.
The file
Files
Iron Law
PROFILE BEFORE OPTIMIZING — RUN EXPLAIN (ANALYZE, BUFFERS) ON THE ACTUAL SLOW QUERY BEFORE WRITING A SINGLE INDEX
When to Use This Skill
- Debugging slow-running queries in PostgreSQL
- Endpoint response times exceeding target SLA
- Designing performant database schemas for high-traffic tables
- Reducing database load and infrastructure costs
- Resolving N+1 query problems from ORM usage (SQLAlchemy, Prisma, R2DBC)
- Analyzing EXPLAIN query plans from production
- Implementing efficient composite and partial indexes
- Migrating from OFFSET pagination to cursor-based pagination
Do Not Use This Skill When
- You need cloud-native SQL or analytics platforms (BigQuery, Snowflake) — use
sql-pro - You need schema migration design — use
database-schema-designer - The database is not PostgreSQL (patterns are PostgreSQL-specific)
Quick Reference
| Problem | Diagnosis | Fix |
| Slow endpoint | EXPLAIN (ANALYZE, BUFFERS) — look for Seq Scan | Add index on WHERE/JOIN columns |
| N+1 queries | Count DB calls per request > 1 | JOIN + eager load or batch query |
| Slow pagination | OFFSET on large table | Cursor-based pagination |
| Slow aggregation | GROUP BY without index | Partial index + filter before GROUP BY |
| Slow COUNT(*) | Full table count | pg_class.reltuples estimate or index-only count |
| Repeated expensive query | Same query hits DB repeatedly | Materialized view + scheduled refresh |
| Large table slow scans | Millions of rows, date filter | Table partitioning by date range |
Process
Step 1 — Identify the Slow Query
-- Find the top-10 slowest queries by mean execution time
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;Step 2 — Profile with EXPLAIN
-- Always use ANALYZE + BUFFERS for real data
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.id, u.email, COUNT(o.id) AS order_count
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days'
GROUP BY u.id, u.email;Key nodes to watch:
Seq Scanon large table → add indexIndex Scan→ good;Index Only Scan→ bestNested Loopon large tables → may need Hash JoinHash Batches > 1→ memory spill, increasework_memRowsestimate far fromActual Rows→ runANALYZE <table>
Step 3 — Apply the Right Fix
See resources/implementation-playbook.md for SQL code for each pattern.
Step 4 — Verify Improvement
-- Re-run EXPLAIN ANALYZE after index/change
-- Compare: Execution Time before vs after
-- Compare: Seq Scan → Index Only ScanOptimization Patterns (Summary)
Load resources/implementation-playbook.md for full SQL code examples.
| Pattern | When | Speedup |
| Composite index | Multi-column WHERE/ORDER BY | 10x–100x |
| Partial index | Filtered subset (e.g., active users) | 5x–50x |
| Covering index | Avoid table heap access | 2x–10x |
| Cursor pagination | Replace OFFSET 100000 | 100x+ |
| N+1 elimination | ORM loop → single JOIN | N× → 1 query |
| Materialized view | Repeated expensive aggregation | 100x+ |
| Batch operations | Individual inserts/updates in loop | 10x–50x |
| Table partitioning | Time-series or date-range tables >10M rows | 5x–20x |
Stack Integration
Python / FastAPI (asyncpg + SQLAlchemy)
- N+1 → use
selectinloadorjoinedloadin SQLAlchemy async - Batch insert →
execute_manywith asyncpg - Slow query → enable
echo=Trueon engine to capture SQL, then EXPLAIN
NestJS / Prisma
- N+1 → use Prisma
include: { orders: true }instead of loop queries - Raw SQL →
prisma.$queryRawfor complex optimized queries - Slow endpoint → enable Prisma query logging, identify the statement
Java / Spring Boot WebFlux (R2DBC)
- N+1 → use
DatabaseClientwith JOIN query instead of reactive loop - Batch → R2DBC
executeBatch()method - Slow query → enable R2DBC logging, capture SQL for EXPLAIN
Anti-Patterns
- Creating indexes without running
EXPLAIN ANALYZEfirst - Function in WHERE clause preventing index use:
WHERE LOWER(email) = ?— use expression index LIKE '%term'with leading wildcard — cannot use B-Tree index; use GIN +pg_trgm- Over-indexing: each index slows INSERT/UPDATE/DELETE — only index proven slow paths
OFFSET 100000pagination on large tables — always replace with cursor- Individual row inserts in a loop — always batch
Documentation Sources
- PostgreSQL EXPLAIN: Query MCP context7 with library ID
/postgresql/postgresql pg_stat_statements: Query MCP context7
Reference Files
resources/implementation-playbook.md— Full SQL code for all 8 optimization patterns, EXPLAIN annotation guide, monitoring queries
Related Skills
sql-pro— Cloud analytics, HTAP, dimensional modeling, BigQuery/Snowflakedatabase-schema-designer— Schema design, migration patterns, FK/index rulesvector-database— pgvector HNSW/IVFFlat index alignmentpython-dev— SQLAlchemy async, asyncpg patternsjava-spring-api— R2DBC reactive database accessnestjs-api— Prisma ORM, raw query patterns
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.

