Summary
What pg_stat_statements is in PostgreSQL, what Performance Schema is in MySQL, what Query Store is in SQL Server, AWR + ASH is in Oracle. But Oracle has one difference: AWR is not only query statistics, it is the health report of the whole database. When the system slows down, adding an index by guess or changing a parameter is forbidden. First we measure. In this guide you will learn how AWR snapshots work, how to find the 20 most expensive queries by total time, how to diagnose the top 3 queries precisely, how to detect plan changes, and how to decide the fix. This article is the first cluster that starts the Oracle leg of the Performance Pillar.
Scenario
Time is 11:42. The application team writes: Pages open in 8 seconds, yesterday it was 400 ms. CPU is at 90%, disk I/O is maxed out. The team says let's scale up the server. The DBA says stop, let's measure first. Because a deploy happened last night. Maybe a new query was added. Maybe an index was deleted. Maybe a plan changed. Maybe statistics were updated. In Oracle, plan changes are more insidious than in other engines. Because the same query can run with a good plan yesterday and a bad plan today. This is called plan change, in Oracle language plan instability. Scaling up by guess hides the problem. First we need to find which query is eating the system and whether its plan changed.
Concept: What Are AWR and ASH?
Oracle has 2 main measurement systems. Do not confuse them.
▸AWR — Automatic Workload Repository
AWR takes a photo of the system at certain intervals. By default it takes a snapshot every 60 minutes and keeps it for 8 days. Each snapshot records the most expensive queries of that hour, wait events, I/O statistics, and memory usage.
Analogy: Think of it like a security camera. It takes 1 photo every hour. Then you compare those photos. You see the difference between yesterday at 11 and today at 11.
▸ASH — Active Session History
ASH records every second what active sessions do. Which session runs which query, in which wait event, with which SQL ID — it records all of them second by second.
Analogy: If AWR is a photo, ASH is a video. AWR takes an hourly photo, ASH records video second by second. ASH is needed to understand the crisis moment.
The 3 most important sources:
- •AWR: Hourly snapshot, persistent measurement and plan history.
- •ASH: Second-by-second active session history.
- •V$SQL: Real-time query statistics. Total time, execution count, and plan of queries currently in cache.
Step 0: Is AWR On? License Check
First check that AWR is on and the license is appropriate.
SELECT snap_id, begin_interval_time, end_interval_time, snap_level
FROM dba_hist_snapshot
ORDER BY snap_id DESC
FETCH FIRST 10 ROWS ONLY;If the last snapshot is older than 1 hour, AWR is not working. Check snapshot interval:
SELECT snap_interval, retention, topnsql
FROM dba_hist_wr_control;Recommended settings for production:
BEGIN
DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(
retention => 11520, -- 8 days, in minutes
interval => 60, -- 60 minutes
topnsql => 50 -- Keep top 50 expensive queries
);
END;
/License warning: AWR and ASH require an Oracle Diagnostics Pack license. Usually included in Enterprise Edition but not in Standard Edition 2. If you have no license, do not use AWR. Use V$SQL and V$SESSION views instead. Using AWR without a license causes problems in audits. First verify your license, then use AWR.
Step 1: Find the 20 Most Expensive Queries
This is the main query. It sorts by total time.
SELECT * FROM (
SELECT
SUBSTR(sql_text, 1, 150) AS query_text,
executions AS exec_count,
ROUND(elapsed_time / 1000000 / NULLIF(executions, 0), 2) AS avg_time_sec,
ROUND(elapsed_time / 1000000, 2) AS total_time_sec,
ROUND(cpu_time / 1000000, 2) AS total_cpu_sec,
ROUND(buffer_gets / NULLIF(executions, 0), 0) AS avg_buffer_gets,
ROUND(rows_processed / NULLIF(executions, 0), 0) AS avg_rows,
sql_id,
last_active_time
FROM v$sql
WHERE executions > 0
AND last_active_time > SYSDATE - 1
ORDER BY elapsed_time DESC
)
WHERE ROWNUM <= 20;More persistent way, look from AWR history:
SELECT * FROM (
SELECT
SUBSTR(st.sql_text, 1, 150) AS query_text,
ss.executions_total AS exec_count,
ROUND(ss.elapsed_time_total / 1000000 / NULLIF(ss.executions_total, 0), 2) AS avg_time_sec,
ROUND(ss.elapsed_time_total / 1000000, 2) AS total_time_sec,
ROUND(ss.cpu_time_total / 1000000, 2) AS total_cpu_sec,
ROUND(ss.buffer_gets_total / NULLIF(ss.executions_total, 0), 0) AS avg_buffer_gets,
st.sql_id
FROM dba_hist_sqlstat ss
JOIN dba_hist_sqltext st ON st.sql_id = ss.sql_id
WHERE ss.snap_id BETWEEN 100 AND 110
ORDER BY ss.elapsed_time_total DESC
)
WHERE ROWNUM <= 20;▸How to Read the Output?
- •
total_time_sec: This is the query that tires the system the most. Look at this first. - •
avg_time_sec: If a single query is fast but runs many times, it may be N+1. - •
avg_buffer_gets / avg_rows: If the ratio is over 100, the query reads unnecessary rows. The index may be missing. - •
total_cpu_sec: If CPU is high but buffer gets are low, the query may do CPU-intensive work. Functions, sorting, hash.
▸Quick Look with AWR Report
Easiest way is to generate an AWR report:
-- In SQL*Plus
@?/rdbms/admin/awrrpt.sqlThe report is generated in HTML or text format. In the report, look at the SQL ordered by Elapsed Time section. The most expensive queries are there. If you click a query, you see its plan history. This is ideal for quick diagnosis without writing queries.
Step 2: Diagnose the Top 3 Queries Precisely
You found the 20 most expensive queries. Now focus on the top 3.
For each query, answer 3 questions:
▸Question 1: Is the Query Really Slow, or Does It Run Too Often?
- •Slow query: Average time is high, execution count is low. Solution: Index, plan, query design.
- •Frequent query: Average time is low, execution count is very high. Solution: N+1 fix, cache, batch.
We made the same distinction in PostgreSQL, MySQL, and SQL Server articles. In Oracle the rule is the same.
▸Question 2: Is the Plan Bad? Did the Plan Change?
This is the most important Oracle-specific question.
-- List plan history of a SQL ID
SELECT
plan_hash_value,
timestamp,
executions_total,
ROUND(elapsed_time_total / 1000000 / NULLIF(executions_total, 0), 2) AS avg_time_sec,
ROUND(buffer_gets_total / NULLIF(executions_total, 0), 0) AS avg_buffer_gets
FROM dba_hist_sqlstat
WHERE sql_id = 'abc123xyz'
ORDER BY timestamp DESC;If the same query ran with an average of 100 ms yesterday and 5000 ms today, and plan_hash_value changed, there is a plan change. The query did not change, the plan changed. Reasons:
- •Statistics were updated.
- •An index was added or deleted.
- •Data distribution changed.
- •Bind variable peeking problem occurred.
- •Adaptive plan changed.
To see the plan:
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('abc123xyz', NULL, 'ALLSTATS LAST'));When looking at the plan, watch for:
- •TABLE ACCESS FULL: Scans the whole table. Disaster on a large table.
- •INDEX RANGE SCAN: Index range scan. Usually good.
- •INDEX UNIQUE SCAN: Index scan for a single row. Best.
- •NESTED LOOPS: Fast for small data, disaster for large data.
- •HASH JOIN: Normal for large data but can pressure memory.
- •SORT ORDER BY: Uses memory for sorting. Can be fixed with an index.
- •PX COORDINATOR: Parallel query coordinator. Means it runs in parallel.
▸Question 3: Does the Query Use an Index?
To find missing indexes, check the plan. If the plan does TABLE ACCESS FULL and the table is large, the index is missing.
Find unused indexes too:
SELECT
index_name,
table_name,
monitoring,
used
FROM v$object_usage
WHERE used = 'NO';First turn on index monitoring:
ALTER INDEX idx_orders_customer MONITORING USAGE;Monitor for 30 days. If never used, consider deleting. But do not delete immediately. It may be for a report that runs once a month.
Step 3: Look at Currently Running Queries — With ASH
Past summary is not enough. Look at what is running now. ASH is the most powerful tool for this.
SELECT
session_id,
session_serial# AS serial_no,
sql_id,
event AS wait_event,
wait_time / 1000000 AS wait_sec,
blocking_session AS blocking_session,
SUBSTR(sql_text, 1, 120) AS query_text
FROM v$session
WHERE status = 'ACTIVE'
AND type = 'USER'
AND sql_id IS NOT NULL
ORDER BY wait_time DESC;Look at the most common wait events:
SELECT
event AS wait_event,
COUNT(*) AS cnt,
ROUND(SUM(wait_time) / 1000000, 2) AS total_wait_sec
FROM v$active_session_history
WHERE sample_time > SYSDATE - 1/24
GROUP BY event
ORDER BY total_wait_sec DESC
FETCH FIRST 20 ROWS ONLY;Interpret wait events:
- •
db file sequential read: Single block read, index read. Normal but if too many, there may be an index problem. - •
db file scattered read: Multi-block read, full table scan. Index may be missing. - •
log file sync: Commit waiting. Seen in write-heavy systems. - •
enq: TX - row lock contention: Row lock waiting. Will be covered in detail in the next lock cluster. - •
direct path read: Direct disk read for parallel queries or large sorts. - •
latch: cache buffers chains: Memory latch contention. Buffer Cache pressure exists.
Step 4: Decide the Fix
Diagnosis is complete. Now decide. Choose 1 action per query.
▸Decision 1: Add an Index
If the plan does TABLE ACCESS FULL and the table is large, add an index.
-- First test in a test environment
CREATE INDEX idx_orders_customer_status
ON orders (customer_id, status)
INCLUDE (total, created_at);
-- Then get the plan again
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));Creating an index on a large table can lock the table. Use ONLINE:
CREATE INDEX idx_orders_customer_status
ON orders (customer_id, status)
ONLINE;▸Decision 2: Fix the Query
If the query does SELECT * and only 3 columns are needed, fix the query.
-- Bad:
SELECT * FROM orders WHERE customer_id = 123;
-- Good:
SELECT order_id, total, created_at FROM orders WHERE customer_id = 123;If the query uses a function-wrapped WHERE, fix it.
-- Bad: Index is not used
SELECT * FROM orders WHERE TRUNC(created_at) = DATE '2026-11-30';
-- Good: Index is used
SELECT * FROM orders
WHERE created_at >= DATE '2026-11-30'
AND created_at < DATE '2026-12-01';▸Decision 3: Fix the Plan — SQL Plan Baseline
If there is a plan change and the old plan is better, fix the old plan. In Oracle this is called SQL Plan Baseline. It is the counterpart of plan forcing in SQL Server.
-- Accept the plan as baseline
DECLARE
v_count NUMBER;
BEGIN
v_count := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(
sql_id => 'abc123xyz',
plan_hash_value => 1234567890
);
END;
/Plan baseline is a temporary solution. It is not a permanent solution without fixing the root cause. Update statistics, fix the index, then review the baseline.
▸Decision 4: Fix N+1
If the query averages 8 ms but runs 2 million times a day, there is N+1. Do not run queries in a loop. Fetch with a single JOIN.
▸Decision 5: Change Parameters — Last Resort
If the query is correct, the index is correct, the plan is correct, but the system is still slow, then look at parameters. SGA and PGA settings will be covered in detail in the next cluster article.
Verification: Did the Fix Work?
Record the baseline measurement before the fix. Measure the same query again after the fix.
SELECT
sql_id,
executions,
ROUND(elapsed_time / 1000000 / NULLIF(executions, 0), 2) AS avg_time_sec,
ROUND(buffer_gets / NULLIF(executions, 0), 0) AS avg_buffer_gets
FROM v$sql
WHERE sql_id = 'abc123xyz';Success criteria:
- •Did total time drop?
- •Did average time drop?
- •Did buffer gets drop?
- •Did plan change resolve?
If you cannot say yes to these questions, the fix did not work. Revert it, diagnose again.
7 Common Mistakes
First mistake: Using AWR without an AWR license. First verify your license.
Second mistake: Choosing the most expensive query by average time. What tires the system is total time.
Third mistake: Not noticing plan changes. Thinking the plan did not change because the query did not change is the sneakiest mistake.
Fourth mistake: Moving unnecessary columns with SELECT *. It increases buffer gets.
Fifth mistake: Not deleting unused indexes. Every unused index slows every write.
Sixth mistake: Thinking SQL Plan Baseline is a permanent solution. Baseline is a temporary bandage. Fix the root cause.
Seventh mistake: Trying to fix a bad query by changing parameters. First fix the query, then look at parameters.
Checklist
- AWR license verified
- AWR snapshot interval and retention checked
- 20 most expensive queries listed by total time
- Top 3 queries diagnosed precisely
- Slow query vs frequent query distinction made
- Plan change existence checked
- Real plan obtained
- Missing index suggestions checked
- Currently running queries checked with ASH
- Wait events checked
- 1 fix action chosen
- Index tested in test environment first
ONLINEused on large tables- Total and average time measured again after fix
- Useless fix reverted
Conclusion
In Oracle, as in other engines, performance problems start with measurement. AWR is the mirror of the system. First look in the mirror, then fix. But in Oracle there is one more step: Look at plan history and check your license. Because even if the query stays the same, the plan can change. Without catching plan changes, you cannot manage Oracle performance.
Next cluster: Oracle Memory Tuning — SGA and PGA. Because after finding the most expensive query, next is to set memory correctly.
Related Articles
- •Pillar: Performance Guide — Performance & Query Optimization
- •Cluster: [PostgreSQL] Finding the 20 Most Expensive Queries with pg_stat_statements
- •Cluster: [MySQL] Finding the 20 Most Expensive Queries with Performance Schema
- •Cluster: [SQL Server] Finding the 20 Most Expensive Queries with Query Store
- •Cluster: [Universal] EXPLAIN ANALYZE Reading Guide
- •Next: [Oracle] Memory Tuning — SGA and PGA