Sub topic 4
Reading the core columns
This chapter assumes you can write basic SQL (SELECT, ORDER BY, LIMIT, aggregates), that you can run queries in psql or another client, and that pg_stat_statements is already enabled in your database. It also assumes a PostgreSQL version of 13 or later, where the timing columns are named total_exec_time and mean_exec_time. Earlier versions used total_time and mean_time.
The view is one row per normalized query
The pg_stat_statements view holds one row for each distinct combination of database, user, and normalized query. Every column except the identifiers is a running total since the statistics were last reset, with a few derived values such as the mean. Reading the view well means knowing what each column counts and which columns to compare.
Start by looking at the shape of the view:
SELECT userid::regrole AS role,
dbid,
queryid,
calls,
rows,
left(query, 60) AS query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 5;Each row answers one question: how often did this query shape run, and what did it cost in total? It does not tell you what happened on any single run.
Identity columns
Four columns say which statement a row describes.
| Column | Meaning |
|---|---|
| `userid` | OID of the role that ran the statement. Use `userid::regrole` to see the name. |
| `dbid` | OID of the database the statement ran in. |
| `queryid` | Hash that identifies the normalized statement. |
| `query` | Text of the first statement seen for this entry, with constants replaced by `$1`, `$2`, and so on. |
The same query text run by two roles produces two rows. The same query text run in two databases also produces two rows. The extension stores statistics for the whole server, so the view shows rows from every database. When you analyze one database, filter on it:
SELECT calls, round(total_exec_time::numeric, 2) AS total_ms, left(query, 60) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 5;Without that filter, a busy neighboring database can crowd your own queries out of the top ten.
Counting columns: calls and rows
calls is the number of times the statement was executed. rows is the total number of rows retrieved or affected by the statement across all those calls.
Dividing one by the other gives the average rows per call. This is a useful sanity check:
SELECT queryid,
calls,
rows,
round(rows::numeric / nullif(calls, 0), 1) AS rows_per_call,
left(query, 60) AS query
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;A query with a high rows_per_call returns or modifies a lot of data on each execution. That may be correct for a report, but it is suspicious for an endpoint that is supposed to fetch one record. A query with rows_per_call near 1 and a very high calls count is a candidate for batching, because the application may be running it in a loop.
Two details affect how you read rows:
- For a
SELECT, it counts rows returned to the client. A query that scans a million rows and returns ten adds ten. - For
INSERT,UPDATE, andDELETE, it counts rows affected. For statements withRETURNING, it counts the rows returned.
So rows tells you the size of the result, not the amount of work. To see work, use the buffer columns, which a later chapter covers.
Timing columns
The timing columns record time spent executing the statement, measured in milliseconds.
| Column | Meaning |
|---|---|
| `total_exec_time` | Sum of execution time over all calls. |
| `mean_exec_time` | `total_exec_time / calls`. |
| `min_exec_time` | Fastest single execution. |
| `max_exec_time` | Slowest single execution. |
| `stddev_exec_time` | Population standard deviation of execution time. |
Execution time does not include planning time. Planning time is tracked in separate columns (total_plan_time, mean_plan_time, and so on), but only when pg_stat_statements.track_planning is on. It is off by default because tracking it adds overhead. Also, in PostgreSQL 13 and later, the plan columns stay at zero unless you turn the setting on.
The values are floating point and have many decimal places, so cast to numeric before rounding:
SELECT queryid,
calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(min_exec_time::numeric, 2) AS min_ms,
round(max_exec_time::numeric, 2) AS max_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
left(query, 50) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Calling round(double precision, integer) fails because that overload does not exist, which is why the ::numeric cast appears in every query in this tutorial.
Total versus mean
total_exec_time and mean_exec_time rank queries differently, and neither is always the right one.
- Sorting by total time finds the queries that use the most database time overall. A query that takes 2 ms but runs ten million times costs about 5.5 hours in total.
- Sorting by mean time finds the queries that are slow each time they run. A report that takes 40 seconds but runs twice a day barely shows up in the total ranking.
Use total time to decide where tuning saves the most capacity. Use mean time to find what users experience as slow. The next chapters develop both rankings.
Reading the spread
min_exec_time, max_exec_time, and stddev_exec_time describe the spread. If mean_exec_time is 12 ms and max_exec_time is 12,000 ms, most runs are fast and a few are very slow. A mean alone hides that. Common causes include lock waits, cold caches, and parameter values that lead to different plans.
A quick comparison is the ratio of maximum to mean:
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
round((max_exec_time / nullif(mean_exec_time, 0))::numeric, 1) AS max_over_mean,
left(query, 50) AS query
FROM pg_stat_statements
WHERE calls >= 100
ORDER BY max_over_mean DESC NULLS LAST
LIMIT 10;A ratio in the hundreds on a query with many calls is worth a look. A ratio of 30 on a query that ran twice means little, which is why the calls >= 100 filter is there.
How the columns relate
The following diagram shows how the core columns build on each other.
Edge cases that change how you read a row
Statements are grouped, so the row may hide variety
One row covers every execution that normalizes to the same shape. If WHERE customer_id = $1 is fast for most customers and slow for one with millions of orders, the row shows a single mean. The max_exec_time and stddev_exec_time columns are the only hint, and you must find the offending parameter values yourself, for example in the application logs.
The query text is a sample
The query column holds the text of the first statement that created the entry. It is cut off at track_activity_query_size bytes (1024 by default). Long statements are truncated, and left(query, 80) truncates further, so two different queries may look identical in your output. Use queryid to tell them apart, not the visible text.
Utility statements appear too
DDL and utility commands such as VACUUM, CREATE INDEX, and COPY appear in the view when pg_stat_statements.track_utility is on, which is the default. They often dominate max_exec_time, and it is easy to mistake them for application queries. Exclude them when you want only application work:
SELECT queryid, calls, round(total_exec_time::numeric, 2) AS total_ms, left(query, 60) AS query
FROM pg_stat_statements
WHERE query !~* '^\s*(vacuum|analyze|create|alter|drop|copy|set|begin|commit)'
ORDER BY total_exec_time DESC
LIMIT 10;The view includes itself
Your own monitoring queries against pg_stat_statements are counted as statements. If you run a ranking query repeatedly, it will start to appear in the results. Ignore it, or exclude it with WHERE query NOT ILIKE '%pg_stat_statements%'.
Counters reset and can restart
Statistics persist across a clean restart but are discarded after a crash recovery, and pg_stat_statements_reset() clears them on demand. A low calls count on a row may mean the statistics were recently cleared and not that the query is rare. Check when the last reset happened before you compare rows. From PostgreSQL 14, the pg_stat_statements_info view has a stats_reset timestamp:
SELECT dealloc, stats_reset FROM pg_stat_statements_info;The dealloc column counts how often the least-used entries were evicted to make room for new ones. A non-zero and growing value means some statements are being forgotten.
A worked reading
Suppose the ranking returns these two rows:
| queryid | calls | total_ms | mean_ms | max_ms | rows |
|---|---|---|---|---|---|
| A | 4,200,000 | 1,260,000 | 0.30 | 45 | 4,200,000 |
| B | 18 | 540,000 | 30,000 | 31,000 | 18 |
Query A runs 4.2 million times at 0.3 ms each and returns one row per call. It takes 21 minutes of database time in total. Its per-call cost is already low, so the saving comes from running it less often, for example by caching or batching.
Query B runs 18 times at about 30 seconds each, which is 9 minutes in total. Its max_exec_time is close to its mean, so the slowness is consistent and is not caused by occasional spikes. Look at its plan, because every execution does a lot of work.
Both deserve attention for different reasons, and the columns show which kind of attention each needs.
Exercise
A row shows calls = 2, meanexectime = 8,000 ms, and maxexectime = 15,900 ms. Another row shows calls = 500,000, meanexectime = 1.2 ms, and maxexectime = 20 ms. Which has the larger totalexectime, and why should you be careful about concluding anything from the first row's max-to-mean ratio?
Show answer
The second row has the larger total: 500,000 × 1.2 ms = 600,000 ms, against 2 × 8,000 ms = 16,000 ms for the first. The first row's max-to-mean ratio of about 2 is based on only two executions, so it says almost nothing about stability. With so few calls, the spread columns are not reliable. Check the call count before reading spread.
Exercise
Write a query that lists, for the current database only, the five statements with the highest average rows per call, ignoring statements that ran fewer than 20 times. Include queryid, calls, and the rows-per-call figure.
Show answer
SELECT queryid, calls, round(rows::numeric / calls, 1) AS rowspercall FROM pgstatstatements WHERE dbid = (SELECT oid FROM pgdatabase WHERE datname = currentdatabase()) AND calls >= 20 ORDER BY rows::numeric / calls DESC LIMIT 5;