Sub topic 12
Tuning pg_stat_statements settings
This chapter assumes you have already enabled the extension and can read its main columns. The defaults suit most servers. This chapter covers the few cases where they don't, and what each change costs.
What you can configure
pgstatstatements has five settings of its own. Each has a different change rule, so check how a setting is applied before you plan a change.
| Setting | Default | What it controls | How to change it |
|---|---|---|---|
| `pg_stat_statements.max` | `5000` | Maximum number of distinct statements tracked | Server restart |
| `pg_stat_statements.track` | `top` | Which statements are counted: `top`, `all`, or `none` | Superuser, reload or per session |
| `pg_stat_statements.track_utility` | `on` | Whether utility commands such as `CREATE INDEX` or `VACUUM` are counted | Superuser, reload or per session |
| `pg_stat_statements.track_planning` | `off` | Whether planning time is recorded (PostgreSQL 13 and later) | Superuser, reload or per session |
| `pg_stat_statements.save` | `on` | Whether statistics survive a clean server shutdown | Configuration reload |
You can read the rule for each setting from the server. The context column shows postmaster for settings that need a restart, superuser for settings a superuser can change without one, and sighup for settings applied on reload.
SELECT name, setting, context
FROM pg_settings
WHERE name LIKE 'pg_stat_statements.%'
ORDER BY name;pg_stat_statements.max: how many statements to remember
Each distinct normalized statement, per user and database, uses one entry. Once all entries are in use, the server discards the least-executed entries to make room for new ones. When that happens you lose history for the discarded queries, and a rarely run but expensive query may vanish from your rankings.
The usual causes of too many entries are these:
- Many different users or databases running the same queries, since each combination gets its own entry.
- Queries that normalization cannot collapse, such as
INlists of varying length in older versions, or statements built with embedded literals in places that are not constants. - Utility statements with different literal text, when
track_utilityis on.
Check how full the table is before changing anything.
SELECT current_setting('pg_stat_statements.max')::int AS max_entries,
count(*) AS current_entries
FROM pg_stat_statements;On PostgreSQL 14 and later, the pg_stat_statements_info view counts how often entries were discarded.
SELECT dealloc, stats_reset
FROM pg_stat_statements_info;A dealloc value that keeps growing means the table is too small for your workload. If dealloc is zero and current_entries is well under max_entries, leave the setting alone. If it is growing, raise max:
# postgresql.conf (restart required)
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 10000The table lives in shared memory, so a larger max reserves more memory at startup. Query text is stored in a separate file on disk, so memory use grows modestly. Doubling the value is usually a safe first step. A very large value makes the view slower to scan and the text file bigger.
pg_stat_statements.track: which statements count
The three values behave as follows:
topcounts only statements sent directly by clients. A call to a function appears as oneSELECT my_function(...)entry, and the statements inside the function are not listed separately.allalso counts statements nested inside functions and procedures. Each inner statement gets its own row.noneturns collection off without removing the extension.
Use all when a PL/pgSQL function is slow and the top-level row only tells you the function as a whole is expensive. Each inner statement then shows its own call count and time. The cost is more entries and some double counting. A nested statement's time is also included in the time of the outer call, so do not add the rows together.
You can switch for a single session if you are a superuser, or for the whole server without a restart.
-- Whole server, applied on reload
ALTER SYSTEM SET pg_stat_statements.track = 'all';
SELECT pg_reload_conf();
-- Revert later
ALTER SYSTEM RESET pg_stat_statements.track;
SELECT pg_reload_conf();pg_stat_statements.track_utility: commands that are not queries
Utility commands are statements other than SELECT, INSERT, UPDATE, DELETE, and MERGE. Examples include CREATE INDEX, VACUUM, COPY, BEGIN, and SET. With the default on, they appear in the view.
This is useful when you want to see how long COPY loads or index builds take. It is a nuisance when an application sends thousands of distinct SET or PREPARE statements, because they fill entries without telling you anything about query performance. If your rankings are cluttered, turn it off:
ALTER SYSTEM SET pg_stat_statements.track_utility = off;
SELECT pg_reload_conf();pg_stat_statements.track_planning: planning time
By default the planner's time is not measured. In PostgreSQL 13 and later the view has plans, total_plan_time, mean_plan_time and related columns, but they stay at zero while track_planning is off.
Turn it on if you suspect planning dominates, for example with very complex queries, many partitions, or heavy use of simple queries that are planned on every call. Be careful: the setting makes every statement update its entry twice, once for planning and once for execution. On servers running many short queries across many connections, this can cause lock contention on the shared entries and measurably reduce throughput. Enable it on a test system first, or for a short window.
ALTER SYSTEM SET pg_stat_statements.track_planning = on;
SELECT pg_reload_conf();Once it is on, compare planning and execution time per call.
SELECT queryid,
calls,
round(mean_plan_time::numeric, 3) AS mean_plan_ms,
round(mean_exec_time::numeric, 3) AS mean_exec_ms,
left(query, 60) AS query
FROM pg_stat_statements
WHERE calls >= 100
ORDER BY mean_plan_time DESC
LIMIT 10;A query where mean_plan_ms is larger than mean_exec_ms is a candidate for prepared statements or for a simpler schema, rather than for an index.
pg_stat_statements.save: surviving restarts
With save = on, the statistics are written to disk on a clean shutdown and reloaded at start. After a crash, or an immediate shutdown, the statistics are lost regardless of this setting. Set save = off only if you want every restart to begin with an empty table, for example on a throwaway test server.
Settings outside the extension that affect it
Two core settings change what the view contains:
compute_query_id(PostgreSQL 14 and later) decides whether the server calculatesqueryid. The defaultautoenables it when pgstatstatements is loaded, so you rarely need to touch it.track_io_timingmakes the server measure time spent on block reads and writes. Without it, the I/O time columns stay at zero. The columns areblk_read_timeandblk_write_timebefore PostgreSQL 17, andshared_blk_read_timeandshared_blk_write_timefrom 17. Timing calls add overhead on systems with slow clocks, and PostgreSQL shipspg_test_timingto measure that.
ALTER SYSTEM SET track_io_timing = on;
SELECT pg_reload_conf();Common mistakes
- Editing
pg_stat_statements.maxand only reloading. The server keeps the old value until a restart, so checkSHOW pg_stat_statements.max;afterwards. - Running
ALTER SYSTEMfor a pgstatstatements setting on a server where the library is not preloaded. The server may accept the value but it has no effect until the library loads. - Leaving
track_planningon permanently on a busy system without measuring throughput before and after. - Adding up rows after setting
track = 'all', which counts nested time twice. - Reading a ranking after a high
dealloccount as if it were complete.
Practical starting configuration
For most production systems, keep the defaults and make two adjustments only when evidence calls for them: raise max if dealloc keeps growing, and enable track_io_timing if you want I/O time columns. Use track = 'all' and track_planning = on as short-lived diagnostic switches, then revert them.
Exercise
After a deployment, your pg_stat_statements_info.dealloc value rises every hour, and a query you know runs nightly is missing from the view. Which setting do you change, how is it applied, and what do you check first?
Show answer
Raise pg_stat_statements.max in postgresql.conf and restart the server, because it is a postmaster setting that a reload does not apply. First compare count(*) from pg_stat_statements to current_setting('pg_stat_statements.max'). If the table is full and dealloc is growing, entries are being discarded, which explains the missing nightly query. Afterward, confirm the new value with SHOW pg_stat_statements.max; and watch whether dealloc stops growing.
Exercise
A PL/pgSQL function shows up as the top query by total_exec_time, but you cannot tell which statement inside it is slow. Which setting helps, how do you apply it without a restart, and what must you remember when reading the new rows?
Show answer
Set pg_stat_statements.track = 'all' with ALTER SYSTEM SET pg_stat_statements.track = 'all'; followed by SELECT pg_reload_conf();. Nested statements then get their own rows. Their time is also included in the outer function call's time, so do not add the rows together. Consider resetting statistics first so the comparison covers one defined period, and revert the setting when you are done.