Sub topic 1
What pg_stat_statements tells you and what it does not
pg_stat_statements is a PostgreSQL extension. It keeps running totals for every kind of statement the server executes. It answers questions such as "which queries use the most time?" and "which queries read the most blocks?" It cannot tell you what happened during one particular slow request. This chapter explains what the extension records and what it leaves out, so that you read its numbers correctly in the rest of the tutorial.
Prerequisites
This chapter assumes you already have:
- Basic SQL:
SELECT,ORDER BY,LIMIT, and aggregate expressions such assum()andround(). - Access to a PostgreSQL instance where you can change configuration, or someone who can change it for you.
- Familiarity with
psqlor another SQL client. - A general idea of what a query plan is: the sequence of steps the server picks to run a query.
You do not need the extension installed to follow this chapter. The next chapter covers enabling it.
The core idea: a ledger of totals
Think of pg_stat_statements as a ledger. Each time a statement finishes, the extension adds that execution's cost to one row. The row stands for a group of similar statements. The row keeps totals, not individual executions.
For each group the ledger records:
- How many times the statement ran (
calls). - Total, mean, minimum, maximum, and standard deviation of execution time.
- How many rows it returned or affected (
rows). - Block counters: shared buffer hits and reads, local blocks, and temporary blocks.
- Write-ahead log (WAL) volume.
- Optionally, planning time and plan counts, when the
track_planningsetting is on.
All of these are cumulative. A value of calls = 12000 means 12,000 executions have been added since the counters were last reset. It does not mean 12,000 in the last hour.
What the extension is good for
The ledger design suits three jobs.
- Finding aggregate cost. A query that runs 2 ms per call but runs 50 million times a day can use more server time than a 5-second report that runs once. Cumulative totals show this. A slow query log alone does not.
- Comparing queries across the whole workload. All statements land in one view, so you can rank them by total time, mean time, I/O, or temporary file use. You get a prioritized list of candidates for tuning.
- Measuring before and after. Because the counters only grow, you can reset them, run a workload, and read the result. The same method works for a change such as a new index.
Statements are identified without their constants. These two queries count as the same statement:
SELECT * FROM orders WHERE customer_id = 42;
SELECT * FROM orders WHERE customer_id = 7;The extension stores one entry with the text SELECT * FROM orders WHERE customer_id = $1. It does this by normalization, which replaces constants with placeholders. Chapter 3 covers how this grouping works in detail. For now, remember that one row represents many executions.
What the extension does not tell you
Most mistakes in reading pg_stat_statements come from asking it questions the ledger cannot answer.
It has no per-execution history
The view does not store when each execution happened, how long that single execution took, or which one was the slow one. You get min_exec_time, max_exec_time, mean_exec_time, and stddev_exec_time. These are summaries, and they cannot rebuild the individual runs.
Here is why a mean can mislead. Suppose a statement shows these values:
SELECT 10000.0 / 1000 AS mean_ms;That is a mean of 10 ms from 1,000 calls totalling 10,000 ms. Two very different histories give the same row. In one, every call takes about 10 ms. In the other, 999 calls take 1 ms and one call takes about 9,001 ms. The max_exec_time and stddev_exec_time columns help you tell these apart. They still do not tell you when the long call happened.
It does not keep parameter values
Normalization removes the constants. If a query is fast for customer_id = 7 and slow for customer_id = 42 because customer 42 has millions of orders, the ledger cannot say so. You will need to find representative parameter values elsewhere, such as in application logs, and test them yourself. Chapter 8 shows how.
It does not store plans
The view records no execution plan. You can see that a query is expensive but not why. For the why, you run EXPLAIN on the query yourself.
It does not time everything a client experiences
The execution time columns measure time spent running the statement inside the server. Time spent in the application, in the network, or waiting in a connection pool is not included. Parsing and planning time are separate. Planning time is only collected when pg_stat_statements.track_planning is on, and it is off by default because it adds overhead. A query that is slow to plan can therefore look cheap in total_exec_time.
It does not show waits or blocking
The extension does not say whether a statement was slow because it waited on a lock. It has no wait events and no information about blockers. Look at pg_stat_activity and pg_locks for that.
It only counts statements that complete
Statements that fail with an error, or that are cancelled before finishing, are not added to the totals. A query that always times out and gets cancelled by statement_timeout may therefore be missing from your ranking, or look cheaper than it is.
It has bounded memory
The extension keeps a fixed maximum number of entries, set by pg_stat_statements.max. When the limit is reached, the least-used entries are dropped to make room. A rarely run query can disappear from the view. Query text is also stored up to a size limit and cut off after it. Chapter 14 covers these limits.
The summary at a glance
| Question | Answered by pg_stat_statements? |
|---|---|
| Which statement shapes use the most total time? | Yes |
| Which statements are slow on average? | Yes |
| How many blocks did this statement read from outside shared buffers? | Yes |
| Does this statement spill to temporary files? | Yes |
| How long did one specific execution take? | No |
| When did the slow execution happen? | No |
| What parameter values were used? | No |
| What plan did the server choose? | No |
| Was the statement waiting on a lock? | No |
Reading counters as rates
Because the numbers are cumulative, a large total_exec_time can mean two things. The query may be expensive now, or it may have been running for months. The ledger shows no difference between the two. Two habits help:
- Note when the counters began. Without a known start point, a ranking tells you little about current behavior. Chapter 9 covers resetting and measuring a time window.
- Compare two snapshots. Copy the view into a table at one time, copy it again later, and subtract. This gives you a rate for the interval between them. It is the closest you can get to history with this extension.
A quick way to see how much data the ledger holds, once the extension is enabled, is to count entries and total calls:
SELECT count(*) AS tracked_statements,
sum(calls) AS total_calls
FROM pg_stat_statements;If tracked_statements is close to the pg_stat_statements.max setting, eviction may already be dropping entries, and your rankings may be incomplete.
Where this fits in a tuning workflow
pg_stat_statements is a triage tool. It narrows thousands of statements down to a short list. You then take each suspect to EXPLAIN (ANALYZE, BUFFERS), which runs the query with real parameters and shows the actual plan, timings, and buffer use. The tutorial follows this path: enable the extension, read the columns, rank by time and I/O, then investigate with EXPLAIN. Keep the limits above in mind at each step, because a number from the ledger is a lead to follow up, not a final verdict.
Exercise
A statement in pgstatstatements shows calls = 2000, totalexectime = 4000 ms, and maxexectime = 3500 ms. A teammate says "it takes 2 ms per call, so it is fine." What is wrong with that conclusion, and what can you not learn from the view about the 3500 ms execution?
Show answer
The mean of 2 ms (4000 / 2000) hides an outlier. One execution took up to 3500 ms, which is most of the total time, so the other 1999 calls average under 1 ms. The conclusion is wrong because the mean describes the group, not each call. From the view you cannot learn when that execution happened, which parameter values it used, what plan it ran with, or whether it was waiting on a lock. Those need application logs, EXPLAIN (ANALYZE, BUFFERS) with realistic parameters, and pgstatactivity or pg_locks.
Exercise
Name three kinds of information that pgstatstatements does not store, and say where you could look for each one.
Show answer
Any three of these. Per-execution timing or the moment a slow call happened: application or server logs, for example logmindurationstatement. Parameter values: application logs or log output that includes bind values. The chosen plan: run EXPLAIN (ANALYZE, BUFFERS) yourself. Lock waits: pgstatactivity and pglocks.