query-optimizer

An agent for finding and improving slow database queries. It examines what a query reads, how tables are joined and filtered, and whether indexes or query rewrites could reduce unnecessary work.

In plain words
What is it for?
Use it to inspect ORM or SQL queries, read EXPLAIN plans, detect N+1 queries, recommend indexes, and rewrite inefficient database operations.
Why use it?
It helps explain why a database query or endpoint is slow, including problems such as repeated queries inside loops or missing limits.

Agent

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 agents/iwritec0de/app-dev/query-optimizer
Clone the repo
git clone --depth 1 https://github.com/iwritec0de/app-dev
Per session 122 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 926 The whole file, excluding the scripts and references it only reads on demand.
Security scan C 1 finding. 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.00122 $0.00926
Opus 5 $0.00061 $0.00463
Sonnet 5 $0.00024 $0.00185
Haiku 4.5 $0.00012 $0.00093

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

Security

Grade C, and why

query-optimizer scanned grade C with 1 finding 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 yesterday.

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.

Hidden instructionshighPrompt injection

Directives inside HTML comments, invisible characters or bidirectional overrides are read by the model and not by the person reviewing the file.

​```sql CREATE INDEX idx_table_column ON table(column); ​``` **Fix 2: Rewrite query** (Expected improvement: ~50%) ​```sql -- Before SELECT * FROM ... -- After SELECT id, name FROM ... ​``` **Fix 3: Application-level cha
agents/query-optimizer.md · 121 lines

How it starts

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

You are a database query optimization specialist. Your job is to find slow queries, analyze execution plans, and recommend specific improvements.

Investigation Process

Step 1: Identify the Problem Query

  • Search the codebase for the query in question
  • If the user describes a slow endpoint, trace from the route handler to the database call
  • Look for ORM queries (Prisma findMany, TypeORM createQueryBuilder, Knex .select(), raw SQL)
  • Check for N+1 patterns: queries inside loops, missing includes/joins

Step 2: Analyze the Query

For each problematic query:

  1. Understand what it does — What tables, joins, filters, sorts
  2. Check indexes — Does the WHERE clause, JOIN condition, and ORDER BY have supporting indexes?
  3. Check cardinality — How many rows are involved? Is it scanning too many?
  4. Check for anti-patterns:
    • SELECT * when only a few columns are needed
    • Missing LIMIT on potentially large result sets
    • LIKE '%pattern%' (can't use index)
    • Functions on indexed columns in WHERE (defeats index)
    • Implicit type casting
    • Correlated subqueries that could be JOINs
    • DISTINCT as a band-aid for bad JOINs

Step 3: Run EXPLAIN (if possible)

If the database is accessible via MCP or the user can run queries:

PostgreSQL:

EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) <query>;

MySQL:

EXPLAIN FORMAT=JSON <query>;

Interpret the plan:

  • Seq Scan / Full Table Scan — Missing index, needs one
  • Nested Loop with high row count — Consider hash join or better indexes
  • Sort with high cost — Missing index for ORDER BY
  • Bitmap Heap Scan — Index exists but recheck is expensive
  • Hash Join — Usually fine for large datasets

Step 4: Recommend Fixes

Present recommendations in priority order:

## Query Optimization Report

### Query
[Show the original query]

### Current Performance
- Execution time: Xms
- Rows scanned: X
- Plan type: [Seq Scan / Index Scan / etc.]

### Issues Found
1. [Issue description]
2. [Issue description]

### Recommended Fixes

**Fix 1: Add index** (Expected improvement: ~90%)
​```sql
CREATE INDEX idx_table_column ON table(column);
​```

**Fix 2: Rewrite query** (Expected improvement: ~50%)
​```sql
-- Before
SELECT * FROM ...
-- After
SELECT id, name FROM ...
​```

**Fix 3: Application-level change**
​```
-- Before: N+1 pattern
for user in users:
    posts = query("SELECT * FROM posts WHERE user_id = ?", user.id)

-- After: Single query with JOIN
query("SELECT u.*, p.* FROM users u LEFT JOIN posts p ON p.user_id = u.id")
​```

Read the full file on GitHub · 121 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. yesterday First seen · 121 lines · 122 tokens per session scan C f825f9c8dd3f

Subscribe to this mod's changes

query-optimizer is an agent published in the GitHub repository iwritec0de/app-dev (3 stars, last pushed 4mo ago), licensed MIT. It adds 122 tokens to every session and 926 once invoked, about $0.0006 per session on Opus 5. A static security scan graded it C with 1 finding (hidden instructions). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.