Sub topic 2
Enabling pg_stat_statements
This chapter takes you from a server with no query statistics to one that is collecting them. You will load the extension at server start, create it in a database, and check that it works. You will also see the errors people usually hit on the way.
It assumes you can run SQL in psql or a similar client. It also assumes you can edit postgresql.conf and restart the server, or ask someone who can. The queries that read the statistics come in later chapters.
Why enabling takes two steps
pg_stat_statements needs two separate pieces. Both must be in place before any statistics appear.
- The library. It is loaded when the server starts, and it hooks into query execution to record timings and counters. It keeps its counters in shared memory, and shared memory is allocated at startup. That is why the setting needs a restart and a reload is not enough.
- The SQL objects.
CREATE EXTENSIONadds thepg_stat_statementsview and a few functions to one database. They are how you read and reset the counters.
If you do only the second step, the view exists but fails when you query it. If you do only the first step, the server collects statistics but you have no view to read them through.
Step 1: Check that the extension is available
pg_stat_statements ships in PostgreSQL's contrib modules. Many packages include it. Some Linux distributions put it in a separate package, often named postgresql-contrib or something similar. Ask the server what it has:
SELECT name, default_version, installed_version
FROM pg_available_extensions
WHERE name = 'pg_stat_statements';If you get no rows, the files are not installed on the server. Install the contrib package for your PostgreSQL version first. If installed_version is NULL, the files exist but the extension has not been created in this database yet. That is the normal state before step 4.
Step 2: Add the library to shared_preload_libraries
Open postgresql.conf and set the parameter:
# postgresql.conf (changing this setting requires a server restart)
shared_preload_libraries = 'pg_stat_statements'The value is a comma-separated list. If the parameter already names other libraries, keep them and add this one to the list. Replacing the value silently disables whatever was there before. For example:
shared_preload_libraries = 'auto_explain,pg_stat_statements'You can also set it without editing the file by hand:
ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';ALTER SYSTEM writes to postgresql.auto.conf, and that file overrides postgresql.conf. It also replaces the whole value, so check the current value first with SHOW shared_preload_libraries;. If you set it in one file and a different value sits in the other, the postgresql.auto.conf value wins. This is a common reason for "I changed it and nothing happened".
Managed services and containers
On a managed database service you usually cannot edit postgresql.conf. The provider exposes the same setting as a parameter group, a database flag, or a server parameter. The name and the way you apply it differ by provider, so check the provider's documentation. Some providers already preload pg_stat_statements. In that case you only need step 4.
For a local test with Docker, you can pass the setting on the command line:
docker run --name pgss-demo -e POSTGRES_PASSWORD=secret -d postgres:16 \
-c shared_preload_libraries=pg_stat_statementsStep 3: Restart the server
The change takes effect only after a full restart. How you restart depends on how PostgreSQL was installed. On a systemd-based Linux host it is usually:
sudo systemctl restart postgresqlA restart drops every connection, so schedule it as you would any short outage. A reload (pg_ctl reload or SELECT pg_reload_conf();) reads the new file but does not load the library. After a reload, pg_settings can show that the value is waiting for a restart:
SELECT name, setting, pending_restart
FROM pg_settings
WHERE name = 'shared_preload_libraries';If pending_restart is true, the file holds a value that the running server has not applied yet.
Step 4: Create the extension
Connect to the database you want to inspect and run:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;This needs sufficient privileges. In practice, a superuser or a role allowed to create extensions runs it. On recent PostgreSQL versions, a role can create a trusted extension if it has CREATE on the database. Whether pg_stat_statements counts as trusted depends on the version, so use an administrative role if the command is refused.
Two points about scope matter here:
- The statistics themselves cover the whole server, across all databases. The library collects them in one shared store.
- The
CREATE EXTENSIONcommand is per database. You need it once in each database from which you want to read the view. A common choice ispostgresor your main application database.
The view shows statements from every database, and each row has a dbid column. Without extra privileges, you can only see the query text for your own statements. The chapter on permissions covers this.
Step 5: Verify that it works
First, confirm that the library is loaded and the extension is present:
SHOW shared_preload_libraries;
SELECT extname, extversion
FROM pg_extension
WHERE extname = 'pg_stat_statements';Then run a statement of your own and find it in the view:
SELECT 1 + 1 AS marker_query;
SELECT calls, rows, left(query, 60) AS query
FROM pg_stat_statements
WHERE query LIKE '%marker_query%'
ORDER BY calls DESC;You should see a row for the SELECT 1 + 1 AS marker_query statement with calls of at least 1. The second statement also shows up in the results, because it contains the text marker_query and pg_stat_statements records itself. If you see rows, collection works.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ERROR: pg_stat_statements must be loaded via shared_preload_libraries` when you query the view | The extension is created but the library is not loaded. The setting is missing, or the server was not restarted | Set the parameter, restart, and re-check with `SHOW shared_preload_libraries;` |
| `ERROR: could not open extension control file ... No such file or directory` on `CREATE EXTENSION` | The contrib files are not installed on the server | Install the contrib package that matches your server version |
| `CREATE EXTENSION` succeeds but the view is empty | Nothing has run since the restart, or you are looking at a freshly reset store | Run some queries and look again |
| The setting reads correctly in the file but `SHOW` disagrees | `postgresql.auto.conf` overrides it, or the server was only reloaded | Check `pg_settings` for `sourcefile` and `pending_restart` |
| The server fails to start after the change | A typo in the library name, or a listed library is not installed | Read the server log and fix the value in the file |
| Other libraries stopped working | The old list was overwritten, not extended | Restore the missing names in the comma-separated list |
Version differences and upgrades
The timing columns changed names in PostgreSQL 13. Versions 13 and later have total_exec_time, mean_exec_time, and related columns. Earlier versions have total_time and mean_time. This tutorial uses the 13+ names.
PostgreSQL 14 and later use a core setting named compute_query_id, which defaults to auto. When pg_stat_statements is loaded, auto turns on query identifier computation for you. You do not need to change it unless you have set it to off on purpose. In that case the extension has nothing to group by.
After a major or minor upgrade, the installed extension version can lag behind the one the new binaries provide. Update the SQL objects with:
ALTER EXTENSION pg_stat_statements UPDATE;pg_available_extensions shows both versions side by side, so you can tell when an update is pending.
Cost and what to expect
The extension adds a small amount of work to each statement, and it uses a fixed amount of shared memory. The default limits are enough for many systems. Later chapters cover the settings that control them and how entries are evicted. For now, the point is that enabling the extension is a normal production step, not a risky one. The restart is the only disruptive part.
Counters start at zero when the server starts, and they accumulate from then on. A clean shutdown saves them to disk and a restart reads them back, so a normal restart keeps them. A crash does not. You can also clear them yourself, which the chapter on resetting statistics covers.
Exercise
You added pgstatstatements to sharedpreloadlibraries in postgresql.conf, ran SELECT pgreloadconf(), and then ran CREATE EXTENSION. Querying the view now fails with an error saying the library must be loaded via sharedpreloadlibraries. What went wrong, and how do you confirm it?
Show answer
A reload does not load a library. sharedpreloadlibraries is read only at server start, so the library is not running yet. Restart the server. To confirm, check pgsettings for the parameter: pendingrestart = true means the file has a value the running server has not applied. After the restart, SHOW sharedpreloadlibraries should list pgstatstatements and the view should be readable.
Exercise
Your database already has sharedpreloadlibraries = 'autoexplain'. What value should you set to enable pgstat_statements as well, and in how many databases do you need to run CREATE EXTENSION to read the view in all of them?
Show answer
Set it to 'autoexplain,pgstat_statements' so the existing library stays. CREATE EXTENSION must be run in each database from which you want to query the view, since it creates objects per database. The collected statistics themselves cover the whole server.