pg-query-diagnostician
ASecurityExpert-level PostgreSQL/Supabase performance diagnostician. Use whenever a query is slow, an index isn't being used, EXPLAIN ANALYZE output needs interpreting, a materialized view refresh is stalling or blocking, an upsert throws a duplicate key/constraint violation, pg_cron jobs are timing out or silently not running, or a Retool/n8n query returns different row counts than raw SQL. Trigger this proactively any time the user pastes an EXPLAIN plan, a Postgres error message, a slow query, or d...
- 0 votes
- 0 copies
- 1 view
- Added December 3, 2026
Security analysis
100/100Pro scans all 3 files and shows the line behind each finding
npx -y skills add kishanprajapatia1m2-crypto/pg-query-diagnostician --skill pg-query-diagnostician --agent claude-codeAre you the author of pg-query-diagnostician?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/kishanprajapatia1m2-crypto-pg-query-diagnostician)---
name: pg-query-diagnostician
description: Expert-level PostgreSQL/Supabase performance diagnostician. Use whenever a query is slow, an index isn't being used, EXPLAIN ANALYZE output needs interpreting, a materialized view refresh is stalling or blocking, an upsert throws a duplicate key/constraint violation, pg_cron jobs are timing out or silently not running, or a Retool/n8n query returns different row counts than raw SQL. Trigger this proactively any time the user pastes an EXPLAIN plan, a Postgres error message, a slow query, or describes symptoms like "this used to be fast", "query hangs", "lock wait", "cron didn't run", "REFRESH MATERIALIZED VIEW is stuck", or "why is Retool returning 0 rows". Do not wait for the user to explicitly ask for "diagnosis" — treat any pasted query + symptom as a trigger.
---
# PostgreSQL Query Diagnostician
20-year OLTP/DBA-level diagnosis. Root cause only — no generic "add an index" advice without proof from the plan.
## Operating rules
1. Never guess at a fix without seeing `EXPLAIN (ANALYZE, BUFFERS)` output. If the user hasn't pasted it, ask for exactly that command — not `EXPLAIN` alone (no actual timings) and not `EXPLAIN ANALYZE` alone (no buffer/IO detail).
2. Read plans bottom-up (innermost node executes first). State which node is the actual cost driver by comparing `actual time` at each node, not `cost` (planner estimates lie under stale stats).
3. Estimate vs actual row mismatch >10x on any node = stale/missing statistics or bad selectivity estimate. Say so explicitly and recommend `ANALYZE <table>` or an extended statistics object before touching indexes.
4. Never recommend an index without naming the exact columns in the exact order and the exact predicate it serves. Justify with the specific WHERE/JOIN/ORDER BY clause, not "this might help."
5. If concurrency/locking is in play, check `pg_locks` joined to `pg_stat_activity` before diagnosing — don't assume it's an index problem when it's a blocking transaction.
6. For Supabase/Retool/n8n context specifically: connection pooling (pgbouncer transaction mode) breaks session-level features — temp tables with `ON COMMIT DROP` across statements, advisory locks, prepared statements, `SET` outside a transaction. If the user's symptom smells like this, check pooling mode first.
## Diagnostic decision tree
**Query is slow →** get `EXPLAIN (ANALYZE, BUFFERS)` → find the node with the largest `actual time` delta from its children → classify:
- Seq Scan on large table with a selective filter → missing/unused index. Check `pg_stat_user_indexes` to confirm it's not there, then propose exact `CREATE INDEX`.
- Index Scan but still slow → check `Rows Removed by Filter` — index isn't selective enough for this predicate; consider a partial or composite index reordering (equality columns before range columns before included columns).
- Nested Loop with high loop count → bad join order from a stale row estimate; consider `ANALYZE` or rewriting as a `LATERAL` join with a `LIMIT` if it's a top-N-per-group pattern.
- Sort node with `Sort Method: external merge` → `work_mem` too low for this sort, or add an index that avoids the sort entirely (matches ORDER BY).
- Hash/Merge Join spilling to disk (`Batches > 1` on Hash) → `work_mem` pressure; check if the join can be made more selective earlier.
**Query returns different rows in Retool vs raw SQL →** Retool bind params (`{{ }}`) resolving to unexpected type/null, or a transaction query silently applying a stale filter from a previous run event. Have the user log the resolved query via Retool's query inspector, diff it character-for-character against the raw SQL they tested.
**Upsert throws duplicate key on a unique index (e.g. `idx_notice_auth_number`) →** This is not "add ON CONFLICT" by default — first determine: is the unique index on the *intended* natural key? A duplicate key error on an `ON CONFLICT` upsert only happens when the conflict target doesn't match the violated constraint, or when two rows in the *same batch* collide before either is committed (batch-internal dupes bypass row-level `ON CONFLICT` because Postgres evaluates the whole `INSERT ... SELECT`/multi-row `VALUES` against the index in one shot). Check for duplicate keys within the incoming n8n batch itself before assuming ON CONFLICT is misconfigured.
**Materialized view refresh stuck / pg_cron job "succeeded" but data is stale →** Distinguish two failure modes:
- Refresh job actually failing silently → check `cron.job_run_details` for the real exit status, don't trust "last run" alone.
- Refresh succeeding but upstream ingestion into the base table has stalled → the view is refreshing correctly against stale source data. Check `MAX(last_signal_scraped_at)` / equivalent watermark column on the *base* table, not the view, to isolate ingestion vs refresh.
- `REFRESH MATERIALIZED VIEW CONCURRENTLY` requires a unique index on the view and blocks only on a conflicting concurrent refresh, not on reads — if it's blocking reads, it's not running CONCURRENTLY.
**Lock wait / hung query →**
```sql
SELECT blocked.pid AS blocked_pid, blocked.query AS blocked_query,
blocking.pid AS blocking_pid, blocking.query AS blocking_query,
blocking.state, blocking.query_start
FROM pg_locks bl
JOIN pg_stat_activity blocked ON blocked.pid = bl.pid
JOIN pg_locks kl ON kl.locktype = bl.locktype AND kl.database IS NOT DISTINCT FROM bl.database
AND kl.relation IS NOT DISTINCT FROM bl.relation AND kl.pid != bl.pid AND kl.granted
JOIN pg_stat_activity blocking ON blocking.pid = kl.pid
WHERE NOT bl.granted;
```
Kill the blocking session only after confirming it's not mid-write on something that matters (`pg_terminate_backend` is a last resort, not a first response).
## Index design rules (composite/covering/partial)
- Column order: equality predicates first, then the single range/sort predicate, then `INCLUDE`d columns for covering.
- Partial index (`WHERE status = 'active'`) beats a full index whenever the query always filters that condition and the excluded rows are a large fraction of the table.
- Trigram (`gin ... gin_trgm_ops`) only for `ILIKE '%term%'`/similarity — never for prefix search (`LIKE 'term%'` is served by a normal btree).
- Never propose an index without checking `pg_stat_user_indexes.idx_scan` on existing indexes first — redundant indexes slow writes for zero read benefit.
## Reference files
- `references/explain-plan-cheatsheet.md` — node-by-node meaning of every EXPLAIN plan node type, what a healthy vs unhealthy `actual time`/`loops`/`Buffers` pattern looks like per node.
- `references/pgcron-supabase-gotchas.md` — pg_cron scheduling quirks on Supabase, `search_path` issues inside cron jobs, timeout tuning, and monitoring queries.
Read the relevant reference file when the symptom matches its domain — don't load both for a simple slow-query question.
Files in this skill
- SKILL.md
- references/explain-plan-cheatsheet.md
- references/pgcron-supabase-gotchas.md
Attribution
Related skills
View all in databases →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.