Agent skill

SQL Optimizer

by Mathews-Tom in Mathews-Tom/armory

Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans.

MITAuto-check passedDatabases

Install SQL Optimizer

skills CLI
$ npx skills add Mathews-Tom/armory --skill sql-optimizer -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install Mathews-Tom/armory sql-optimizer --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/Mathews-Tom/armory.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/sql-optimizer .claude/skills/sql-optimizer && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
sql-optimizer
GitHub stars
327
Token cost
~2.3k tokens
SKILL.md length
786 words
Files
6 (incl. references)
Skills in repo
80
Repo updated
First seen
Licence
MIT

At a glance

Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans.

  • Works in 5 steps: Query Analysis → EXPLAIN Interpretation → Anti-Pattern Detection → …
  • : optimize this query
  • SKILL.md covers Reference Files, Prerequisites, Workflow and Output Format, plus 4 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

SQL Optimizer is an agent skill from Mathews-Tom/armory. Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans. Interprets EXPLAIN, detects anti-patterns, rewrites queries. Triggers on: "optimize this query", "slow query", "add indexes", "explain plan", "N+1 query", "why is this query slow".

Its SKILL.md is about 2.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 7 other files, including reference files (for example `evals/cases.yaml`, `references/anti-patterns.md` and `references/explain-guide.md`).

It sits in Databases, covering SQL and Query optimization. It works with SQL. The repository describes itself as: Curated, production-grade skills for AI coding agents. Battle-tested workflows for developers who use AI seriously. The licence is MIT.

When your agent uses it

  • : optimize this query
  • Why is this query slow

Example prompts

  • “optimize this query”
  • “slow query”
  • “add indexes”
  • “/sql-optimizer”

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Query Analysis
  2. EXPLAIN Interpretation
  3. Anti-Pattern Detection
  4. Optimization
  5. Output

What it can do on your machine

Read from SKILL.md and the folder at commit 4594fb7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are mardkown).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

SQL Optimizer loads about 2.3k tokens when it runs, and up to ~7.6k if it reads all its reference files. Until then it costs about 73 tokens; SKILL.md has 786 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~73
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~7.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from Mathews-Tom/armory at commit 4594fb7, republished under its MIT licence (© Mathews-Tom). 786 words, ~2,296 tokens.

Download SKILL.mdSave it as .claude/skills/sql-optimizer/SKILL.md (or your agent's skills folder). This skill also uses 5 other files; get the full folder from GitHub.
name
sql-optimizer
description
Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans. Interprets EXPLAIN, detects anti-patterns, rewrites queries. Triggers on: "optimize this query", "slow query", "add indexes", "explain plan", "N+1 query", "why is this query slow".
metadata.version
1.1.1
metadata.category
data
metadata.tags
sql, performance, database, optimization
metadata.difficulty
intermediate
metadata.phase
build

SQL Optimizer

Systematic SQL performance analysis: parse query structure, interpret EXPLAIN plans, detect anti-patterns (N+1, full scans, cartesian joins), recommend indexes, and rewrite queries — with explanations of WHY each change improves performance, not just WHAT changed.

Reference Files

FileContentsLoad When
references/anti-patterns.mdCommon SQL anti-patterns with detection rules and fixesAlways
references/index-strategies.mdIndex type selection, composite index ordering, covering indexesIndex recommendations needed
references/explain-guide.mdReading EXPLAIN output for PostgreSQL, MySQL, SQLiteEXPLAIN plan provided
references/join-optimization.mdJoin type selection, join order optimization, subquery-to-join conversionQuery contains joins or subqueries

Prerequisites

  • The SQL query to optimize
  • Database engine (PostgreSQL, MySQL, SQLite) — optimization differs by engine
  • Table schemas and approximate row counts (helpful but not required)
  • EXPLAIN output (highly valuable when available)

Workflow

Phase 1: Query Analysis

Parse the SQL to understand its structure:

  1. Identify operations — SELECT columns, FROM tables, JOIN conditions, WHERE filters, GROUP BY, ORDER BY, HAVING, subqueries.
  2. Map table relationships — Which tables are joined? On what keys? Are there implicit cartesian products?
  3. Detect immediate red flags:
    • SELECT * — fetching unnecessary columns
    • Functions on indexed columns in WHERE — prevents index use
    • OR in WHERE — often prevents index use
    • Correlated subqueries — potential N+1
    • Missing WHERE on DELETE/UPDATE — dangerous
Phase 2: EXPLAIN Interpretation

If an EXPLAIN plan is provided:

  1. Scan types — Sequential Scan (bad for large tables), Index Scan (good), Index Only Scan (best), Bitmap Index Scan (acceptable).
  2. Join methods — Nested Loop (good for small tables), Hash Join (good for equi-joins), Merge Join (good for sorted data).
  3. Row estimates — Compare estimated rows with actual rows. Large discrepancies indicate stale statistics (ANALYZE).
  4. Cost hotspots — Highest-cost node is the bottleneck. Optimize there first.
  5. Sort operations — External sorts (disk) are expensive. Consider indexes that match ORDER BY.
Phase 3: Anti-Pattern Detection

Check for known performance anti-patterns (see references/anti-patterns.md):

PatternDetectionImpact
SELECT *Star in select listTransfers unnecessary data
N+1 queriesLoop with query insideN additional roundtrips
Function on indexed columnWHERE UPPER(name) = 'X'Index bypass
Implicit type castString compared to integerIndex bypass
Missing join conditionCartesian productExponential rows
LIKE '%prefix'Leading wildcardFull scan
OR with different columnsWHERE a=1 OR b=2Index bypass
SELECT DISTINCT as band-aidHides duplicate-producing joinFix the join instead
Phase 4: Optimization
  1. Index recommendations — Based on WHERE, JOIN, ORDER BY, GROUP BY columns. Consider composite indexes for multi-column conditions.
  2. Query rewrite — Convert correlated subqueries to JOINs, replace IN (SELECT...) with EXISTS, use CTEs for readability without performance cost (PostgreSQL 12+ may inline CTEs).
  3. Schema suggestions — Denormalization, materialized views, partitioning (mention only when query-level optimization is insufficient).
Phase 5: Output

Present the original query, detected issues, recommended indexes, rewritten query, and explanation of each change.

Output Format

mardkown
## SQL Optimization Analysis

### Original Query
```sql
{original SQL}
```

### Issues Detected

| #   | Issue   | Severity          | Location            | Impact           |
| --- | ------- | ----------------- | ------------------- | ---------------- |
| 1   | {issue} | {High/Medium/Low} | {WHERE/JOIN/SELECT} | {what it causes} |

### EXPLAIN Interpretation

{If EXPLAIN provided}

- **Bottleneck:** {node type} on `{table}` (cost: {N})
- **Rows scanned:** {N} (estimated {M})
- **Index used:** {name or "None"}
- **Key insight:** {what this reveals}

### Recommended Indexes

```sql
-- {Reason for this index}
CREATE INDEX {name} ON {table}({columns});
```

### Optimized Query

```sql
{rewritten query}
```

### Change Explanation

1. **{Change}** — {Why this improves performance. Include estimated impact.}

### Expected Improvement

- Scan type: {before} → {after}
- Estimated rows scanned: {before} → {after}
- Index usage: {before} → {after}
Show full SKILL.md (334 more words)Show less

Configuring Scope

ModeInputDepthWhen to Use
quickSingle queryAnti-pattern scan + index suggestionFast feedback during development
standardQuery + schemaFull analysis with rewritesDefault for optimization requests
deepQuery + EXPLAIN + schema + row countsFull analysis with statistics validationProduction performance investigation

Calibration Rules

  1. Measure before optimizing. Request EXPLAIN output before recommending changes. Intuition about query performance is unreliable — a "slow-looking" query may be fast with proper indexes, and a "simple" query may scan millions of rows.
  2. Index discipline. Every index has write overhead. Do not recommend indexes that won't be used by the actual query workload. Consider the read/write ratio.
  3. Explain WHY, not just WHAT. "Add an index on users.email" is incomplete. "Add an index on users.email because the WHERE clause filters by email, currently causing a sequential scan of 1M rows" is actionable.
  4. Preserve correctness. Query rewrites must return identical results. If a rewrite changes semantics (e.g., INNER JOIN vs LEFT JOIN), flag it explicitly.
  5. Database engine matters. PostgreSQL, MySQL, and SQLite have different optimizers, index types, and capabilities. Always target the specific engine.

Error Handling

ProblemResolution
No EXPLAIN output providedAnalyze query structure and anti-patterns. Note that recommendations are best-effort without EXPLAIN.
Unknown database engineAsk which engine. Default anti-pattern analysis applies to all engines.
Query uses ORM-generated SQLOptimize the SQL, then suggest ORM-level changes (e.g., select_related in Django, eager loading).
Schema not providedInfer table structure from the query. Note assumptions.
Query is already optimalState that no significant improvements are possible. Suggest non-query optimizations (caching, denormalization).
Complex multi-CTE queryAnalyze each CTE independently, then analyze the composition.

When NOT to Optimize

Push back if:

  • The query runs infrequently and performance is acceptable (one-time admin query)
  • The optimization requires schema changes that affect many consumers — suggest an ADR instead
  • The real problem is application-level (N+1 from ORM loop) — fix the application code, not the SQL
  • The query is auto-generated by a tool (ORM migration, BI tool) — optimize at the tool level

© Mathews-Tom, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 5 other files (references) in skills/sql-optimizer of Mathews-Tom/armory.

  • SKILL.md
  • evals/cases.yaml
  • references/anti-patterns.md
  • references/explain-guide.md
  • references/index-strategies.md
  • references/join-optimization.md

Open the folder on GitHubat commit 4594fb7

Compare with similar skills

SQL Optimizer next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

SQL Optimizer compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
SQL Optimizer this skillMathews-Tom/armory327—~2.3kAutomated safety check: PassMIT
SQL Optimization Patternsynulihao/AgentSkillOS61710 repos~3.3kAutomated safety check: PassNone
Query Engine Designrevfactory/claude-code-harness120—~474Automated safety check: PassNone
SQL Optimization Patternssickn33/agentic-awesome-skills47k1 repos~566Automated safety check: PassMIT
SQL Database Assistantborghei/Claude-Skills874—~1.5kAutomated safety check: PassMIT
SQL Optimization InterviewerPrepLabsAI/InterviewMentor112—~2.1kAutomated safety check: PassMIT

Similar skills

  • SQL Optimization Patterns

    ynulihao/AgentSkillOS

    Master SQL query optimization, indexing strategies, and EXPLAIN analysis to dramatically improve database performance and eliminate slow queries.

    617 GitHub starsUsed in 10 repos~3.3k tokens
    DatabasesAuto-check passed
  • Query Engine Design

    revfactory/claude-code-harness

    SQL query engine design and implementation guide. An agent skill from revfactory/claude-code-harness.

    120 GitHub stars~474 tokensUpdated 7 mo ago
    DatabasesAuto-check passed
  • SQL Optimization Patterns

    sickn33/agentic-awesome-skills

    Diagnose slow SQL with query plans, preserve query results, and verify indexing or query changes against representative data.

    47k GitHub starsUsed in 1 repo~566 tokens
    DatabasesAuto-check passed
  • SQL Database Assistant

    borghei/Claude-Skills

    This skill should be used when the user asks to "optimize SQL queries", "explore database schemas", "generate migration SQL", "analyze query performance", or "document database structure".

    874 GitHub stars~1.5k tokensUpdated today
    DatabasesAuto-check passed
  • SQL Optimization Interviewer

    PrepLabsAI/InterviewMentor

    A Data Engineering interviewer focused on database performance.

    112 GitHub stars~2.1k tokensUpdated today
    DatabasesAuto-check passed
  • Writing SQL

    rileyhilliard/claude-essentials

    Staff+ DBA SQL patterns targeting what Claude's defaults miss - multi-column statistics, operator classes, keyset pagination, silent performance anti-patterns.

    130 GitHub stars~627 tokensUpdated 1 mo ago
    DatabasesAuto-check passed

More from Mathews-Tom/armory

All 80 skills in this repo
  • Architecture Reviewer

    Mathews-Tom/armory

    Architecture reviews across 7 dimensions (structural, scalability, enterprise readiness, performance, security, ops, data) with scored reports.

    327 GitHub stars~4.6k tokensUpdated yesterday
    Auto-check passed
  • Concept To Image

    Mathews-Tom/armory

    Turn concepts into static HTML visuals exported as PNG or SVG files via HTML/CSS/SVG.

    327 GitHub stars~2.6k tokensUpdated yesterday
    Auto-check passed
  • Watch

    Mathews-Tom/armory

    A skill your agent uses when analyzing an existing video URL or local recording: "watch this video", "analyze youtube video", "summarize this video", "youtube transcript", "find this moment", "what…

    327 GitHub stars~2.8k tokensUpdated yesterday
    Auto-check passed
  • Code Refiner

    Mathews-Tom/armory

    Deep code simplification and refactoring preserving behavior across Python, Go, TypeScript, Rust.

    327 GitHub stars~3.1k tokensUpdated yesterday
    Auto-check passed
  • Concept To Video

    Mathews-Tom/armory

    Turn concepts into animated explainer videos using Manim (Python) with MP4/GIF output, audio overlay, multi-scene composition.

    327 GitHub stars~4.9k tokensUpdated yesterday
    Auto-check passed
  • Decision Map

    Mathews-Tom/armory

    Maps the unresolved architecture, policy, and scope decisions that must be answered before planning can start: one durable decision ticket per question on the issue tracker, typed and blocker-linked…

    327 GitHub stars~2.7k tokensUpdated yesterday
    Auto-check passed

Works with

Categories

Questions about SQL Optimizer

What does SQL Optimizer do?

Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans. SQL Optimizer is an agent skill from Mathews-Tom/armory. Analyzes SQL queries for missing indexes, N+1 patterns, suboptimal joins, and full table scans.

When should I use SQL Optimizer?

SQL Optimizer fits situations like: : optimize this query; why is this query slow.

How do I install SQL Optimizer in Claude Code?

Run `npx skills add Mathews-Tom/armory --skill sql-optimizer -a claude-code`. Or copy the skill folder (skills/sql-optimizer in Mathews-Tom/armory) into .claude/skills/sql-optimizer in your project. Claude Code loads it when a task matches its description.

How do I install SQL Optimizer in Codex?

Run `npx skills add Mathews-Tom/armory --skill sql-optimizer -a codex`. Or copy the skill folder (skills/sql-optimizer in Mathews-Tom/armory) into .agents/skills/sql-optimizer in your project. Codex loads it when a task matches its description.

Can I use SQL Optimizer in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add Mathews-Tom/armory --skill sql-optimizer -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/sql-optimizer, .gemini/skills/sql-optimizer, .github/skills/sql-optimizer and .opencode/skills/sql-optimizer in your project.

What does SQL Optimizer need to run?

SKILL.md names no scripts, command-line tools or credentials: SQL Optimizer is instructions for the agent only.

Does SQL Optimizer access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is SQL Optimizer safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does SQL Optimizer use?

SQL Optimizer is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does SQL Optimizer use?

About 2.3k tokens (SKILL.md is roughly 9.2k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 5.3k tokens, read only when the agent opens those files.

What are the alternatives to SQL Optimizer?

Skills that share tags, products or a category with SQL Optimizer: SQL Optimization Patterns (ynulihao/AgentSkillOS, 617 stars), Query Engine Design (revfactory/claude-code-harness, 120 stars), SQL Optimization Patterns (sickn33/agentic-awesome-skills, 47k stars) and SQL Database Assistant (borghei/Claude-Skills, 874 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains SQL Optimizer?

Mathews-Tom (a GitHub user) maintains it in Mathews-Tom/armory, which has 327 GitHub stars. The repository holds 80 skills in this directory. The repository was last updated on October 6, 2026.

Source: Mathews-Tom/armory on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.