How to find slow PostgreSQL queries
Doha I. · Published · Lire en français

Enable the pg_stat_statements extension, then list queries by total time to find what costs the database the most, and by mean time to find individually slow queries. Check whether they scan large tables (missing index), return too many rows, or run too often (an N+1 pattern), then fix the biggest one first and measure again.
When an application slows down, the cause is usually a handful of queries. Finding them is the first step, and PostgreSQL gives you the tool.
Start with pg_stat_statements
pg_stat_statements is a PostgreSQL extension that records statistics for every normalized query: how many times it ran, total and mean execution time, and rows returned.
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time) AS mean_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Read the numbers
- High total time: the queries that cost the database the most overall. Often a fast query that runs very often.
- High mean time: individually slow queries, the ones users feel.
- Many calls with few rows each: often an N+1 pattern in the application.
Fix, then measure
- Missing index? Run
EXPLAIN ANALYZEand look for sequential scans on large tables. - Too many rows? Paginate, select only the needed columns.
- Too many calls? Batch them or cache results (Redis is good at this).
- Connection waits? Check pooling before blaming the query.
Then reset the statistics or compare over a fixed period, and repeat with the next query.
Query analytics on LordBase
LordBase's query analytics reads pg_stat_statements for you: a summary, query statistics sortable by total time, calls, mean time or rows, slow queries above a threshold (1,000 ms of mean time by default) and the queries running right now. You can see them in the dashboard, call them from the API, or ask an AI assistant connected through the MCP server, "which queries are slowing my app down?".
