brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pg_stat_statements shows which PostgreSQL queries take the most time overall

Postgresql
~/tips/tip-postgresql-pg-stat-statements

shared_preload_libraries = 'pg_stat_statements'

Ranks normalized queries by their total run time so you tune the ones that matter.

The slowest query is not always the problem. A 2 ms query that runs a million times an hour costs more than one slow report. pg_stat_statements adds those up for you.

It needs a line in postgresql.conf and a restart, then the extension in the database you query from:

shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION pg_stat_statements;
SELECT calls, round(total_exec_time) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Queries are normalized, so WHERE id = 42 and WHERE id = 43 count as one entry with $1 in place of the value. calls is how often it ran and total_exec_time the sum in milliseconds. The top of this list is where tuning pays off. Ordering by mean_exec_time instead finds the slow ones.

After a fix, SELECT pg_stat_statements_reset(); clears the numbers so you can measure fresh.

The library must be in shared_preload_libraries; only running CREATE EXTENSION gives you a view that errors out. That restart is the part I find annoying on a busy server. In the official Docker image you can pass it as a command option, such as -c shared_preload_libraries=pg_stat_statements. Only superusers and roles with pg_read_all_stats see the query text of other users; everyone else gets <insufficient privilege> in that column.

Further reading: pg_stat_statements

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link