sql-query-optimization
Skill28 starsChanged 3 months agoApache-2.0View on GitHub
Diagnoses and rewrites slow SQL on traditional engines (Postgres, MySQL, SQL Server, etc.) using EXPLAIN/EXPLAIN ANALYZE — indexing strategy, WHERE clause selectivity, avoiding functions on indexed columns, JOIN vs. subquery vs. CTE tradeoffs, and pagination. Use for any query slowness outside BigQuery, or when a query needs an index.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- justanesta/claude-code-resourcestheir own version, first seen Jan 20, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- justanesta/claude-code-resources★ 2same 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 repository34 other files it gives its agents.
- bigquery-query-optimizationSkill
- build-and-ci-gatesSkill
- cdc-scd-patternsSkill
- code-implementerSkill
- code-smells-expertSkill
- commit-expertSkill
- compliance-verifierSkill
- context-captureSkill
- context-restoreSkill
- database-migration-expertSkill
- design-spec-expertSkill
- documentation-expertSkill
- flutter-architecture-decisionsSkill
- flutter-performance-profilingSkill
- flutter-release-engineeringSkill
- flutter-review-checklistSkill
- flutter-senior-orchestrationSkill
- flutter-test-strategySkill
- flutter-upgrade-migrationSkill
- gcp-data-engineeringSkill
- guidelines-karpathySkill
- loop-engineeringSkill
- performance-scalabilitySkill
- product-analystSkill
- pull-request-expertSkill
- python-expertSkill
- qa-testerSkill
- refactoring-code-expertSkill
- repo-researchSkill
- security-auditSkill
- senior-architect-engineeringSkill
- senior-dev-orchestratorSkill
- test-driven-developmentSkill
- testing-expertSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 1 is distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
Obtain the Actual Plan: Never optimize SQL from reading text alone.
- Very specific: line 33
Audit Statistics Freshness: If estimated rows differ from actual rows by orders of magnitude, re-run table statistics analysis (ANALYZE …
- Very specific: line 38
Avoid Over-Indexing: Every index adds write overhead during INSERT/UPDATE/DELETE.
- Distinctive: line 41
Unwrap Indexed Columns: Never wrap indexed columns in functions.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 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 Skill
Overview
This skill diagnoses, profiles, and optimizes slow SQL queries across traditional relational database engines (PostgreSQL, MySQL, SQL Server, SQLite, Oracle). It acts as a Database Performance Engineer operating under the mandate: always start from the execution plan, never from intuition. It analyzes EXPLAIN ANALYZE outputs, designs targeted composite indexes, rewrites inefficient subqueries, and implements keyset pagination.
When to Use
Trigger Scenarios
- Query latency spikes, timeout errors, or high database CPU usage on traditional RDBMS instances.
- Analyzing execution plans (
EXPLAIN (ANALYZE, BUFFERS)in Postgres,EXPLAIN ANALYZEin MySQL). - Designing single-column and composite indexes to eliminate sequential table scans.
- Rewriting inefficient SQL patterns (correlated subqueries, function-wrapped index filters, deep
OFFSETpagination).
When NOT to Use
- Google Cloud BigQuery queries: Route to
bigquery-query-optimization(which uses a distributed columnar slot-based model). - Database schema migrations and DDL lock safety: Route to
database-migration-expert. - Application-level caching architecture: Route to
performance-scalability.
Process
Phase 1: Execution Plan Diagnostics
- Obtain the Actual Plan: Never optimize SQL from reading text alone. Run
EXPLAIN ANALYZEwith buffer statistics:EXPLAIN (ANALYZE, BUFFERS, VERBOSE) <query>; - Locate Bottleneck Nodes:
- Sequential Scans (Seq Scan) on large tables where an index scan was expected.
- Hash / Nested Loop Joins with massive differences between estimated and actual row counts.
- External Sorts / Hash Aggregates spilling to disk (indicates low
work_memor missing indexes).
- Audit Statistics Freshness: If estimated rows differ from actual rows by orders of magnitude, re-run table statistics analysis (
ANALYZE <table>;) before changing the query.
Phase 2: Indexing Strategy
- Target Filtering Columns: Index columns appearing in
WHERE,JOIN ... ON, andORDER BYclauses. - Composite Index Ordering: Order columns by selectivity: place equality-filtered columns first, followed by range-filtered or sorting columns.
- Avoid Over-Indexing: Every index adds write overhead during
INSERT/UPDATE/DELETE. Create covering indexes only when high read frequency justifies it.
Phase 3: Query Rewriting Patterns
- Unwrap Indexed Columns: Never wrap indexed columns in functions.
- Anti-pattern:
WHERE DATE(created_at) = '2026-09-01'(disables index scan). - Optimized:
WHERE created_at >= '2026-09-01' AND created_at < '2026-09-02'.
- Anti-pattern:
- Keyset Pagination vs. OFFSET: Replace deep offsets (
OFFSET 50000) with keyset pagination (WHERE id > :last_seen_id ORDER BY id ASC LIMIT 20) to eliminate scanning discarded rows. - Decorrelate Subqueries: Convert correlated subqueries (which execute once per outer row) into explicit
JOINs or CTEs. - Column Pruning: Eliminate
SELECT *to allow the engine to use Index-Only scans without reading heap pages.
Phase 4: Empirical Verification
Re-run EXPLAIN ANALYZE after applying index or query changes. Confirm the planner chose the index scan and that total execution time and buffer read counts dropped.
Usage
CLI Invocations
# PostgreSQL explain plan
psql -d mydb -c "EXPLAIN (ANALYZE, BUFFERS) SELECT id, email FROM users WHERE created_at >= '2026-01-01' LIMIT 50;"
# MySQL explain plan
mysql -u root -p -e "EXPLAIN ANALYZE SELECT id, email FROM users WHERE status = 'active';"Example Prompts
- "Run EXPLAIN ANALYZE on this Postgres query and tell me why it's performing a sequential scan."
- "Rewrite this paginated query to use keyset pagination instead of LIMIT/OFFSET."
- "Design a composite index for this multi-column filter on status, tenant_id, and created_at."
Host Execution Instructions
- Claude Code: Request or inspect the execution plan output in the shell before proposing SQL rewrites.
- Antigravity: Analyze SQL query plans, apply unwrapping rules, and verify execution metrics.
Red Flags
- Suggesting indexes without reviewing an
EXPLAIN ANALYZEplan. - Wrapping filtered columns in functions like
LOWER(email)orDATE(timestamp)without functional indexes. - Using
LIMIT 20 OFFSET 50000for infinite scroll or deep pagination. - Adding single-column indexes on every column instead of targeted composite indexes.
Verification
- Query execution plan obtained via
EXPLAIN ANALYZEbefore and after modifications. - Sequential table scans replaced by Index Scans or Index-Only Scans.
- No functions wrapping indexed columns in
WHEREpredicates. - Deep pagination rewritten using keyset filters (
WHERE id > :last_id).
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.

