Skip to content

PostgreSQL

Tested on PostgreSQL 16. The column names below are for PostgreSQL 13 and later.


Find the unindexed query before adding cache

SELECT calls, round(mean_exec_time::numeric, 1) AS avg_ms,
       round(total_exec_time::numeric) AS total_ms, query
  FROM pg_stat_statements
 WHERE query NOT ILIKE '%pg_stat%'
 ORDER BY total_exec_time DESC
 LIMIT 15;

Sort by total time, not mean. A 4ms query run 900k times beats a 2s query run twice, and only one of them is worth your afternoon.

It needs one-time setup, or it fails with "pg_stat_statements must be loaded via shared_preload_libraries":

# postgresql.conf, then restart PostgreSQL:
#   shared_preload_libraries = 'pg_stat_statements'
sudo -u postgres psql -c 'CREATE EXTENSION IF NOT EXISTS pg_stat_statements;'

© 2026 Helius ApS · CVR 46850297. All rights reserved.

Got an idea for the next post? Tell me →