/ai-stuff:postgres-query-tuningfrom ai-stuff
Diagnose and fix a slow PostgreSQL query: read EXPLAIN (ANALYZE, BUFFERS), find bad row estimates and fix them with ANALYZE, statistics targets and CREATE STATISTICS, avoid planner pitfalls (ORDER BY ... LIMIT picking the wrong index, OR vs UNION/ANY, NOT IN, CTE materialization, casts that defeat indexes), choose join and LATERAL rewrites, and handle parallel query, JIT, prepared-statement generic plans, work_mem spills and cost settings. Use when a specific Postgres query is slow or its plan changed.
Ships in ai-stuff. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A playbook distilled from Scaling Postgres. Evidence and version notes are in reference.md. Related skills:
postgres-monitoring.postgres-schema-design.postgres-server-tuning.Reproduce with real data and parameters. Plans on a tiny dev database are meaningless.
EXPLAIN (ANALYZE, BUFFERS, SETTINGS) <query>; -- add SERIALIZE (PG17+) if output is large
For a prepared statement, also test the generic plan:
SET plan_cache_mode = force_generic_plan;.
Find the expensive node. Use inclusive time × loops, and the
buffers read. Most problems sit in one node.
Compare estimated and actual rows at that node. If they're off by 10x or more, fix the estimates before anything else:
ANALYZE on the table, and on the partitioned parent.ALTER TABLE t ALTER COLUMN c SET STATISTICS 1000; ANALYZE t;.CREATE STATISTICS s (dependencies, ndistinct, mcv) ON a, b FROM t;.lower(x) or JSONB keys, create statistics on
the expression (PG14+), or add an expression index.If an index is ignored, check why before changing costs:
Rewrite or add the right index, then re-run step 1 and confirm the plan actually changed.
| Symptom | Fix |
|---|---|
ORDER BY x LIMIT n walks an index on x and filters millions of rows | Composite index (filter_col, x); or stop the sort index being chosen with ORDER BY x + 0 |
a = 1 OR b = 2 gives a seq scan | Separate indexes plus a BitmapOr, or UNION ALL of two indexed queries |
(a > x OR (a = x AND b > y)) keyset filter is slow | Row comparison: (a, b) > (x, y) |
NOT IN (subquery) is slow or wrong with NULLs | NOT EXISTS |
Huge IN (...) lists | = ANY($1::bigint[]) |
| Top-N per group | LATERAL (... ORDER BY ... LIMIT n) against a composite index |
| CTE referenced once is slow | Postgres 12+ inlines it; MATERIALIZED / NOT MATERIALIZED controls it explicitly |
Sort or hash spills to disk (external merge, temp files) | Raise work_mem for that session/role, not globally |
| Fast first runs, slow after 5 executions | Generic plan chosen: plan_cache_mode = force_custom_plan for that path |
| Short OLTP queries pay JIT compile time | jit = off, or raise jit_above_cost |
| Planning time > execution time | Fewer partitions/indexes touched, prepared statements, or pruning that works (stable functions, the key in the WHERE) |
random_page_cost around 1.1. Set
effective_cache_size to the RAM actually available for caching.enable_* switches only per session, to diagnose. Never disable a join
type globally.Workers Launched), and look at
max_parallel_workers_per_gather, plus table size thresholds such as
min_parallel_table_scan_size.pg_hint_plan) and plan pinning are the last resort, after
statistics, indexes and rewrites. Revisit them after every major upgrade.ANALYZE (PG18's pg_upgrade keeps
statistics; earlier versions don't), and recheck key plans.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
25 skills in this plugin
/brainstormingYou MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation./codebase-designShared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary./dispatching-parallel-agentsUse ONLY when the developer has explicitly told you to dispatch subagents — never infer or self-authorize it. Splits 2+ independent tasks across isolated subagents, assigns them cheap models, and polls at a per-harness cadence that preserves prompt cache (Claude Code vs Codex/opencode)./frontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults./grillingGrill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases./handoffCompact the current conversation into a handoff document for another agent to pick up.npx claudepluginhub pauldotsh/ai-stuff --plugin ai-stuff