Detect n plus one
detect_n_plus_oneIdentify N+1 query loops in PostgreSQL by analyzing pg_stat_statements: hundreds of calls returning few rows, sorted by total time. Thresholds tunable. Results are candidates for investigation.
Instructions
Surface query templates in pg_stat_statements that look like an N+1 loop: hundreds of calls, each returning at most a row or two, with meaningful total wall-clock time spent. Returns the candidates sorted by total time descending so the worst offender appears first. Thresholds (min_calls, max_rows_per_call, min_total_ms) are tunable. Treat results as candidates for investigation, NOT verdicts — a hot cache-miss pattern on a primary-key lookup can trip the same shape. Reports availability=false if pg_stat_statements is not installed.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| database | No | Optional: target a configured secondary (read-only) database by name; omit for the primary. Call list_databases to see the configured ids. | |
| min_calls | No | ||
| min_total_ms | No | ||
| max_rows_per_call | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| available | Yes | ||
| candidates | Yes | ||
| thresholds | Yes |