Find top SQL by elapsed time/CPU in a past period (AWR + V$SQLAREA)
OraclePerformanceCommand
-- AWR: top 20 by elapsed time within a snapshot range (per plan)
SELECT *
FROM (SELECT st.sql_id,
st.plan_hash_value,
SUM(st.executions_delta) AS execs,
ROUND(SUM(st.elapsed_time_delta)/1e6, 1) AS elapsed_s,
ROUND(SUM(st.cpu_time_delta)/1e6, 1) AS cpu_s,
ROUND(SUM(st.iowait_delta)/1e6, 1) AS io_wait_s,
SUM(st.buffer_gets_delta) AS buffer_gets,
ROUND(SUM(st.elapsed_time_delta)/1e3
/ NULLIF(SUM(st.executions_delta),0), 2) AS ms_per_exec,
MAX(st.parsing_schema_name) AS parsing_schema
FROM dba_hist_sqlstat st
WHERE st.dbid = (SELECT dbid FROM v$database)
AND st.snap_id BETWEEN <begin_snap> AND <end_snap>
GROUP BY st.sql_id, st.plan_hash_value
ORDER BY elapsed_s DESC)
WHERE ROWNUM <= 20;
-- For CPU ranking: ORDER BY cpu_s DESC
-- SQL text: SELECT DBMS_LOB.SUBSTR(sql_text, 4000, 1) FROM dba_hist_sqltext WHERE sql_id = '<sql_id>';
-- Plan history of a single SQL: @?/rdbms/admin/awrsqrpt.sql
-- Current (since instance startup, still in cache) by CPU:
SELECT sql_id,
ROUND(cpu_time/1e6,1) AS cpu_s,
ROUND(elapsed_time/1e6,1) AS elapsed_s,
executions, buffer_gets, disk_reads,
ROUND(cpu_time/1e3/NULLIF(executions,0),2) AS cpu_ms_per_exec,
parsing_schema_name,
SUBSTR(sql_text,1,80) AS sql_text
FROM v$sqlarea
WHERE parsing_schema_name NOT IN ('SYS','SYSTEM')
ORDER BY cpu_time DESC
FETCH FIRST 20 ROWS ONLY;What it does
Sums the *_DELTA columns in DBA_HIST_SQLSTAT to list the most expensive SQL in a snapshot range, broken down by plan_hash_value, which also reveals plan changes for the same SQL. The V$SQLAREA query gives cumulative values for what is still in the cache.
When to use it
For "what loaded the system last night between 02:00 and 04:00?", to detect plan changes (same sql_id, different plan_hash_value), and to build a list of tuning candidates.
Caution
Querying DBA_HIST_* requires the Diagnostics Pack license; V$SQLAREA does not. AWR keeps only top SQL (top-N by default), so small but very frequent statements may be missing. V$SQLAREA values are lost when the cursor ages out. Deltas remain correct across a restart, but the cache-based query starts from zero.
Related
- Take an AWR snapshot and generate an AWR report between two snapshots
- AWR diff (compare period) report between two periods
- Top wait events and top SQL from ASH for the last minutes
- Run an ADDM analysis and get its report
- Get a SQL Monitor report (running or completed long SQL)
- Enable/disable 10046 trace for a session and summarize with TKPROF