DBAtlas · Database operations atlas

Find the slowest / most expensive queries

Oracle

SELECT sql_id,
       ROUND(elapsed_time/1e6, 1) AS elapsed_sec,
       executions,
       ROUND(elapsed_time/1e6/NULLIF(executions,0), 3) AS sec_per_exec,
       sql_text
FROM v$sql
ORDER BY elapsed_time DESC
FETCH FIRST 10 ROWS ONLY;

For historical analysis use AWR: dba_hist_sqlstat. With the sql_id, DBMS_XPLAN.DISPLAY_CURSOR shows the plan.

PostgreSQL

SELECT calls,
       ROUND(total_exec_time::numeric, 1) AS total_ms,
       ROUND(mean_exec_time::numeric, 2) AS mean_ms,
       query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

Requires the pg_stat_statements extension (shared_preload_libraries). Reset with pg_stat_statements_reset().

MySQL

SELECT digest_text,
       count_star AS calls,
       ROUND(sum_timer_wait/1e12, 2) AS total_sec,
       ROUND(avg_timer_wait/1e9, 2) AS avg_ms
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC
LIMIT 10;

Alternative: the slow query log with slow_query_log = ON and long_query_time.

SQL Server

SELECT TOP 10
       qs.execution_count,
       qs.total_elapsed_time/1000 AS total_ms,
       qs.total_elapsed_time/qs.execution_count/1000 AS avg_ms,
       SUBSTRING(t.text, 1, 200) AS sql_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) t
ORDER BY qs.total_elapsed_time DESC;

If Query Store is enabled, use sys.query_store_runtime_stats for richer historical analysis.

MongoDB

// Enable the profiler for operations over 100ms:
db.setProfilingLevel(1, { slowms: 100 })
// Then read the slowest ones:
db.system.profile.find().sort({ millis: -1 }).limit(10)

The profiler adds write overhead; turn it off with db.setProfilingLevel(0) after diagnostics.

Redis

SLOWLOG GET 10
# Set the threshold (microseconds): CONFIG SET slowlog-log-slower-than 10000

slowlog-log-slower-than is in microseconds (10000 = 10 ms). Clear it with SLOWLOG RESET.

Open in DBAtlas →