Geavanceerd
Zoeken inHow-to-gidsen
Zo zoek je
  • Typ de taak in je eigen woorden (poort vinden, firewall openen, schijf vol) of plak een foutmelding tussen aanhalingstekens.
  • Kies "Snel antwoord" om alleen de commando's te zien, of een gebied om in één vakgebied te blijven.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

How-to 186Data · PostgreSQL

How to find slow PostgreSQL queries

The app is slow and the database CPU is high — but which query? pg_stat_statements sums up every query type: how often it ran, total and mean time. The one with the highest total time is usually the best fix. Then EXPLAIN (ANALYZE, BUFFERS) shows why it is slow, and often one index solves it. This how-to turns on the statistics, finds the top queries, looks at running queries, and fixes a missing index safely.

  • 5 Lessen
  • 3 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

186.1

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;"

186.2

Step by step

  1. Turn on pg_stat_statements (quick answer). If shared_preload_libraries already has values, add to the list ('pg_stat_statements,auto_explain'), do not replace it.
  2. Find the top queries — sort by total_exec_time (load on the server) and also by mean_exec_time (slow for each user). Parameters are shown as $1, so similar queries are grouped.
  3. 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).

  1. 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();"
  1. 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.

  1. 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);"
  1. 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.

  1. Measure again — reset the statistics after the fix (SELECT pg_stat_statements_reset();) and compare after a day.

186.3

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.

186.4

Common problems

ProblemCauseFix
relation "pg_stat_statements" does not existExtension not created in this database.CREATE EXTENSION pg_stat_statements; in that database.
must be loaded via shared_preload_librariesLibrary not preloaded, or no restart.Set it and restart PostgreSQL.
Column total_time not foundOld name (before PostgreSQL 13).Use total_exec_time / mean_exec_time on 13+.
CREATE INDEX CONCURRENTLY failed and left an INVALID indexError or cancel during the build.DROP INDEX CONCURRENTLY it and run again.
Index exists but is not usedOld statistics, wrong column order, or a function on the column.ANALYZE; match the index to the WHERE/ORDER BY; expression index.
EXPLAIN ANALYZE changed dataIt really runs the statement.Wrap UPDATE/DELETE in BEGIN; … ROLLBACK;.

186.5

Go further

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.

Commando's in deze les

Alle commando's in dit hoofdstuk