Why the slow log does not show it#
A slow-query log, whether PostgreSQL's log_min_duration_statement or a provider's query insights, lists statements that individually cross a threshold. A loop that runs a 12 ms query 540 times never crosses it. The request still spends seconds in the database, plus a network round trip per call, plus whatever the application does with each answer.
pg_stat_statements groups tracked statements by database, role, normalized query identifier and top-level status. Its calls, total_exec_time and block counters only grow, so the difference between two readings is the work done in between. If that interval holds one request, the difference is that request's query profile.
The lab#
The lab needs Docker and runs in a few seconds. The extension has to be preloaded, so the container starts with an extra setting.
docker run -d --rm --name pl-a-pgss-diff -e POSTGRES_PASSWORD=x postgres:18 \
-c shared_preload_libraries=pg_stat_statements
docker exec -it pl-a-pgss-diff psql -U postgres
CREATE EXTENSION pg_stat_statements;
CREATE TABLE shipped (deploy_id int, review_id int);
CREATE TABLE findings (id bigserial PRIMARY KEY, review_id int, severity text, body text);
CREATE INDEX ON shipped (deploy_id);
CREATE INDEX ON findings (review_id);
INSERT INTO shipped SELECT 1, g FROM generate_series(1, 540) g;
INSERT INTO findings (review_id, severity, body)
SELECT g % 20000, CASE WHEN g % 7 = 0 THEN 'high' ELSE 'low' END, repeat('f', 300)
FROM generate_series(1, 400000) g;
VACUUM ANALYZE;
The request is a deploy page: it lists the reviews shipped in a deploy, then reads each review's findings. A shell loop writes the statements it sends:
{ echo "SELECT review_id FROM shipped WHERE deploy_id = 1;"
for r in $(seq 1 540); do
echo "SELECT severity, body FROM findings WHERE review_id = $r;"
done
} > request.sql
Take the snapshot, run the request, and diff:
CREATE TABLE pgss_before AS
SELECT dbid, userid, queryid, toplevel, calls, total_exec_time,
shared_blks_hit + shared_blks_read AS blks
FROM pg_stat_statements;
-- run request.sql from another session here
SELECT s.calls - coalesce(b.calls, 0) AS calls,
round((s.total_exec_time - coalesce(b.total_exec_time, 0))::numeric, 1) AS exec_ms,
s.shared_blks_hit + s.shared_blks_read - coalesce(b.blks, 0) AS blocks,
left(regexp_replace(s.query, '\s+', ' ', 'g'), 60) AS query
FROM pg_stat_statements s
LEFT JOIN pgss_before b USING (dbid, userid, queryid, toplevel)
WHERE s.calls > coalesce(b.calls, 0)
AND s.query NOT LIKE '%pgss_before%'
ORDER BY exec_ms DESC
LIMIT 5;
On PostgreSQL 18.7:
calls | exec_ms | blocks | query
-------+---------+--------+----------------------------------------------------------
540 | 31.6 | 12420 | SELECT severity, body FROM findings WHERE review_id = $1
1 | 1.8 | 3 | SELECT review_id FROM shipped WHERE deploy_id = $1
The 540 is the tell. It equals the number of shipped reviews, so the page runs one findings query per row. Replace the loop with one statement that takes every review at once:
SELECT f.review_id, f.severity, f.body
FROM findings f
WHERE f.review_id = ANY (ARRAY(SELECT review_id FROM shipped WHERE deploy_id = 1));
The same diff then shows one call, 24.7 ms and 508 blocks. The application groups the rows by review_id in memory.
The database time fell only from 33 ms to 25 ms in the lab, because the lab's client sits next to the server. The 539 removed round trips are where an application over a real network gains most. Each costs at least the network latency, plus the application's own work per answer, and none of that appears in total_exec_time.
Read the diff#
Three patterns are worth looking for.
- Calls equal to a row count. One statement per item on the page, as above. Batch it with
= ANY($1)or a join. - Several statements with the same call count. A loop body with three queries shows as three rows that each ran N times. Batch them together, or the page keeps 3N query calls.
- Database time far below the request time. Subtract the diff's total from the request's duration. A large remainder is round trips, pool waits or application work, and the call counts tell you how many round trips there were.
Run the diff at a quiet moment, or on a replica or staging copy that serves only your request, because pg_stat_statements counts every session on the server. On a shared instance, filter both readings to the application's database and role. A quiet interval still matters when other requests use the same role. The view keeps at most pg_stat_statements.max statements, 5,000 by default, and evicts the least used. Check that dealloc in pg_stat_statements_info did not move between snapshots. Statements run inside functions are counted only with pg_stat_statements.track = all. Avoid pg_stat_statements_reset() on a shared server: it wipes everyone's history to save you one subtraction.
The production cases#
A deploy page in one production application took 57 to 88 seconds to answer, and no statement in the slow log was near its 30-second bound. A diff around one 58-second request named the work:
| Work | Calls in one request | Database time |
|---|---|---|
| Carried rows of each promotion | 49 | 19.9 s |
| Previous promotion of each lane | 49 | 4.9 s |
| Freeze state of each promotion | 50 | 3.3 s |
| Findings of each shipped review, three statements | 539 × 3 | 6.6 s |
| Plan of each shipped review, three statements | 539 to 590 × 3 | 0.6 s |
The deploy carried 592 pull requests through 49 promotions, with 539 reviews to show, so each count matched a list on the page. The last 27 seconds of the request fell after the last slow statement, in the per-review loop's round trips and the parsing of 39,274 records in the application. The fix batched the per-review reads into three statements for all reviews, counted findings in SQL where the page showed only a count, and changed the per-promotion statements so each is planned for its call.
A second endpoint, a connection list, took 353 ms at the median for one organization against 48 to 60 ms for others. Its loop ran three or four statements per connection, two of them over the organization's audit history. Building every connection's view in at most two statements, whatever the number of connections, removed the dependence on N.
When the diff is not enough#
The diff tells you what ran and how often, not why. When one statement dominates without a loop, read its plan; this guide separates a plan change from more rows. When the counts grow with rows but the database time is small, the cost is in the application, and the query count is the number to fix. Counting queries with one row and with several turns the same comparison into a regression test.
Where this came from#
Proofline found these loops in its own control plane and shipped the fixes in its production releases of 22 and 24 November 2026. The call counts in The production cases come from diffs taken around single requests before the changes. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review · Eligibility and fair-use terms
Questions#
How do I find an N+1 query in PostgreSQL without application tracing?
Snapshot pg_stat_statements, make the request once, and subtract the counters. A statement whose call count matches the number of rows the page shows runs once per row.
Should I reset pg_stat_statements before measuring?
Not on a shared server. A reset discards every statement's history for all users; a snapshot table and a subtraction give the same numbers without that loss.
Does pg_stat_statements include network time?
No. total_exec_time covers execution on the server. Round trips, pool waits and application work show up only as the gap between the request's duration and the diff's total.