Skip to content
SQLEye

Blog / PostgreSQL

Find slow queries in PostgreSQL

By CodeROG · Published · Last updated

To find slow queries in PostgreSQL, set log_min_duration_statement to a threshold such as 250ms so the server logs every statement that runs at least that long, then enable the pg_stat_statements extension to rank queries by total and mean execution time. Use the first for individual offenders and the second for aggregate cost.

How do I log slow statements?

log_min_duration_statement causes the duration of each completed statement to be logged if the statement ran for at least the specified time. Its meaning at the edges:

Value Effect
-1 (default) Disabled: durations are not logged
0 Logs the duration of every statement
250ms Logs statements that ran 250 ms or longer

A value without units is taken as milliseconds. Only superusers and users with the appropriate SET privilege can change it.

For a quick look, change it for your own session only:

SET log_min_duration_statement = '250ms';
SHOW log_min_duration_statement;

To make it server-wide, edit postgresql.conf:

log_min_duration_statement = 250ms

How do I apply it without a restart?

Ask the server to reload its configuration files:

SELECT pg_reload_conf();

pg_reload_conf() returns a boolean and causes all server processes to reload their configuration files (it signals the postmaster with SIGHUP). It is restricted to superusers by default, and access can be granted to other roles with GRANT. The documentation also points to the pg_file_settings view for checking the files for errors before you reload.

Be careful with 0 on a busy server: it logs every statement and the log grows quickly, and logged statements can contain sensitive values.

Where do the logs go?

By default the server logs to stderr only. Two settings decide the rest:

  • logging_collector is a background process that captures log messages sent to stderr and redirects them into log files. It can only be set at server start, so turning it on needs a restart.
  • log_destination chooses the formats: stderr, csvlog, jsonlog and syslog (plus eventlog on Windows), comma-separated. It can only be set in postgresql.conf or on the server command line.

When the collector is on, log_directory (default log, relative to the data directory unless absolute) and log_filename (a strftime pattern; default postgresql-%Y-%m-%d_%H%M%S.log) decide where files go. If CSV output is enabled .csv is appended to the name, and if JSON output is enabled .json is appended.

logging_collector = on
log_destination = 'stderr,jsonlog'
log_directory = 'log'

jsonlog was added in PostgreSQL 15 (“The new setting is log_destination = jsonlog” in the 15 release notes). It also requires logging_collector. JSON entries are easier for tools to parse than text lines. The exact fields and the text line layout depend on your version and on log_line_prefix, so read a few lines from your own server before writing a parser.

How do I rank queries with pg_stat_statements?

The log tells you about single executions. A query that takes 5 ms but runs a million times never appears with a 250 ms threshold, yet may cost more than one 2-second report. pg_stat_statements aggregates by normalised statement.

  1. Add the module to postgresql.conf. The doc notes it needs extra shared memory, so this requires a server restart:

    shared_preload_libraries = 'pg_stat_statements'
  2. Restart PostgreSQL.

  3. Create the view in each database where you want to query it:

    CREATE EXTENSION pg_stat_statements;

The module also needs query identifiers to be computed: it is only active if compute_query_id is auto or on (or another module computes them). Statistics are tracked across all databases on the server, but the view is only available where the extension was created.

Now rank by total time spent:

SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

In this view calls is the number of executions, total_exec_time and mean_exec_time are in milliseconds (double precision), and rows is the total rows retrieved or affected. These names apply from PostgreSQL 13, where the view exposes total_exec_time. Literal constants are replaced with parameter symbols such as $1, so queries that differ only in constants share one row. Output values vary by workload.

Only superusers and roles with pg_read_all_stats see the query text of other users’ statements. The statistics persist until you discard them with SELECT pg_stat_statements_reset(); (superuser by default).

To find the “slow each time” queries instead, sort by mean_exec_time DESC. To find the “cheap but constant” ones, sort by calls DESC and look for a shape that matches an N+1 pattern.

What about auto_explain?

auto_explain logs the execution plan of slow statements automatically. It is loaded per session with LOAD 'auto_explain'; (superuser), or preloaded via session_preload_libraries or shared_preload_libraries. Its trigger is auto_explain.log_min_duration, in milliseconds, default -1 (disabled), where 0 logs all plans. Leave auto_explain.log_analyze off unless you are debugging: the documentation warns that when it is on, per-plan-node timing occurs for all statements executed, whether or not they run long enough to be logged, and “this can have an extremely negative impact on performance”.

What do I do once I find one?

Run EXPLAIN on the statement to see the plan the planner chose, then decide whether an index, a rewrite or fewer round trips is the answer. EXPLAIN ANALYZE actually runs the statement, so do not use it blindly on a statement that writes data.

How does SQLEye help?

SQLEye is not released yet and there are no downloads. This describes designed behaviour.

SQLEye is a free desktop app that runs local PostgreSQL instances and shows each query as it runs. It uses the same mechanism described above. When capture is turned on for an instance it sets logging_collector=on, log_destination='jsonlog' (so it needs PostgreSQL 15 or newer, which covers all versions in its catalogue) and log_min_duration_statement = 0, applies it with pg_reload_conf() and tails the JSON log. When capture is turned off it sets the threshold back to -1. Each statement appears with its duration, connection, database, user and application name, and anything at or above the slow threshold (100 ms by default, configurable) is marked slow.

Capture is off by default because logging every statement costs throughput. See slow queries for how the flag works, capture for what is changed on the server, and PostgreSQL in SQLEye for the managed config.

Documentation: Find slow queries. A query is slow when its duration reaches the threshold in Settings (default 100 ms). Use Slow only to list them and the Shapes tab to rank them.

postgresqlslow querieslogging

Related posts

Written by CodeROG, who develop SQLEye. CodeROG develops and maintains SQLEye, a free desktop app for running local PostgreSQL and MySQL and watching every query live. This post is also available as Markdown.