Skip to content

Find slow queries in PostgreSQL

Use pg_stat_statements to find statements that consume the most execution time across repeated calls. Run this in the database you want to inspect:

SELECT query, calls,
total_exec_time / 1000 AS total_seconds,
mean_exec_time / 1000 AS average_seconds,
max_exec_time / 1000 AS maximum_seconds
FROM pg_stat_statements
WHERE dbid = (
SELECT oid FROM pg_database
WHERE datname = current_database()
)
ORDER BY total_exec_time DESC
LIMIT 100;

A high total can come from frequent short calls or a few long calls. Compare calls and average_seconds before choosing a query to investigate. These counters cover retained statistics, rather than only queries running now.

Find slow queries in PostgreSQL with TableAI

Section titled “Find slow queries in PostgreSQL with TableAI”
  1. Open Admin › Slow Queries.
  2. Set Min duration: to the minimum average execution time, in seconds.
  3. Select a statement to inspect its calls and timings.
  4. Choose EXPLAIN, when available, to inspect the plan.

TableAI loads up to 100 statements ordered by total execution time for the current database. The duration filter applies to that list; its default is 0.1 seconds. Set it to zero when investigating frequent short statements.

Slow Queries showing call counts and average, total, and maximum execution times

Review the statement before EXPLAIN ANALYZE: that command executes it and can change data. See diagnose performance for plan inspection.

The server must preload pg_stat_statements, and the current database must have the extension installed. Loading the module requires a server restart. Follow the setup steps or ask your database administrator to enable it.

Your role also needs statistics access. Reading other users’ query text can require pg_read_all_stats or superuser access. See PostgreSQL’s extension reference.