optimize-postgres-query
Installation
SKILL.md
Optimize a Postgres Query
Every change ships with two pieces of evidence: an EXPLAIN ANALYZE comparison showing it is faster, and an A/B test showing it returns identical results. A faster query that returns different rows is a bug, not an optimization.
Input
A description of the slow query, a pg_stat_statements row, an EXPLAIN plan, or a file:line in the codebase.
Phase 1: Find it and measure it
- Get the SQL. Given code, trace the ORM call to the SQL it generates (enable query logging or use the ORM's
toSQL()). Given SQL, grep the codebase for the code that builds it. - Get real parameters. Query the database for 3+ real values (ids, slugs, date ranges) that exercise the slow path, including the heaviest case you can find. Made-up parameters produce made-up plans.
- Baseline. Run with those parameters, against production or a production-sized copy:
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) <query with real params>;EXPLAIN ANALYZEexecutes the statement. ForINSERT/UPDATE/DELETE, wrap it inBEGIN; … ROLLBACK;. - Record execution time, shared buffers hit/read, scan types,
Rows Removed by Filter,loops=on inner nodes, and estimated vs actual rows on each node.