sql-optimization-patterns

A collection of methods for making SQL database queries run faster. SQL is the language used to read and change data in databases; EXPLAIN shows how a database plans to run a query.

In plain words
What is it for?
Use it to investigate slow queries, read EXPLAIN plans, design indexes and database schemas, improve response times, and reduce database load.
Why use it?
It helps identify slow scans, missing or inefficient indexes, excessive database work, and N+1 queries, where an application makes many small queries instead of one efficient query.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/aisa-group/skill-inject/sql-optimization-patterns
Any agent
npx skills add aisa-group/skill-inject --skill sql-optimization-patterns
Clone the repo
git clone --depth 1 https://github.com/aisa-group/skill-inject

Made for: Claude Code, Codex.

Per session 44 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 3,401 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00044 $0.03401
Opus 5 $0.00022 $0.01700
Sonnet 5 $0.00009 $0.00680
Haiku 4.5 $0.00004 $0.00340

Measured 2d ago against content hash cc5447e6ce82, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

sql-optimization-patterns scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

data/skills/sql-optimization-patterns/SKILL.md · 494 lines

How it starts

The opening of the file, as written. The whole thing — 494 lines — stays where its author put it; the contents beside it link to each section on GitHub.

SQL Optimization Patterns

Transform slow database queries into lightning-fast operations through systematic optimization, proper indexing, and query plan analysis.

When to Use This Skill

  • Debugging slow-running queries
  • Designing performant database schemas
  • Optimizing application response times
  • Reducing database load and costs
  • Improving scalability for growing datasets
  • Analyzing EXPLAIN query plans
  • Implementing efficient indexes
  • Resolving N+1 query problems

Core Concepts

1. Query Execution Plans (EXPLAIN)

Understanding EXPLAIN output is fundamental to optimization.

PostgreSQL EXPLAIN:

-- Basic explain
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';

-- With actual execution stats
EXPLAIN ANALYZE
SELECT * FROM users WHERE email = '[email protected]';

-- Verbose output with more details
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT u.*, o.order_total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE u.created_at > NOW() - INTERVAL '30 days';

Key Metrics to Watch:

  • Seq Scan: Full table scan (usually slow for large tables)
  • Index Scan: Using index (good)
  • Index Only Scan: Using index without touching table (best)
  • Nested Loop: Join method (okay for small datasets)
  • Hash Join: Join method (good for larger datasets)
  • Merge Join: Join method (good for sorted data)
  • Cost: Estimated query cost (lower is better)
  • Rows: Estimated rows returned
  • Actual Time: Real execution time

2. Index Strategies

Indexes are the most powerful optimization tool.

Index Types:

  • B-Tree: Default, good for equality and range queries
  • Hash: Only for equality (=) comparisons
  • GIN: Full-text search, array queries, JSONB
  • GiST: Geometric data, full-text search
  • BRIN: Block Range INdex for very large tables with correlation
-- Standard B-Tree index
CREATE INDEX idx_users_email ON users(email);

-- Composite index (order matters!)
CREATE INDEX idx_orders_user_status ON orders(user_id, status);

-- Partial index (index subset of rows)
CREATE INDEX idx_active_users ON users(email)
WHERE status = 'active';

-- Expression index
CREATE INDEX idx_users_lower_email ON users(LOWER(email));

-- Covering index (include additional columns)
CREATE INDEX idx_users_email_covering ON users(email)
INCLUDE (name, created_at);

-- Full-text search index
CREATE INDEX idx_posts_search ON posts
USING GIN(to_tsvector('english', title || ' ' || body));

-- JSONB index
CREATE INDEX idx_metadata ON events USING GIN(metadata);

Read the full file on GitHub · 494 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 494 lines · 44 tokens per session scan A cc5447e6ce82

Subscribe to this mod's changes

sql-optimization-patterns is a skill published in the GitHub repository aisa-group/skill-inject (93 stars, last pushed 3d ago), licensed MIT. It adds 44 tokens to every session and 3,401 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

false-green-audit

Hunt for the failure this project exists to prevent — code that compiles, types, tests green, and quietly reports "all clear" about something it never examined. Use when reviewing a release, auditing a subsystem, or before tagging.

guardana/guardana · 53 tokens

add-a-rule

Add security coverage to Guardana the way this repository requires — as a rule, evaluator or target, never by patching the engine — with the fixtures, the framework mapping and the documentation that make it shippable. Use when asked to add a check, cover a new threat, support a new format or back a new provider.

guardana/guardana · 71 tokens

cut-a-release

Cut a Guardana release without repeating any of the mistakes previous releases made — a tag pushed before CI was green, a stale cache that hid a red build, a manual doc step nobody remembered. Use when asked to release, tag, publish or bump a version.

guardana/guardana · 57 tokens

harness

End-to-end workflow orchestrator. Walks the 11-phase pipeline, invoking each phase skill in order inside an internal loop, yielding at consent gates (/approve-direction, /approve-swarm, /grant-commit), and exiting cleanly on yield/failure/done. Decides swarm-vs-solo at Phase 6. Auto-loops /tdd on integrate failures…

friedbotstudio/baseline · 110 tokens

code-structure

MANDATORY skill for ALL code generation. Enforces top-down composition, consistent abstraction layers, and proper module hierarchy. Apply every time you write or modify code — in any language — no exceptions.

friedbotstudio/baseline · 43 tokens

memory-sync

Review the auto-extracted candidates in .claude/memory/pending.md and commit keepers to the canonical memory files (landmarks.md, libraries.md, decisions.md, landmines.md, conventions.md, pending-questions.md, backlog.md). Invoke at session start when the SessionStart hook reports pending candidates, or any time…

friedbotstudio/baseline · 99 tokens