Running SQL and Long-Running Queries
When you get a report that "the database is slow," first look at what is running right now. All three databases let you see start time, waits, and the SQL text from a list of running requests. Sorted by longest running first, the cause is usually near the top.
Progress appears only for operations where the database knows the total amount of work (full scans, index builds, backups, VACUUM, and so on). None of the databases can tell you exactly when an ordinary SELECT will finish.
Oracle
Required privileges: SELECT on V$SESSION, V$SQL, and V$SESSION_LONGOPS (SELECT_CATALOG_ROLE). SQL Monitor requires a Tuning Pack license.
Running SQL
SELECT s.sid, s.serial#, s.username, s.sql_id, s.sql_child_number,
s.sql_exec_start, ROUND((SYSDATE - s.sql_exec_start) * 86400) AS run_sec,
s.event, s.wait_class, s.blocking_session,
SUBSTR(q.sql_text, 1, 100) AS sql_text
FROM v$session s
LEFT JOIN v$sql q ON q.sql_id = s.sql_id AND q.child_number = s.sql_child_number
WHERE s.status = 'ACTIVE'
AND s.type = 'USER'
AND s.sid <> SYS_CONTEXT('USERENV', 'SID')
ORDER BY s.sql_exec_start;
sql_exec_startis when the current statement started.last_call_etis based on the whole PL/SQL call, so it can differ.- View the full statement with
SELECT sql_fulltext FROM v$sql WHERE sql_id = '...';. For the execution plan, see Viewing Cached Execution Plans. - A parallel query shows the coordinator (QC) and the slaves separately. Group them by
qcsidinV$PX_SESSION.
Progress of long-running operations
SELECT sid, serial#, opname, target, sofar, totalwork, units,
ROUND(sofar / NULLIF(totalwork, 0) * 100, 1) AS pct,
elapsed_seconds, time_remaining, sql_id
FROM v$session_longops
WHERE totalwork > 0
AND sofar <> totalwork
ORDER BY start_time;
- Only single operations lasting more than 6 seconds are recorded (full table scan, hash join, sort, RMAN backup, statistics gathering, and so on).
- If one SQL goes through several stages, one row is created per stage and then ends. It is not the progress of the whole query.
time_remainingis the number of seconds computed from the speed so far.
Step-by-step progress with SQL Monitor
Parallel queries, and statements that use more than 5 seconds of CPU or I/O, are monitored automatically. You can also force it with the /*+ MONITOR */ hint.
SELECT sql_id, sql_exec_id, status, username, sql_exec_start,
elapsed_time / 1e6 AS elapsed_sec, cpu_time / 1e6 AS cpu_sec, buffer_gets
FROM v$sql_monitor
WHERE status = 'EXECUTING'
ORDER BY sql_exec_start;
SELECT DBMS_SQLTUNE.REPORT_SQL_MONITOR(sql_id => '7h35uxf5uhmm1', type => 'TEXT')
FROM dual;
The report shows, for each step of the execution plan, the rows processed so far, the time, and which step is currently running. Finished executions remain for a while.
Canceling only the running statement
ALTER SYSTEM CANCEL SQL '123, 45678'; -- 'sid, serial#' (Oracle 18c+)
ALTER SYSTEM CANCEL SQL '123, 45678, 7h35uxf5uhmm1'; -- cancels only if the sql_id matches
WARNING The session stays, and only that statement fails with
ORA-01013. Data changed by the statement is rolled back, but earlier statements in the same transaction remain.
PostgreSQL
Required privileges: pg_read_all_stats to see other users' query text. Progress views show rows for other users too, but some columns are visible only with the same privilege.
Running SQL
SELECT pid, usename, datname, now() - query_start AS running_for,
wait_event_type, wait_event, query_id, -- query_id: PostgreSQL 14+
left(query, 100) AS query
FROM pg_stat_activity
WHERE state = 'active'
AND backend_type = 'client backend'
AND pid <> pg_backend_pid()
ORDER BY query_start;
- If
wait_eventis empty, the backend is using CPU. query_idis populated whencompute_query_idis on (withauto, whenpg_stat_statementsis used), and it is the same value aspg_stat_statements.queryid.- Workers of a parallel query appear as
backend_type = 'parallel worker'and are grouped with their leader byleader_pid(13+).
Progress views
| Operation | View | Version |
|---|---|---|
| VACUUM | pg_stat_progress_vacuum | 9.6+ |
| CREATE INDEX, REINDEX | pg_stat_progress_create_index | 12+ |
| CLUSTER, VACUUM FULL | pg_stat_progress_cluster | 12+ |
| ANALYZE | pg_stat_progress_analyze | 13+ |
| pg_basebackup | pg_stat_progress_basebackup | 13+ |
| COPY | pg_stat_progress_copy | 14+ |
-- Index build
SELECT p.pid, p.relid::regclass AS table_name, p.index_relid::regclass AS index_name,
p.phase, p.blocks_done, p.blocks_total,
ROUND(100.0 * p.blocks_done / NULLIF(p.blocks_total, 0), 1) AS block_pct,
p.tuples_done, p.tuples_total
FROM pg_stat_progress_create_index p;
-- VACUUM
SELECT p.pid, p.relid::regclass AS table_name, p.phase,
p.heap_blks_scanned, p.heap_blks_vacuumed, p.heap_blks_total,
ROUND(100.0 * p.heap_blks_scanned / NULLIF(p.heap_blks_total, 0), 1) AS scan_pct,
p.index_vacuum_count
FROM pg_stat_progress_vacuum p;
- Progress is counted again in each phase (
phase).CREATE INDEXpasses through table scan, sort, and tree build phases in turn. - If VACUUM's
index_vacuum_countkeeps rising, the memory for holding dead tuples (maintenance_work_mem) is too small and the indexes are being scanned multiple times.
Execution time limit
SET statement_timeout = '5min'; -- this session only
ALTER ROLE report_user SET statement_timeout = '10min';
Cancel a statement that is already running with pg_cancel_backend(pid) (Viewing and Killing Sessions).
SQL Server
Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+).
Running SQL
SELECT r.session_id, r.status, r.command, DB_NAME(r.database_id) AS db,
r.start_time, r.total_elapsed_time / 1000 AS elapsed_sec,
r.cpu_time / 1000 AS cpu_sec, r.logical_reads,
r.wait_type, r.blocking_session_id, r.dop,
SUBSTRING(t.text, r.statement_start_offset / 2 + 1,
(CASE r.statement_end_offset WHEN -1 THEN DATALENGTH(t.text)
ELSE r.statement_end_offset END - r.statement_start_offset) / 2 + 1) AS stmt
FROM sys.dm_exec_requests r
JOIN sys.dm_exec_sessions s ON s.session_id = r.session_id
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) t
WHERE s.is_user_process = 1
AND r.session_id <> @@SPID
ORDER BY r.total_elapsed_time DESC;
stmtis the statement currently running inside the batch or procedure. The full batch ist.text.status:running(using CPU),runnable(waiting for its turn on CPU),suspended(waiting; seewait_type).- The
dopcolumn exists in SQL Server 2016+.
Operations that report progress
SELECT r.session_id, r.command, r.percent_complete,
r.estimated_completion_time / 1000 / 60 AS remaining_min,
r.total_elapsed_time / 1000 / 60 AS elapsed_min
FROM sys.dm_exec_requests r
WHERE r.percent_complete > 0;
percent_complete is populated only for certain commands, such as BACKUP, RESTORE, DBCC CHECKDB, DBCC SHRINKFILE, ALTER INDEX REORGANIZE, ROLLBACK, and database recovery. For SELECT and ALTER INDEX REBUILD it is 0.
Per-operator progress of a running query
sys.dm_exec_query_profiles shows, for each node of the execution plan, the rows processed so far and the estimated rows. Lightweight profiling must be on (the default in 2019+; in 2016 SP1 to 2017, use trace flag 7412 or have the query collect the actual plan).
SELECT node_id, physical_operator_name, row_count, estimate_row_count,
CAST(100.0 * row_count / NULLIF(estimate_row_count, 0) AS decimal(9, 1)) AS pct_of_estimate
FROM sys.dm_exec_query_profiles
WHERE session_id = 57
ORDER BY node_id;
- If
row_counthas greatly exceededestimate_row_countand keeps growing, the estimate was wrong and the query is taking longer than expected. - To get the current execution plan and live statistics as XML, use
SELECT * FROM sys.dm_exec_query_statistics_xml(57);(2016 SP1+). Live Query Statistics in SSMS uses the same information.