// SQL snippet

Find the most expensive queries in PostgreSQL

Rank by total time and both kinds of expensive query show up: the rare slow one and the fast one that runs a million times.

Main statement
PostgreSQL
还支持
SQL Server MySQL Oracle

The task

pg_stat_statements normalizes every executed statement (literals replaced by placeholders) and accumulates calls, total, min, max and mean execution time, rows and I/O. Ranking by total_exec_time lists the statements that account for the most server time across the whole workload. That is usually the first place to optimize: a 20 percent improvement to the top statement can be worth more than fixing the ten slowest queries you have ever seen.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and Oracle are under Variations.

PostgreSQL
SELECT calls,
       ROUND(total_exec_time::numeric, 1) AS total_ms,
       ROUND(mean_exec_time::numeric, 2) AS mean_ms,
       rows, rows / NULLIF(calls, 0) AS rows_per_call,
       ROUND(100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0), 1) AS cache_hit_pct,
       LEFT(query, 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

工作原理

total_exec_time is the sum of all executions since stats were reset (pg_stat_statements_reset). mean_exec_time splits it per call, and rows_per_call distinguishes a query returning 1 row from one returning 100,000; they need different fixes. shared_blks_hit and shared_blks_read give that statement's own buffer cache hit ratio. Setup takes two steps: add pg_stat_statements to shared_preload_libraries in postgresql.conf and restart, then run CREATE EXTENSION pg_stat_statements in the database you query from. A role without superuser or pg_read_all_stats sees <insufficient privilege> in place of the text of other users' statements.

Variations

SQL Server: sys.dm_exec_query_stats

SQL Server
SELECT TOP 20
    qs.execution_count,
    CAST(qs.total_elapsed_time / 1000.0 AS DECIMAL(18,1)) AS total_ms,
    CAST(qs.total_elapsed_time / 1000.0 / qs.execution_count AS DECIMAL(18,2)) AS mean_ms,
    LEFT(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1,
         (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text)
               ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1), 120) AS query
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
ORDER BY qs.total_elapsed_time DESC;

MySQL: performance_schema digest table

MySQL
SELECT SCHEMA_NAME,
       COUNT_STAR AS calls,
       ROUND(SUM_TIMER_WAIT / 1e12, 3) AS total_sec,
       ROUND(AVG_TIMER_WAIT / 1e9, 3) AS mean_ms,
       LEFT(DIGEST_TEXT, 120) AS digest
FROM performance_schema.events_statements_summary_by_digest
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 20;

Oracle: v$sql by elapsed time

Oracle
SELECT executions,
       ROUND(elapsed_time / 1000 / 1000, 3) AS total_sec,
       ROUND(elapsed_time / 1000 / 1000 / NULLIF(executions, 0), 4) AS mean_sec,
       SUBSTR(sql_text, 1, 120) AS sql_text
FROM v$sql
ORDER BY elapsed_time DESC
FETCH FIRST 20 ROWS ONLY;

Questions that come up

Total time or mean time: which should I optimize first?

Total time first if the goal is less load on the server; mean time first if the goal is a specific slow page or report. A query near the top of both lists goes first either way. Check rows_per_call before you start: a query with a high mean that returns 100,000 rows per call may need a smaller result, not a better plan.

Does pg_stat_statements slow the database down?

The overhead is small enough that most production systems, and most managed PostgreSQL services, run it permanently. It is a contrib module that ships with the standard PostgreSQL packages; enabling it needs the shared_preload_libraries entry and a restart. The cost that can show up is with many distinct statements: it keeps pg_stat_statements.max entries (5,000 by default) and evicts the least-used when full, so an application that generates unique SQL text churns that table.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.