Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
The quick answer
sudo -u postgres psql -c "ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';"
systemctl restart postgresql
sudo -u postgres psql -d shop -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"
sudo -u postgres psql -d shop -c "SELECT round(total_exec_time::numeric/1000,1) AS total_s, calls, round(mean_exec_time::numeric,1) AS mean_ms, left(query,70) AS query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;"Step by step
- Turn on pg_stat_statements (quick answer). If
shared_preload_librariesalready has values, add to the list ('pg_stat_statements,auto_explain'), do not replace it. - Find the top queries — sort by
total_exec_time(load on the server) and also bymean_exec_time(slow for each user). Parameters are shown as$1, so similar queries are grouped. - See what runs right now:
sudo -u postgres psql -c "SELECT pid, now()-query_start AS runtime, state, wait_event_type, left(query,60) FROM pg_stat_activity WHERE state <> 'idle' AND now()-query_start > interval '5 seconds' ORDER BY runtime DESC;"Stop one politely: SELECT pg_cancel_backend(PID); (pg_terminate_backend ends the whole session).
- Log slow queries with their duration — every statement over 500 ms goes to the log:
sudo -u postgres psql -c "ALTER SYSTEM SET log_min_duration_statement = '500ms';" -c "SELECT pg_reload_conf();"- Explain the query — with real values in place of
$1:
sudo -u postgres psql -d shop -c "EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 4711 ORDER BY created_at DESC LIMIT 20;"Warning signs: Seq Scan on a big table with Rows Removed by Filter in the millions, estimated rows far from actual rows, external merge Disk.
- Add the missing index without locking writes:
sudo -u postgres psql -d shop -c "CREATE INDEX CONCURRENTLY idx_orders_customer_created ON orders (customer_id, created_at DESC);"- Check table health — many sequential scans or dead rows:
sudo -u postgres psql -d shop -c "SELECT relname, seq_scan, idx_scan, n_dead_tup, last_autoanalyze FROM pg_stat_user_tables ORDER BY seq_scan DESC LIMIT 10;"Old statistics → ANALYZE orders;. Many dead rows → check autovacuum.
- Measure again — reset the statistics after the fix (
SELECT pg_stat_statements_reset();) and compare after a day.
Check that it worked
EXPLAIN ANALYZE now shows Index Scan using idx_orders_customer_created and an execution time in milliseconds; the query drops down the pg_stat_statements list; app response times and database CPU go down.
Common problems
| Problem | Cause | Fix |
|---|---|---|
relation "pg_stat_statements" does not exist | Extension not created in this database. | CREATE EXTENSION pg_stat_statements; in that database. |
must be loaded via shared_preload_libraries | Library not preloaded, or no restart. | Set it and restart PostgreSQL. |
Column total_time not found | Old name (before PostgreSQL 13). | Use total_exec_time / mean_exec_time on 13+. |
CREATE INDEX CONCURRENTLY failed and left an INVALID index | Error or cancel during the build. | DROP INDEX CONCURRENTLY it and run again. |
| Index exists but is not used | Old statistics, wrong column order, or a function on the column. | ANALYZE; match the index to the WHERE/ORDER BY; expression index. |
EXPLAIN ANALYZE changed data | It really runs the statement. | Wrap UPDATE/DELETE in BEGIN; … ROLLBACK;. |
Go further
- Command pages: psql.
- Next how-tos: Tune PostgreSQL memory settings, See who is connected to a database, Find slow MySQL queries, Load test an API with k6.
- Learn it: Data services at work — PostgreSQL. Full guide: PostgreSQL.
1Why sort pg_stat_statements by total time first?
Total time shows which query costs the server the most overall — often a fast query that runs millions of times.
2Why use CREATE INDEX CONCURRENTLY in production?
It builds the index without blocking writes to the table; a normal CREATE INDEX blocks inserts and updates until it is done.