Top SQL by Load

When the whole database is heavy rather than one specific query, first look at which SQL uses the most resources. All three databases keep cumulative per-statement execution statistics in memory. Sorted by total, a handful of statements often account for most of the database load.

There are three criteria to look at: total CPU (when CPU is busy), total logical reads (inefficient queries that scan many buffers), and execution count (queries that are fast once but called too often). Also look at the per-execution values, to tell whether the thing to fix is the query or the way it is called.

Statistics in memory disappear when the plan is evicted from the cache or on restart. To look at past periods, use AWR in Oracle, periodically taken snapshots in PostgreSQL, and Query Store in SQL Server.

Oracle

Required privileges: SELECT on V$SQLSTATS and V$SQL (SELECT_CATALOG_ROLE). AWR (DBA_HIST_*) requires a Diagnostics Pack license.

Top SQL in the shared pool

SELECT sql_id, plan_hash_value, executions,
       ROUND(cpu_time / 1e6) AS cpu_sec,
       ROUND(elapsed_time / 1e6) AS elapsed_sec,
       buffer_gets, disk_reads, rows_processed,
       ROUND(buffer_gets / NULLIF(executions, 0)) AS gets_per_exec,
       SUBSTR(sql_text, 1, 80) AS sql_text
FROM v$sqlstats
ORDER BY cpu_time DESC              -- try buffer_gets, executions, elapsed_time in turn
FETCH FIRST 20 ROWS ONLY;
  • V$SQLSTATS has one row per SQL_ID and plan combination and is cheaper to query than V$SQL. Time columns are in microseconds.
  • The full statement is in the sql_fulltext column.
  • The statistics are cumulative since the instance started, or since the cursor entered the shared pool. Take two snapshots and compare them instead of reading a single point in time to see the current load.

Grouping SQL that differs only in literals

SQL executed with only the values changed, without bind variables, gets separate SQL_IDs, so no single one appears near the top. Group them with force_matching_signature.

SELECT force_matching_signature, COUNT(*) AS sql_ids,
       SUM(executions) AS executions, ROUND(SUM(cpu_time) / 1e6) AS cpu_sec,
       MAX(sql_id) AS sample_sql_id
FROM v$sqlstats
WHERE force_matching_signature <> 0
GROUP BY force_matching_signature
HAVING COUNT(*) > 10
ORDER BY cpu_sec DESC
FETCH FIRST 20 ROWS ONLY;

Top SQL for a past period (AWR)

SELECT st.sql_id, st.plan_hash_value,
       SUM(st.executions_delta) AS executions,
       ROUND(SUM(st.cpu_time_delta) / 1e6) AS cpu_sec,
       ROUND(SUM(st.elapsed_time_delta) / 1e6) AS elapsed_sec,
       SUM(st.buffer_gets_delta) AS buffer_gets
FROM dba_hist_sqlstat st
JOIN dba_hist_snapshot sn
  ON sn.snap_id = st.snap_id AND sn.dbid = st.dbid AND sn.instance_number = st.instance_number
WHERE sn.begin_interval_time >= TIMESTAMP '2026-11-25 09:00:00'
  AND sn.end_interval_time   <= TIMESTAMP '2026-11-25 12:00:00'
GROUP BY st.sql_id, st.plan_hash_value
ORDER BY cpu_sec DESC
FETCH FIRST 20 ROWS ONLY;
  • The *_delta columns hold the values for that snapshot interval. Find the statement text in DBA_HIST_SQLTEXT.
  • AWR does not store all SQL, only the top SQL of each interval (the topnsql setting of DBMS_WORKLOAD_REPOSITORY).
  • Generate a formatted report with @?/rdbms/admin/awrrpt.sql (the whole interval) or @?/rdbms/admin/awrsqrpt.sql (one SQL). The "SQL ordered by CPU Time" and "SQL ordered by Gets" sections contain the same information.

PostgreSQL

Required privileges: installing the pg_stat_statements extension requires superuser. pg_read_all_stats to see other users' query text.

Enabling pg_stat_statements

-- postgresql.conf (restart required)
-- shared_preload_libraries = 'pg_stat_statements'

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

WARNING Changing shared_preload_libraries requires a server restart. If it already has a value, do not remove it; append with a comma.

Top SQL

SELECT queryid, calls,
       ROUND(total_exec_time::numeric / 1000, 1) AS total_sec,
       ROUND(mean_exec_time::numeric, 2) AS mean_ms,
       rows,
       shared_blks_hit + shared_blks_read AS logical_reads,
       shared_blks_read,
       ROUND(100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct,
       left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC       -- try logical_reads, calls in turn
LIMIT 20;
  • Column names are for PostgreSQL 13+ (12 and earlier use total_time, mean_time).
  • Times are in milliseconds and are elapsed time, not CPU time. There is no column that measures CPU alone. I/O time accumulates in the blk_read_time and blk_write_time columns when track_io_timing is on (in 17+ they are split into shared_blk_read_time, local_blk_read_time, and so on).
  • Literals are replaced with $1 and similar, so queries of the same shape are grouped into one row. The same statement still appears separately for a different user or database (userid, dbid).
  • To include planning time, turn on pg_stat_statements.track_planning = on (total_plan_time).

Checking whether the statistics overflow

SELECT current_setting('pg_stat_statements.max') AS max_entries,
       (SELECT COUNT(*) FROM pg_stat_statements) AS entries;

SELECT dealloc, stats_reset FROM pg_stat_statements_info;   -- PostgreSQL 14+

If dealloc keeps rising, entries have exceeded the limit (default 5000) and rarely used statements are being evicted. Raising the limit requires a restart.

Resetting to compare intervals

SELECT pg_stat_statements_reset();

WARNING This clears all accumulated statistics. If another monitoring tool uses these statistics, its values break as well. Rather than resetting, it is better to copy them into a table periodically and look at the differences.

SQL Server

Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+). To query Query Store, VIEW DATABASE STATE on that database.

Top SQL in the plan cache

SELECT TOP (20)
       qs.execution_count,
       qs.total_worker_time / 1000 AS cpu_ms,
       qs.total_elapsed_time / 1000 AS elapsed_ms,
       qs.total_logical_reads, qs.total_physical_reads,
       qs.total_logical_reads / qs.execution_count AS reads_per_exec,
       qs.creation_time, qs.last_execution_time,
       SUBSTRING(t.text, qs.statement_start_offset / 2 + 1,
                 (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(t.text)
                       ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1) AS stmt
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) t
ORDER BY qs.total_worker_time DESC;   -- try total_logical_reads, execution_count in turn
  • There is one row per statement (one statement within a batch). Time columns are in microseconds.
  • Values are cumulative since creation_time, when the plan entered the cache. A statement that was recompiled recently looks small.
  • Plans that do not stay in the cache, such as OPTION (RECOMPILE) statements, do not appear here or keep only the last execution.
  • To view by procedure, use sys.dm_exec_procedure_stats.

Grouping SQL that differs only in literals

SELECT TOP (20) qs.query_hash,
       COUNT(*) AS plans, SUM(qs.execution_count) AS executions,
       SUM(qs.total_worker_time) / 1000 AS cpu_ms,
       SUM(qs.total_logical_reads) AS logical_reads
FROM sys.dm_exec_query_stats qs
GROUP BY qs.query_hash
ORDER BY cpu_ms DESC;

Top SQL for a past period (Query Store)

Query Store is available in SQL Server 2016+ and is on by default for new databases from 2022. Run this in that database.

SELECT TOP (20) q.query_id, p.plan_id,
       SUM(rs.count_executions) AS executions,
       SUM(rs.avg_cpu_time * rs.count_executions) / 1000 AS cpu_ms,
       SUM(rs.avg_logical_io_reads * rs.count_executions) AS logical_reads,
       SUM(rs.avg_duration * rs.count_executions) / 1000 AS duration_ms,
       LEFT(qt.query_sql_text, 100) AS query_text
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_runtime_stats_interval i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id
JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
JOIN sys.query_store_query q ON q.query_id = p.query_id
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
WHERE i.start_time >= '2026-11-25 09:00' AND i.end_time <= '2026-11-25 12:00'
GROUP BY q.query_id, p.plan_id, qt.query_sql_text
ORDER BY cpu_ms DESC;
  • Statistics are stored as averages (avg_*) and counts, so compute totals by multiplying. The time unit is microseconds.
  • Interval times (start_time, end_time) are datetimeoffset and stored in UTC.
  • The "Top Resource Consuming Queries" report in SSMS uses the same data.
ALTER DATABASE sales SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);

WARNING Query Store stores its data inside that database. When it reaches the size limit (MAX_STORAGE_SIZE_MB), it switches to read-only and stops collecting, so check actual_state_desc in sys.database_query_store_options.