agentleFS
jggomezjggomez/expert-ai-developer-skills/skills/sql-query-optimization/SKILL.md

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

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
  1. Very specific:

    Obtain the Actual Plan: Never optimize SQL from reading text alone.

    line 25
  2. Very specific:

    Audit Statistics Freshness: If estimated rows differ from actual rows by orders of magnitude, re-run table statistics analysis (ANALYZE …

    line 33
  3. Very specific:

    Avoid Over-Indexing: Every index adds write overhead during INSERT/UPDATE/DELETE.

    line 38
  4. Distinctive:

    Unwrap Indexed Columns: Never wrap indexed columns in functions.

    line 41

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 ANALYZE in MySQL).
  • Designing single-column and composite indexes to eliminate sequential table scans.
  • Rewriting inefficient SQL patterns (correlated subqueries, function-wrapped index filters, deep OFFSET pagination).

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

  1. Obtain the Actual Plan: Never optimize SQL from reading text alone. Run EXPLAIN ANALYZE with buffer statistics:
    EXPLAIN (ANALYZE, BUFFERS, VERBOSE) <query>;
  2. 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_mem or missing indexes).
  3. 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

  1. Target Filtering Columns: Index columns appearing in WHERE, JOIN ... ON, and ORDER BY clauses.
  2. Composite Index Ordering: Order columns by selectivity: place equality-filtered columns first, followed by range-filtered or sorting columns.
  3. 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

  1. 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'.
  2. 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.
  3. Decorrelate Subqueries: Convert correlated subqueries (which execute once per outer row) into explicit JOINs or CTEs.
  4. 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 ANALYZE plan.
  • Wrapping filtered columns in functions like LOWER(email) or DATE(timestamp) without functional indexes.
  • Using LIMIT 20 OFFSET 50000 for infinite scroll or deep pagination.
  • Adding single-column indexes on every column instead of targeted composite indexes.

Verification

  • Query execution plan obtained via EXPLAIN ANALYZE before and after modifications.
  • Sequential table scans replaced by Index Scans or Index-Only Scans.
  • No functions wrapping indexed columns in WHERE predicates.
  • Deep pagination rewritten using keyset filters (WHERE id > :last_id).

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.