The symptom
A query is slow on Oracle, or the instance is busy and nobody knows why. Oracle records what every session is waiting on, so the diagnosis is a matter of reading the right views in order. Two things to know first: the V$ views need SELECT_CATALOG_ROLE или SELECT ANY DICTIONARY, and Active Session History and AWR are part of the Diagnostics Pack, a separately licensed option on Enterprise Edition. The ASH queries below are marked; everything else is free to use.
Diagnose it
See what sessions are waiting on right now
SELECT sid, username, sql_id,
CASE WHEN state = 'WAITING' THEN event ELSE 'ON CPU' END AS activity,
CASE WHEN state = 'WAITING' THEN wait_class END AS wait_class,
round(CASE WHEN state = 'WAITING' THEN wait_time_micro
ELSE time_since_last_wait_micro END / 1e6, 1) AS seconds
FROM v$session
WHERE type = 'USER' AND status = 'ACTIVE'
ORDER BY seconds DESC;
Этот CASE matters: when state is anything other than WAITING, the session is on CPU and event still shows its previous wait, which misleads anyone reading the raw columns. Among the waits, wait_class sorts the problem: User I/O (db file sequential read, db file scattered read) is reads from disk, Application is mostly row locks, Concurrency is buffer busy waits and latches, Commit является log file sync on commit. A session waiting on enq: TX - row lock contention is blocked, not slow - the blocking and deadlocks guide picks that up.
Sample the recent past with ASH (Diagnostics Pack)
Active Session History samples every active session once a second into a memory buffer that typically holds the last hour or so, depending on how busy the instance is:
SELECT sql_id, sql_plan_hash_value,
COUNT(*) AS samples,
round(RATIO_TO_REPORT(COUNT(*)) OVER () * 100) AS pct
FROM v$active_session_history
WHERE sample_time > SYSTIMESTAMP - INTERVAL '15' MINUTE
GROUP BY sql_id, sql_plan_hash_value
ORDER BY samples DESC
FETCH FIRST 10 ROWS ONLY;
Each sample is roughly one second of someone's wait or CPU, so the count is a workload profile: the SQL with the most samples owns the problem. Add session_state и event to the GROUP BY to see whether it was burning CPU or waiting. For older incidents, dba_hist_active_sess_history keeps one in ten samples for the AWR retention period (8 days by default).
Get the real plan with actual row counts
Run the query once with the gather hint, then read the plan it produced in the same session. In SQL*Plus, SET SERVEROUTPUT OFF first; otherwise DISPLAY_CURSOR(NULL, NULL) shows the plan of the DBMS_OUTPUT call SQL*Plus runs after your query:
SELECT /*+ gather_plan_statistics */ o.order_id, c.cust_name
FROM orders o JOIN customers c ON c.customer_id = o.customer_id
WHERE o.status = 'PENDING';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));
Этот A-Rows column is actual rows; compare it with E-Rows on every line, remembering that E-Rows is per execution of the line and A-Rows is the total across all its Starts. Where actual dwarfs estimated, the optimizer guessed wrong - fix statistics before anything else. Buffers shows the logical reads, the number that tracks CPU and I/O cost. A note saying dynamic statistics used usually means a table in the query has no statistics at all. Format the SQL with the Форматировщик SQL and paste the plan into the query plan viewer to read it without SQL Developer open.
Rank the SQL that reads the most (no pack needed)
SELECT sql_id, executions, buffer_gets,
round(buffer_gets / executions) AS gets_per_exec,
round(cpu_time / 1e6, 1) AS cpu_seconds,
round(elapsed_time / 1e6, 1) AS elapsed_seconds
FROM v$sqlstats
WHERE executions > 0
ORDER BY buffer_gets DESC
FETCH FIRST 10 ROWS ONLY;
The figures are cumulative while the statement stays in the shared pool, and times are in microseconds. FETCH FIRST needs Oracle 12c or later; on 11g wrap the query and filter on ROWNUM. Look up the text of any sql_id в v$sqlstats.sql_fulltext.
Fix it
Fix the statistics where estimates lie. The automatic statistics job (nightly maintenance window) covers most tables, and with the default method_opt it builds histograms on columns it has seen used in predicates. Tables loaded in bulk after the job ran, and skewed columns it missed, need a manual gather:
EXEC DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS', method_opt => 'FOR COLUMNS status SIZE 254');
Index the path the plan walks. If the plan does a full scan on a big table for a selective predicate, add the index on the predicate columns and confirm the plan switches to an index range scan with far fewer buffers.
Reduce logical reads on hot statements. The SQL with the most buffer gets is where CPU and I/O both come from; covering indexes (add the selected columns) and rewrites that stop fetching the same rows repeatedly are the usual wins. The high CPU guide continues from here.
Check memory before resizing. If the waits are dominated by User I/O, ask the buffer cache advisory how much a bigger cache would save before touching sga_target — memory pressure guide покрывает v$db_cache_advice and the PGA advisory.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Query v$session and name what active sessions are doing: ON CPU or the dominant wait_class.
- With the Diagnostics Pack, sample the last 15 minutes of ASH; without it, rank v$sqlstats by elapsed time.
- Run the top SQL with /*+ gather_plan_statistics */ and DISPLAY_CURSOR ALLSTATS LAST.
- Compare A-Rows with E-Rows per plan line; refresh statistics where they diverge.
- Rank v$sqlstats by buffer_gets and target the leader.
- Add or extend the index the plan is missing; confirm the plan changed and buffers dropped.
- Check DBA_INDEX_USAGE (12.2+) over a full business cycle before dropping any 'unused' index.
Questions that come up
What is the difference between ASH and AWR?
ASH samples which sessions were active and what they waited on, every second, in a memory buffer that covers roughly the last hour - use it to find the SQL that owned a recent slowdown. AWR takes a workload snapshot (SQL stats, system stats and every tenth ASH sample) every hour and keeps it for 8 days by default - use it to compare periods. ASH answers 'what just happened', AWR answers 'what changed between last week and now'.
Do I need the Diagnostics or Tuning Pack for any of this?
Partly. v$session, v$sqlstats, v$sql and DBMS_XPLAN.DISPLAY_CURSOR are part of the database and need no extra license. v$active_session_history, the DBA_HIST views and AWR reports belong to the Diagnostics Pack, which is licensed separately on Enterprise Edition and not available on Standard Edition; the Tuning Pack adds SQL Tuning Advisor and SQL Monitoring. The control_management_pack_access parameter shows what the instance is set to allow, but setting it does not grant a license. Polling v$session and diffing v$sqlstats covers most of what ASH tells you.
The plan has a full table scan - is that automatically wrong?
No. For a query returning a large share of the table, a full scan with multiblock reads is cheaper than thousands of index probes. The number that decides is logical reads (Buffers) per row returned: if a full scan reads fewer buffers than the indexed alternative would, the optimizer is right and the rewrite should target returning fewer rows.
Why do the E-Rows and A-Rows diverge so much on one line?
The optimizer estimated from statistics that no longer match the data - skewed columns, recently bulk-loaded data, or a predicate the stats do not describe. Gather stats with a method_opt that keeps histograms on the skewed column, then re-check. Persistent divergence on the same line is the single most common cause of a bad plan.
Can I read execution plans without SQL Developer?
Yes. DBMS_XPLAN output is plain text you can paste into SQLly's free query plan viewer at /tools/query-plan-viewer, and the SQLly desktop app opens plan output in its built-in plan viewer next to the query editor.