pg_stat_statements Said 6ms. The Query Actually Costs 102ms
Our reporting endpoint got slower over about a month. No deploy to blame, nothing in the logs, just a page that used to load in 400ms and now took 1.4 seconds. So I did what everyone does. Turned on pg_stat_statements, ranked by total_exec_time, read the top ten.
The worst entry was 6ms. Second was 4ms. Nothing on that list could account for a 1.4 second page.
It wasn't lying. It was measuring three things wrong, and none of them were the queries.
The planner's share is missing by default
pg_stat_statements.track_planning ships as off. total_plan_time, mean_plan_time and stddev_plan_time have existed since Postgres 13. They sit at zero until you flip it.
ALTER SYSTEM SET pg_stat_statements.track_planning = on;
SELECT pg_reload_conf();
No restart. shared_preload_libraries needs one, this doesn't.
I built an eight way join over eight small tables and ran it 100 times through psql, which replans every time:
-- track_planning = off
calls | total_exec_time | total_plan_time | mean_exec_time | mean_plan_time
-------+-----------------+-----------------+----------------+----------------
100 | 6.38 | 0.00 | 0.064 | 0.000
-- track_planning = on
100 | 6.82 | 95.82 | 0.068 | 0.958
Six point eight milliseconds of execution against ninety five of planning, fourteen times more work sitting in a column the standard top-ten query never selects. Reported the default way that join costs 6.8ms. With planning on it costs 102ms. Joins and union-expanding views are mostly planning, and you have been reading the tip.
One caveat decides how much this matters. If your driver caches prepared statements you pay the plan once and the defaults are fine. Plenty don't, psql -c included. On one of those, planning is a cost you have been paying all month without seeing.
Normalization welds two different queries into one row
Constants become $1. Every post about this view says so. They leave out that LIMIT counts as a constant too.
-- select id, note from orders order by note limit 10 (10 calls)
mean_exec_time: 29.1ms
-- select id, note from orders order by note limit 20000 (10 calls)
mean_exec_time: 302.1ms
-- both of them, in the view:
calls | mean_exec_time | max_exec_time | stddev_exec_time | query
-------+----------------+---------------+------------------+------------------------------
20 | 165.7 | 305.6 | 137.0 | ... order by note limit $1
One row for two jobs that share nothing but a shape. That mean of 165.7 is just the average of 29 and 302. On a dashboard I would read it as slow and consistently slow, which is wrong twice: it isn't one query, and the fast variant is fine.
The tell is stddev_exec_time, a column almost nobody selects. 137 next to a mean of 165. A shape with one plan spreads tighter than that. When the standard deviation sits close to the mean, treat the row as a blend until you've proven otherwise.
Aliases are worse than LIMIT, because they don't even leave a trace. Output column names aren't part of the hash at all:
select count(*) as a from orders;
select count(*) as b from orders;
select count(*) as c_really_different from orders;
-- queryid 9175542703500084910 | calls 3
-- query: select count(*) as a from orders
Three statements, one row, and the query column only holds the first. That column is a reconstruction, not a log line. It's the first execution of a shape, constants swapped for placeholders, never anything that came later. Copy it into EXPLAIN and you may be explaining a statement that ran with different aliases and a different LIMIT, days ago.
That's why I read max_exec_time and stddev_exec_time before the mean, and why a slow query log with real parameters still earns its keep. When the plan does look insane, these are the five things I check first.
Anything inside a function runs off the books
pg_stat_statements.track defaults to top. Top level only. A PL/pgSQL function is one statement as far as this view is concerned.
create function touch_orders(n int) returns int language plpgsql as $$
declare total int := 0; r int;
begin
for i in 1..n loop
select count(*) into r from orders where customer_id = i;
total := total + r;
end loop;
return total;
end $$;
-- with track = top (the default)
toplevel | calls | total_exec_time | query
----------+-------+-----------------+---------------------
t | 1 | 16.89ms | select touch_orders($1)
-- rows in the view matching the inner select: 0
One call, seventeen milliseconds, scroll past it. Flip to track = all and the same invocation produces a second row: toplevel = false, 5000 calls, 9.7ms. The function was never one cheap statement. It was five thousand index lookups and a loop, and the hot path I was hunting lived inside that loop the whole time.
I run track = all for ten minutes when something smells, then put it back. It instruments every nested statement and costs something. Ten minutes is worth it. Forever is not.
Before you trust the ordering
Three things change what the top ten means, and none of them show up in the query everyone copies.
SELECT name, setting FROM pg_settings WHERE name LIKE 'pg_stat_statements%';
SELECT * FROM pg_stat_statements_info;
pg_stat_statements.max won't go below 100. I set it to 10 to test eviction and startup logged WARNING: 10 is outside the valid range for parameter "pg_stat_statements.max" (100 .. 1073741823), then carried on with the default 5000. Had I not read the log I'd have assumed the setting applied.
When the table fills, entries get evicted and pg_stat_statements_info.dealloc counts it. On a fresh restart with max = 100 I ran 130 statements that differed only in the table they touched. Ninety survived. dealloc reported 4, so that counter won't tell you how much you lost either. The only honest check is whether the statement you're chasing is in there at all.
Last one, and it catches people on shared instances. The extension is per database. shared_preload_libraries is instance wide, the view is not. I created a second database, queried the view, and got relation "pg_stat_statements" does not exist while the library collected happily in the first one.
None of this makes the extension a bad tool. It's the only thing I have that answers where the database spent its time. It just answers a narrower question than a ranking implies, and the gap between the two is where my afternoon went. The 1.4 seconds came from a per-request function running a few thousand lookups under one cheap-looking row.
So: planning on, rank by total_plan_time + total_exec_time, check the standard deviation before the mean, and look at dealloc when the list seems too clean. On MySQL the same drill looks nothing like this, I wrote that one up here. The ranking query and the function test live in Snippet Ark now, mostly so I stop rebuilding them from memory every time a page gets slow.