db-explain
Skill1 starsChanged 26 days agoMITView on GitHub
Use when the user asks why a specific SELECT is slow on their PostgreSQL or MySQL database, wants its plan explained, or asks which index or rewrite would fix it. Read-only: runs plain EXPLAIN (FORMAT JSON), and EXPLAIN ANALYZE only for a SELECT, only with the user's consent and under a timeout, reads index and table statistics for the tables involved, and proposes an index or rewrite as a migration without applying it.
In this repository22 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- new-skillSkill
- review-skillSkill
- db-auditSkill
- db-connection-budgetSkill
- mysql-connectionsSkill
- mysql-indexingSkill
- mysql-keys-and-typesSkill
- mysql-online-ddlSkill
- mysql-query-patternsSkill
- mysql-throughput-per-connectionSkill
- mysql-transactions-and-lockingSkill
- pg-config-by-sizeSkill
- pg-connectionsSkill
- pg-indexingSkill
- pg-keys-and-typesSkill
- pg-observabilitySkill
- pg-online-migrationsSkill
- pg-query-patternsSkill
- pg-throughput-per-connectionSkill
- pg-transactions-and-lockingSkill
- pg-vacuum-and-bloatSkill
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 21
Run
queries/<engine>/00-session.sqlfirst: Stop under the same conditions as /db-skills:db-audit: superuser, a risky role or privilege, … - Very specific: line 35
Never: run ANALYZE or ANALYZE TABLE, change settings with SET GLOBAL, create indexes or extensions, or reset statistics.
- Very specific: line 43
Guard: Run 00-session.sql. Note the version and whether this is a replica.
- Distinctive: line 86
Use the node and field definitions from Using EXPLAIN and EXPLAIN output format.
- Very specific: line 87
Optional what-if (PG): If the hypopg extension is already installed, a hypothetical index plus plain EXPLAIN shows whether the planner …
- Distinctive: line 91
Format: use the repo's migration tool format.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 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.
Files
Explain a query
Purpose
The user gets the plan of one query explained in plain words: where the time or the rows go, why the planner chose that path, and the one change most likely to fix it. That change is either an index, delivered as a migration with its rollback, or a rewrite of the SQL. Each comes with the plan line that proves it worked. Nothing is changed on the database.
Safety
- Read-only is enforced by the database role. Connect with the role from
skills/db-audit/setup/pg-audit-role.sqlorskills/db-audit/setup/mysql-audit-role.sql. The user creates it; you never run setup files.- Privileges:
EXPLAINneeds the same privileges as the statement it explains (MySQL EXPLAIN; Postgres checks table permissions the same way). So this workflow needsSELECTon the tables involved: the optional, consented grant in the setup file. Ask for the narrow per-table grant beforepg_read_all_data. - Why the role: client-side read-only modes are not a boundary. AWS's MCP servers were bypassed through
COPY ... TO PROGRAM(CVE-2026-87911) and SQL comments (CVE-2026-85788). AWS says the role's permissions are the effective limit.
- Privileges:
- Run
queries/<engine>/00-session.sqlfirst. Stop under the same conditions as/db-skills:db-audit: superuser, a risky role or privilege, writable tables, or a session that is not read-only. - Plain EXPLAIN by default. It plans the statement without running it.
EXPLAIN ANALYZEruns the statement. Postgres says the statement is actually executed and its side effects happen as usual (EXPLAIN). MySQL'sEXPLAIN ANALYZEruns the statement too, including multi-tableUPDATEandDELETE(EXPLAIN). Use it only when all of these hold:- The statement is a single
SELECT,WITH ... SELECTwith no data-modifying CTE,TABLEorVALUES. - It has no
FOR UPDATE/FOR SHARE(or other locking clause), noSELECT ... INTO, and calls no function you cannot see is read-only:nextval, advisory locks,dblink, user functions. - The user said yes after seeing the exact statement, the host, whether it is a replica, and the timeout.
- It runs inside
BEGIN READ ONLY/START TRANSACTION READ ONLYwith a statement timeout, and ends inROLLBACK.
In a read-only transaction, Postgres rejects
SELECT ... FOR UPDATEand the timeout cancels a run that is too long. Those are a second guard, not the reason to try.- The statement is a single
- Never
EXPLAIN ANALYZEa write. Not even insideBEGIN ... ROLLBACK: row locks are held until the rollback, triggers fire, and sequences advance. The audit role also cannot plain-EXPLAINa write, because it holds no write privilege. To see how a write finds its rows, explain the equivalentSELECTwith the sameFROMandWHERE. - Literals.
- The user's query and its parameter values may contain personal data. Use real values only in the session, never in the report.
- Plan JSON repeats constants in
Filter,Index Condandattached_condition: replace them with?when you quote plan lines. - The helper files never read
pg_stats.most_common_vals/histogram_boundsor histogram buckets.
- Never run
ANALYZEorANALYZE TABLE, change settings withSET GLOBAL, create indexes or extensions, or reset statistics. When stale statistics are the cause, the report tells the user to runANALYZEthemselves.
Steps
- Get the query. Take it from the argument, or ask. If the user points at code (an ORM call, a query builder), get the SQL it actually sends. Prefer the normalized text from
05-statement-stats.sql(PG) or04-statement-stats.sql(MySQL), or the app's SQL log, over a reconstruction. If the query has parameters:- PG 16+: plan it as a generic plan with
GENERIC_PLAN(EXPLAIN). That option cannot be combined withANALYZE. - Otherwise: ask for representative values, including a common value and a rare one, since they can produce different plans.
- PG 16+: plan it as a generic plan with
- Classify it with the rules in Safety. A write gets rewritten as its row-finding
SELECT. More than one statement means refuse, and ask for one. - Guard. Run
00-session.sql. Note the version and whether this is a replica. - Collect context. List the tables the query reads. Run the helper files after the one allowed edit: replace the table names in the
ARRAY[...]/IN (...)literal, and the fragment in theLIKEpattern.- PG:
01-indexes-for-tables,02-table-stats,03-column-stats,04-planner-settings,05-statement-stats(skip it without pg_stat_statements). - MySQL:
01-indexes-for-tables,02-table-stats,03-planner-settings,04-statement-stats.
- PG:
- Plain plan. Build the statement at run time from the user's query:
- PostgreSQL:
EXPLAIN (FORMAT JSON, SETTINGS) <query>; with parameters on 16+,EXPLAIN (GENERIC_PLAN, FORMAT JSON) <query>. - MySQL:
EXPLAIN FORMAT=JSON <query>; addEXPLAIN FORMAT=TREE <query>when the JSON is hard to read. MySQL 9.x defaults the JSON to layout version 2, which has noaccess_typeorkeyfields; runSET SESSION explain_json_format_version = 1;first so the plan has the fields this workflow reads (explain_json_format_version).
- PostgreSQL:
Measured plan, only with consent. Offer it when estimates and reality may differ, for example a large row-estimate gap or a production mean far from the plan's cost. Show the exact block, then run it only on a yes:
-- PostgreSQL (BUFFERS is automatic on 18; TIMING OFF lowers overhead) BEGIN READ ONLY; SET LOCAL statement_timeout = '5s'; SET LOCAL lock_timeout = '1s'; EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) <select>; ROLLBACK;-- MySQL (EXPLAIN ANALYZE prints TREE format only) SET SESSION max_execution_time = 5000; START TRANSACTION READ ONLY; EXPLAIN ANALYZE SELECT /*+ MAX_EXECUTION_TIME(5000) */ ...; ROLLBACK;A timeout is a finding in itself: report "runs longer than 5 s". Do not raise the timeout without asking.
Read the plan. Find the nodes that hold most of the cost or time, and the row estimates that are wrong by 10x or more. Then match them to a cause:
What the plan shows Likely cause Fix to propose Decision skill PG Seq ScanwithRows Removed by Filterfar above rows returned; MySQLaccess_type: ALL, highrows_examined_per_scan, lowfilteredno index for the filter composite index: equality columns first, then the range or sort column pg-indexing / MySQL indexing skill Index Scanfollowed by aFilterthat drops most rows; MySQLused_key_partsshorter than the indexwrong column order, or a range before an equality column reorder or extend the index pg-indexing Sortwithexternal merge Disk; MySQLusing_filesorton a large row countno index delivers the order, or sort memory is too small index matching WHERE+ORDER BY; else a per-rolework_mempg-indexing, pg-config-by-size HashwithBatches> 1; MySQLusing_temporary_tablespillinghash or temp table larger than memory reduce rows earlier, or raise memory per role pg-config-by-size Nested Loopwith manyloopson an innerSeq Scanmissing index on the join column index the inner table's join column (often an FK) pg-indexing Limitabove a largeOffset, or a sort of every row for the first pageOFFSET pagination keyset pagination on an indexed key pg-query-patterns Filter on lower(col),col::text,date(col); MySQL comparing a string column with a numberfunction or type mismatch hides the index rewrite to compare the bare column, or an expression index pg-indexing, pg-query-patterns Index Only Scanwith highHeap Fetchesvisibility map stale, vacuum behind autovacuum tuning for the table pg-vacuum-and-bloat Estimate far from actual on correlated columns planner assumes independence CREATE STATISTICSon the columns (docs), then the user runsANALYZEpg-observability Estimate far from actual and n_mod_since_analyzehigh orlast_analyzeoldstale statistics the user runs ANALYZE <table>; check autovacuum settingspg-vacuum-and-bloat Large JITtime on a short queryJIT cost above the query's own cost jit = offfor the OLTP rolepg-config-by-size Use the node and field definitions from Using EXPLAIN and EXPLAIN output format. A fix must remove most of the cost, not 10%. If no index or rewrite does that, say so and point to the data model or caching.
- Optional what-if (PG). If the
hypopgextension is already installed, a hypothetical index plus plainEXPLAINshows whether the planner would use the proposed index. It is session-local and builds nothing (hypopg). Installing the extension is DDL: suggest it, do not do it. - Write the fix.
- Postgres index:
SET lock_timeout = '5s'; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...outside a transaction (CREATE INDEX). Rollback:DROP INDEX CONCURRENTLY IF EXISTS .... - MySQL index:
SET SESSION lock_wait_timeout = 5; ALTER TABLE t ADD INDEX ix (...), ALGORITHM=INPLACE, LOCK=NONE(online DDL). Rollback:ALTER TABLE t DROP INDEX ix. - Format: use the repo's migration tool format. Create the file only if the user asks.
- Rewrite: show the before and after SQL, and where in the code it changes.
- Postgres index:
- Report in the format below.
Output
Query: <redacted, normalized text> Engine: <engine version>, <primary|replica>
Plan: <estimated (EXPLAIN) | measured (EXPLAIN ANALYZE, with consent)> Parameters: <generic plan | sample values, not shown>
Production: <calls, mean, max from pg_stat_statements / digest summary, or "not available">Where the cost is: the 1–3 nodes that matter, quoting plan lines with constants redacted:
| Node | Table / index | Estimated rows | Actual rows | Share of cost or time | Problem |
Findings: ordered by impact:
| # | Severity | Finding | Evidence | Related skill | Proposed migration or rewrite (rollback) | How to verify |
| E1 | HIGH | orders filtered by customer_id and sorted by created_at with no matching index | Seq Scan on orders, Rows Removed by Filter: 2,400,000 per call; mean 48 ms over 2.1M calls | pg-indexing | CREATE INDEX CONCURRENTLY orders_customer_created_idx ON orders (customer_id, created_at) (rollback DROP INDEX CONCURRENTLY orders_customer_created_idx) | plain EXPLAIN shows Index Scan using orders_customer_created_idx with no Sort; mean_exec_time falls after deploy |
The row above is an example of the format.
After the table, give the full migration or rewrite, the write cost of the new index (one more index to maintain on every insert, and on every update of its columns), and anything the user must run themselves, such as ANALYZE. Write the report to a Markdown file in the repo only if the user asks.
When not to use
- The user wants a health check of the whole database, not one query: use
/db-skills:db-audit. - The query is fast alone but slow under load because of lock waits or connection queuing: the plan will look fine. Use
/db-skills:db-audit(sessions and lock waits) or/db-skills:db-connection-budget. - The statement is an
INSERT,UPDATE,DELETEor DDL and the user wants it measured: this workflow will not execute it. Measure it on a staging copy the user controls. - The audit role has no
SELECTon the tables and the user declines the grant:EXPLAINcannot plan the query. Ask for an explain from someone with access, or use a staging copy. - The tables on the connected instance are much smaller than production, as on a laptop or fresh staging: the planner will choose differently. Explain against production or a replica.
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
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.

