agentleFS
mDevsLabsmDevsLabs/Skills/skills/sql-query-optimizer/SKILL.md

sql-query-optimizer

Skill2 starsChanged 4 months agoMITView on GitHub

Diagnoses and rewrites slow SQL queries by reading execution plans, spotting anti-patterns, and proposing indexes, rewrites and schema changes with an estimated impact for each. Use when a query is slow, a report times out, a database is CPU- or IO-bound, or someone asks for help with EXPLAIN output, indexing strategy or query tuning on PostgreSQL, MySQL, SQL Server, Oracle, SQLite, BigQuery, Snowflake or DuckDB.

6 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

10 rules. 0 are common, 7 are distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 5 edited versions we read keep these.

  • 7

    Distinctive

    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. Distinctive:

    Use for slow SELECTs, timeouts, lock contention, runaway DML, plan regressions, index design, and reviewing SQL before it ships.

    line 21
  2. Distinctive:

    Do not use for: writing a query from scratch (that is authoring, not tuning), ORM configuration debugging, or infrastructure sizing.

    line 24
  3. Distinctive:

    Never optimise blind. Ask for whatever is missing, but proceed with assumptions clearly labelled if the user cannot supply it:

    line 31
  4. Distinctive:

    Before reasoning about the plan, catch the mechanical defects:

    line 58
  5. Very specific:

    Add covering columns (INCLUDE in PG/SQL Server) to enable index-only scans.

    line 113
  6. Very specific:

    Use partial indexes for skewed predicates: WHERE status = 'pending'.

    line 114
  7. Distinctive:

    Every index costs write throughput and storage — state the tradeoff explicitly.

    line 115
  8. Distinctive:

    Verify the index is actually used after creation.

    line 116
  9. Very specific:

    Use CONCURRENTLY (PG) or ONLINE=ON (SQL Server) to avoid blocking prod.

    line 117
  10. Distinctive:

    Before adding, check for a redundant prefix of an existing index.

    line 118

“Common” is measured: kept by at least 6 in 10 of the 5 edited versions of this file we could read. “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 Optimizer

Turn "this query is slow" into a ranked, evidence-backed remediation plan.

When to use

Use for slow SELECTs, timeouts, lock contention, runaway DML, plan regressions, index design, and reviewing SQL before it ships.

Do not use for: writing a query from scratch (that is authoring, not tuning), ORM configuration debugging, or infrastructure sizing.

Workflow

1. Gather context before theorising

Never optimise blind. Ask for whatever is missing, but proceed with assumptions clearly labelled if the user cannot supply it:

InputWhy it matters
Engine + versionPlan syntax, optimiser features, hint availability
Full query textHidden subqueries and functions dominate cost
EXPLAIN (ANALYZE, BUFFERS) or equivalentActual vs estimated rows is the single best signal
Table row counts and sizesDistinguishes "needs an index" from "needs a rewrite"
Existing indexesPrevents recommending a duplicate
Frequency + SLAA 2 s query run 10 000×/min matters more than a 5 min nightly job
Read/write ratioConstrains how many indexes are acceptable

Plan commands by engine:

EngineCommand
PostgreSQLEXPLAIN (ANALYZE, BUFFERS, VERBOSE, FORMAT TEXT) <query>
MySQL 8+EXPLAIN ANALYZE <query> / EXPLAIN FORMAT=JSON <query>
SQL ServerSET STATISTICS IO, TIME ON + actual execution plan
OracleEXPLAIN PLAN FOR … then DBMS_XPLAN.DISPLAY_CURSOR(format=>'ALLSTATS LAST')
SQLiteEXPLAIN QUERY PLAN <query>
BigQueryExecution details tab / INFORMATION_SCHEMA.JOBS
SnowflakeQuery Profile / GET_QUERY_OPERATOR_STATS

2. Run the static linter first

Before reasoning about the plan, catch the mechanical defects:

python3 scripts/sql_lint.py query.sql --dialect postgres --format md

It flags the anti-patterns in the catalogue below, reports query complexity, and proposes a candidate composite index using the equality → range → sort ordering. Its output is a set of leads: a static rule cannot know your data distribution, so confirm everything against a real plan.

3. Read the plan top-down, cost bottom-up

Find the operator that dominates actual time, not estimated cost. Then check:

  • Cardinality misestimation — actual rows ≫ or ≪ estimated rows (>10× off). Root cause is usually stale statistics, correlated predicates, or a function wrapping a column.
  • Scan type — Seq/Full scan on a large table with a selective predicate.
  • Join strategy — Nested loop over a large outer input; hash join spilling to disk; merge join forcing an expensive sort.
  • Materialisation — sorts, hash aggregates, or CTEs spilling to temp files.
  • Row multiplication — a join fan-out that inflates rows before filtering.

4. Match against the anti-pattern catalogue

Anti-patternSymptomFix
Non-sargable predicateWHERE YEAR(created_at)=2025, WHERE col+0=5, leading LIKE '%x'Rewrite as a range: created_at >= '2025-01-01' AND created_at < '2026-01-01'; or add an expression index
Implicit type castIndex ignored on a varchar column compared to a numberMatch types, or cast the literal not the column
SELECT *Wide rows, no covering index possible, network costProject only needed columns
OR across columnsFull scan instead of index usageSplit into UNION ALL branches, or add a composite/partial index
Correlated subquery in SELECTExecuted once per outer rowRewrite as a LEFT JOIN on a pre-aggregated derived table
DISTINCT masking a fan-outHuge intermediate rowcountFix the join grain; aggregate before joining
IN (SELECT …) with NULLsNOT IN returns nothing / can't optimiseUse NOT EXISTS or LEFT JOIN … IS NULL
Offset paginationOFFSET 100000 scans and discardsKeyset pagination: WHERE (sort_key, id) > (:k, :id) ORDER BY … LIMIT n
Function on join keyHash join impossibleStore a normalised/computed column and index it
Over-wide ORDER BY + LIMITFull sort of the result setIndex matching the sort order so the sort is eliminated
Missing predicate pushdownFilter applied after a large aggregation/CTEMove filters into the CTE/subquery; in PG <12 CTEs are optimisation fences — use MATERIALIZED/NOT MATERIALIZED deliberately
Row-by-row DML in a loopN round-tripsSet-based single statement or batched INSERT … SELECT
Warehouse full-partition scanBigQuery/Snowflake bytes-scanned is hugeAdd a partition filter + clustering key; avoid SELECT *

5. Design indexes deliberately

Order composite index columns as equality → range → sort/include:

-- WHERE tenant_id = ? AND status = ? AND created_at >= ? ORDER BY created_at DESC
CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created
  ON orders (tenant_id, status, created_at DESC);

Rules:

  • One well-ordered composite index beats three single-column indexes.
  • Add covering columns (INCLUDE in PG/SQL Server) to enable index-only scans.
  • Use partial indexes for skewed predicates: WHERE status = 'pending'.
  • Every index costs write throughput and storage — state the tradeoff explicitly.
  • Verify the index is actually used after creation; do not assume.
  • Use CONCURRENTLY (PG) or ONLINE=ON (SQL Server) to avoid blocking prod.
  • Before adding, check for a redundant prefix of an existing index.

6. Escalate only if rewrites and indexes are not enough

In order of increasing cost: refresh statistics → increase work_mem/sort memory → materialised view or summary table → denormalisation → partitioning → caching layer → sharding. Never propose sharding as a first response.

7. Report

Deliver a table of recommendations, each with: change, rationale tied to a plan line, estimated speedup, risk, and rollback. Provide runnable DDL/SQL, and always tell the user to re-run EXPLAIN ANALYZE to verify.

Tools

ScriptUse
scripts/sql_lint.pyStatic anti-pattern detection, complexity metrics and candidate index DDL
python3 scripts/sql_lint.py query.sql --dialect postgres --format md
echo "SELECT * FROM t WHERE YEAR(d)=2025" | python3 scripts/sql_lint.py --min-severity high

Exit code 1 means at least one critical/high finding — usable as a CI gate on checked-in SQL.

Worked example

Query

SELECT * FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE YEAR(o.created_at) = 2025
  AND c.country = 'FR'
ORDER BY o.created_at DESC
LIMIT 50;

Plan finding — Seq Scan on orders (12.4 M rows, actual 8.1 s), then hash join, then top-N sort. Estimated 1 200 rows, actual 486 000 rows.

Diagnosis

  1. YEAR(o.created_at) is non-sargable → no index can be used.
  2. SELECT * pulls 41 columns, preventing an index-only scan.
  3. The sort runs after the join over ~486 k rows.

Fix

CREATE INDEX CONCURRENTLY idx_orders_created_customer
  ON orders (created_at DESC) INCLUDE (customer_id, total_amount, status);
CREATE INDEX CONCURRENTLY idx_customers_country_id
  ON customers (country, id);

SELECT o.id, o.created_at, o.total_amount, o.status, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= DATE '2025-01-01'
  AND o.created_at <  DATE '2026-01-01'
  AND c.country = 'FR'
ORDER BY o.created_at DESC
LIMIT 50;

Result — index scan walks created_at DESC and stops early; sort eliminated. 8.1 s → ~15 ms. Cost: two indexes, ~180 MB, small write penalty on orders.

Quality checklist

  • sql_lint.py run and every finding either fixed or explicitly dismissed
  • Every recommendation cites a specific line/operator of the plan
  • Rewrites are semantically identical (NULL handling, duplicates, ordering)
  • No index recommended that duplicates an existing prefix
  • Write-path cost of new indexes stated
  • Engine-specific syntax is correct for the stated version
  • Verification step (EXPLAIN ANALYZE re-run) included
  • Destructive or blocking operations flagged with a safe alternative

Failure modes

SituationResponse
No plan availableGive the ranked hypotheses, ask for EXPLAIN ANALYZE, do not assert a fix
Query is already optimalSay so; redirect to schema, hardware or caching
Plan regression after a version upgradeCompare plans, check statistics and optimiser flags before rewriting
Slowness is not the queryCheck lock waits, connection pool saturation, IO throttling, cold cache

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.

Reviews can't be read right now.

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.