Configuration·PostgreSQL
PostgreSQL Query Statistics with pg_stat_statements
One extension, one restart, and every statement the server runs is aggregated by shape with call counts and timings - finding the query that takes 5 ms and runs a hundred thousand times, which no slow-query threshold ever will.
Performance Guide 36 of 47 Intermediate
- OSUbuntu 26.04 LTS
- PostgreSQL18.6-0ubuntu0.26.04.1
- Test data400,000 rows, 2 core / 4 GB host
- TimeAbout 14 min
pg_stat_statements must be in shared_preload_libraries, which requires a restart. It is the single most valuable extension to have installed before you need it.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| db-a01 | 192.168.0.81 | Ubuntu 26.04 LTS | Primary / Source / Replica Set Member 1 | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when you need to know which statements cost the most. This matters because it is not an ordinary extension - it needs a restart before CREATE EXTENSION does anything - and it aggregates by statement shape rather than by literal.
- loading the extension, which takes two steps rather than one
- running queries with different literals, and reading them back aggregated together
- seeing that statements are grouped by shape rather than by their values
Before you start
- Superuser access, and a restart window.
-
Load the extension and reset the counters
-
Run three queries and read them back aggregated