galihcitta/dotclaudeskills/optimizing-queries
- community
Checking that the SKILL.md file is still in the repository.
Analyzes and optimizes SQL/NoSQL queries for performance. Use when reviewing query performance, optimizing slow queries, analyzing EXPLAIN output, suggesting indexes, identifying N+1 problems, recommending query rewrites, or improving database access patterns. Supports PostgreSQL, MySQL, SQLite, MongoDB, Redis, DynamoDB, and Elasticsearch.
Install
npx vskill@latest install galihcitta/dotclaudeskills/optimizing-queriesSKILL.md
Query Optimization
Analyze database queries and provide actionable optimization recommendations.
Workflow
Copy and track progress:
- Identify database type from syntax or user context
- Analyze query structure - parse SELECT, FROM, WHERE, JOIN, ORDER BY, GROUP BY clauses
- Check for red flags (see Quick Reference)
- Provide concrete recommendations with copy-pasteable code
- Suggest verification - EXPLAIN command or metric to confirm
For complex queries (3+ JOINs or nested subqueries):
- Decompose into logical units
- Analyze each unit's access pattern
- Synthesize recommendations in priority order
Analysis Checklist
For each query, evaluate:
- Index usage: Missing or inefficient indexes
- Scan type: Full scans on large tables
- Join efficiency: Join order, type, missing conditions
- Filtering: WHERE placement, function usage on columns
- Projection: SELECT * vs specific columns
- Pagination: OFFSET vs keyset/cursor
- N+1 detection: Loop patterns in code context
Quick Reference
SQL Red Flags
SELECT *on large tablesWHERE function(column)prevents index useLIKE '%pattern'(leading wildcard)ORconditions spanning different columns- Large
OFFSETvalues NOT INwith nullable subquery- Missing
LIMITon unbounded queries
NoSQL Red Flags
- MongoDB: COLLSCAN,
$where, unbounded arrays - Redis:
KEYS *, missing TTL, wrong data structure - DynamoDB: Scan operations, hot partitions
- Elasticsearch: Deep pagination, wildcard prefix
Examples
Example 1: Missing Index
Input:
Output:
Example 2: N+1 Query Pattern
Input:
Output:
Example 3: When NOT to Optimize
Input:
Output:
Example 4: Incomplete Information
Input:
Output:
Example 5: MongoDB COLLSCAN
Input:
Output:
Response Format
Structure recommendations as:
Confidence Levels
When uncertainty exists, indicate confidence:
- HIGH: Pattern clearly matches known anti-pattern
- MEDIUM: Likely issue, depends on data distribution/schema
- LOW: Potential issue, needs EXPLAIN to confirm
Response Constraints
- Max 5 recommendations per query - prioritize by impact
- Order by severity: HIGH → MEDIUM → LOW
- One primary fix per issue - mention alternatives briefly
- Code must be copy-pasteable - no placeholders like
<table_name> - Verification commands must be complete - include all flags
Prioritization Matrix
| Issue Type | Impact | Priority | |
|---|---|---|---|
| Missing JOIN index | Query blocks | P0 | |
| Full table scan (>100k rows) | Slow response | P0 | |
| N+1 pattern | Latency × N | P1 | |
| SELECT * | Memory/bandwidth | P1 | |
| Missing LIMIT | Resource exhaustion | P1 | |
| Large OFFSET | Slow pagination | P2 | |
| Suboptimal ORDER BY | Sort overhead | P2 |
Reference Files
Consult these for detailed patterns (use grep to find specific sections):
references/sql-patterns.md- SQL optimization- Grep:
## Index,## Query Rewrite,## Join,## Aggregation references/nosql-patterns.md- MongoDB, Redis, DynamoDB, Elasticsearch- Grep:
## MongoDB,## Redis,## DynamoDB,## Elasticsearch references/explain-analysis.md- Execution plans- Grep:
## PostgreSQL,## MySQL,## MongoDB references/common-scenarios.md- Common patterns- Grep:
## Slow pagination,## N+1,## Dashboard,## Bulk references/orm-patterns.md- ORM fixes- Grep:
### Django,### SQLAlchemy,### ActiveRecord,### Prisma
Utility Scripts
All scripts use Python standard library only (no pip install required).
Run these for automated analysis:
Query Analysis
analyze_query.py - Detect anti-patterns and score complexity:
suggest_index.py - Generate index recommendations:
EXPLAIN & Logs
parse_explain.py - Analyze EXPLAIN output:
diff_explain.py - Compare before/after EXPLAIN outputs:
parse_slow_log.py - Analyze slow query logs:
Schema & Code
analyze_schema.py - Find schema optimization opportunities:
detect_orm_issues.py - Find ORM anti-patterns in code:
check_migration.py - Check migration safety:
Workflow with Scripts
For query optimization:
analyze_query.py→ detect issuessuggest_index.py→ generate indexes- User runs EXPLAIN (before)
- User applies optimization
- User runs EXPLAIN (after)
diff_explain.py→ verify improvement
For verifying optimization impact:
For codebase audit:
detect_orm_issues.py --dir ./→ find N+1 patternsanalyze_schema.py→ check schema- Prioritize fixes by severity
For migration review:
check_migration.py→ safety check- Fix critical issues before deployment
- Use safe alternatives (CONCURRENTLY, etc.)
EXPLAIN Commands
Provide appropriate commands:
Index Recommendation Format
When suggesting indexes:
Handling Missing Information
When user provides incomplete context:
No schema provided:
"To give precise recommendations, I need the table schema. Could you share:1. Column data types2. Existing indexes3. Approximate row countsMeanwhile, here's what I can infer from the query..."
No EXPLAIN output:
"Run this command and share the output:```sqlEXPLAIN (ANALYZE, BUFFERS) <their query>;```This will show actual vs estimated rows and scan types."
Unknown database type:
"Which database are you using? (PostgreSQL, MySQL, SQLite, MongoDB, etc.)The optimization strategies differ significantly between them."
Conditional Workflows
Analyzing a query:
- Run
analyze_query.pyfirst - Check for anti-patterns
- Suggest fixes with examples
Interpreting EXPLAIN output:
- Run
parse_explain.pywith appropriate flag - Identify warnings
- Correlate with query structure
Full optimization request:
- Analyze query → identify issues
- Suggest indexes → generate CREATE statements
- Request EXPLAIN → interpret results
- Provide before/after comparison
Complex optimization (3+ issues or architectural decisions): Use extended reasoning to:
- Map full query execution path
- Identify all optimization opportunities
- Evaluate trade-offs between approaches
- Prioritize by impact and implementation cost
Script Error Handling
If scripts fail:
- Check Python version (requires 3.7+)
- Verify input format (SQL string, valid file path)
- Fall back to manual analysis using reference files
Common errors:
FileNotFoundError→ Check file path, use absolute pathsjson.JSONDecodeError→ Input not valid JSON, check --pg/--mysql flags- Empty output → Query may be valid, no issues detected
When scripts are unavailable: Perform manual analysis using Quick Reference red flags and reference files.
Unsupported Databases
For databases not explicitly covered (Oracle, SQL Server, CockroachDB, etc.):
- Apply general SQL patterns from
references/sql-patterns.md - Note: "Optimization patterns based on PostgreSQL/MySQL; verify syntax for [database]"
- Recommend user consult database-specific documentation for EXPLAIN syntax and index creation
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/optimizing-queries/SKILL.md
Popularity
- Repository stars
- 6
- 7-day trend score
- 10
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 25 Mar 2026, 7 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/galihcitta/dotclaudeskills/optimizing-queries)