A Query Tuning
When a query slows down, start by measuring what changed. Capture its SQL ID, the time window, the execution plan, and the work the database performed. Compare those observations with an earlier healthy run or a representative baseline. This appendix provides a path for investigating one slow query and a separate path for investigating a broader slowdown.
How SQL Executes
SQL is declarative: you describe the result you want, and Oracle chooses an execution plan. The optimizer uses available statistics and access paths to choose operations such as table scans, index access, joins, filters, aggregation, and sorting. The plan and the volume of data processed by each operation largely determine how much work the query performs.
Think of the SQL statement as a request, the optimizer as the planner, and the execution plan as the strategy. Oracle executes that strategy while sharing CPU, memory, and I/O with other work. When performance changes, find out whether the strategy changed, the amount of work changed, or the available resources changed.
| Symptom | Area to investigate |
|---|---|
| One query takes much longer than expected | Its access path, joins, row estimates, waits, and temporary-space use. |
| A query that used to be fast regresses | Plan history, data volume, statistics, bind values, and workload changes. |
| Several queries slow down together | System load, waits, concurrent sessions, and scheduled work. |
| One run is fast and another is slow | Differences in plans, bind values, caching, parallel execution, and concurrent load. |
Start with the scope of the problem. For one slow query, follow Diagnosing a Slow Query . For several affected queries or an application-wide slowdown, follow Diagnosing System-Wide Performance Issues. If performance changed after a plan change, use Understanding Plan Instability.
- One query is slow: capture its SQL ID and plan, then check access paths, row estimates, waits, and temporary-space use.
- Several queries are slow: identify the affected interval and compare AWR, Usage Monitoring, sessions, and scheduled work.
- A query regressed: compare its plan and workload with a measured healthy run.
Baselining Your Query
A baseline records how an important query behaves under representative data and workload conditions. It lets you distinguish a regression from normal variation and gives support a concrete comparison. Capture one before go-live, after a major schema or statistics change, after tuning, and periodically for important queries.
Record the SQL ID, plan hash value, execution count, average elapsed time, rows processed, buffer gets, disk reads, date, environment, and relevant workload conditions. A baseline taken on an unusually quiet system may not represent normal response time; label the conditions under which it was collected.
For example, a baseline record can contain the SQL ID, the date, an average elapsed time of 2.8 seconds, 14,200 rows processed, 28,000 buffer gets, 64 disk reads, and the plan hash value. The numbers alone do not say whether the query is acceptable; compare them with the requirement and later runs under similar conditions.
| Metric | Why record it |
|---|---|
| SQL ID and plan hash value | Identify the statement and the plan used for the run. |
| Average elapsed time | Compare user-visible execution time across runs. |
| Rows processed | Detect a change in result or intermediate data volume. |
| Buffer gets | Compare logical I/O and work performed. |
| Disk reads | Compare physical I/O. |
| Executions | Distinguish an expensive single run from a frequently executed statement. |
SQL IDs
Oracle assigns a SQL ID to statement text. Changes to the text, including formatting or literal values, can produce a different SQL ID. Bind values normally do not change the SQL ID for the same statement text. Keep the SQL text or application context with the ID so you can recognize related statements whose text has changed.
If the statement is still in the shared pool and you have access to GV$SQL, use
this query for a recent snapshot. Times in GV$SQL are cumulative
microseconds; the per-execution expression divides by both one million and the execution
count. GV$SQL can contain multiple rows for an SQL ID, including
separate instances and child cursors, so retain the instance and child number.
SELECT inst_id,
child_number,
sql_id,
plan_hash_value,
last_active_time,
executions,
ROUND(elapsed_time / 1000000, 2) AS total_elapsed_sec,
ROUND(elapsed_time / 1000000 / NULLIF(executions, 0), 2)
AS avg_elapsed_sec,
ROUND(rows_processed / NULLIF(executions, 0)) AS avg_rows,
ROUND(buffer_gets / NULLIF(executions, 0)) AS avg_buffer_gets,
ROUND(disk_reads / NULLIF(executions, 0)) AS avg_disk_reads
FROM gv$sql
WHERE sql_id = :sql_id
ORDER BY last_active_time DESC;Save the result with the observation time. A cursor can age out of the shared pool, and its
cumulative counters can reset when a new cursor is created. For a past interval, use
available AWR data instead of treating the current GV$SQL row as
historical evidence.
Optional Baseline Log
The following example stores a snapshot for one SQL ID. Create and schedule it only in a schema where you are authorized to create tables, procedures, and Scheduler jobs. Review retention, privileges, and the effect of scheduled queries before using it in a production environment.
CREATE TABLE sql_baseline_log (
log_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
log_date TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
inst_id NUMBER,
child_number NUMBER,
sql_id VARCHAR2(13),
plan_hash_value NUMBER,
executions NUMBER,
total_elapsed_sec NUMBER,
avg_elapsed_sec NUMBER,
avg_rows NUMBER,
avg_buffer_gets NUMBER,
avg_disk_reads NUMBER
);
CREATE OR REPLACE PROCEDURE log_sql_baseline(p_sql_id IN VARCHAR2) AS
BEGIN
INSERT INTO sql_baseline_log (
inst_id, child_number, sql_id, plan_hash_value, executions,
total_elapsed_sec, avg_elapsed_sec, avg_rows,
avg_buffer_gets, avg_disk_reads
)
SELECT inst_id,
child_number,
sql_id,
plan_hash_value,
executions,
ROUND(elapsed_time / 1000000, 2),
ROUND(elapsed_time / 1000000 / NULLIF(executions, 0), 2),
ROUND(rows_processed / NULLIF(executions, 0)),
ROUND(buffer_gets / NULLIF(executions, 0)),
ROUND(disk_reads / NULLIF(executions, 0))
FROM gv$sql
WHERE sql_id = p_sql_id;
END;
/Call log_sql_baseline with the SQL ID to capture the currently available cursor
rows. Commit the inserted rows when you run it in an interactive transaction:
BEGIN
log_sql_baseline('abcdef1234567');
END;
/
COMMIT;For repeated collection, keep the SQL IDs you care about in a table and have an approved Scheduler job call the procedure. This example runs daily at 2 a.m. in the database session’s time zone; adjust the schedule and the tracked set for the environment.
CREATE TABLE tracked_sql_ids (
sql_id VARCHAR2(13) PRIMARY KEY,
description VARCHAR2(200)
);
INSERT INTO tracked_sql_ids (sql_id, description)
VALUES ('abcdef1234567', 'Critical dashboard query');
COMMIT;
CREATE OR REPLACE PROCEDURE baseline_all_tracked_sql AS
BEGIN
FOR r IN (SELECT sql_id FROM tracked_sql_ids) LOOP
log_sql_baseline(r.sql_id);
END LOOP;
END;
/
BEGIN
DBMS_SCHEDULER.CREATE_JOB(
job_name => 'BASELINE_TRACKED_SQL',
job_type => 'PLSQL_BLOCK',
job_action => 'BEGIN baseline_all_tracked_sql; END;',
start_date => SYSTIMESTAMP,
repeat_interval => 'FREQ=DAILY;BYHOUR=2',
enabled => TRUE
);
END;
/Check that the job succeeds and remove old log rows according to your retention policy. A scheduled baseline does not replace AWR or capture every execution. If a tracked SQL ID has aged out of the shared pool, its collection may insert no rows; investigate missing entries before assuming the query did not run.
Is My Query Slow?
Judge a query against the response time and frequency required by its use. An interactive request has different expectations from a batch report. Record who or what depends on the query, how often it runs, the expected response time, and whether it has caused a timeout. Use the timeout configured for the particular service or application; do not assume one timeout applies to every RDS integration.
If a user reports a slowdown, measure it. This query reports the average elapsed time for each available cursor row, rather than labeling cumulative elapsed time as a single execution:
SELECT inst_id,
child_number,
executions,
ROUND(elapsed_time / 1000000 / NULLIF(executions, 0), 2)
AS avg_elapsed_sec
FROM gv$sql
WHERE sql_id = :sql_id;Compare the result with your baseline and the application’s requirement. A query may be acceptable once a day but costly when called hundreds of times per hour. Move to diagnosis when the measured behavior misses the requirement or has changed materially.
Diagnosing a Slow Query
Work from the statement and the affected time window. Capture evidence before changing SQL, indexes, statistics, or configuration.
Step 1: Find the SQL ID
Get the SQL ID from the application, an APEX session or request log, RDOC Top SQL when the statement is active, or an authorized query of recent SQL activity. For example:
SELECT inst_id, sql_id, last_active_time, sql_text
FROM gv$sql
WHERE sql_text LIKE '%target_table%'
AND last_active_time > SYSDATE - 1/24
ORDER BY last_active_time DESC;Replace target_table with a distinctive portion of the statement. Limit the
search to the relevant schema or time window when possible. A statement that aged out of
the shared pool will not appear in GV$SQL.
Step 2: Review the Execution Plan
For a cursor still available in the current instance, display its plan:
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(:sql_id, NULL, 'ALLSTATS LAST'));ALLSTATS LAST shows actual row counts only when execution statistics were
collected for that cursor. Compare estimated and actual rows where available. Look for
large full scans, expensive joins, high buffer gets, sorts, and temporary-space use. A
full scan or hash join is not automatically a problem; judge it against data volume and
elapsed time.
| Question | Evidence to review |
|---|---|
| Is the access path appropriate? | Full scans, index access, filters, and rows returned. |
| Are row estimates far from actual rows? | Statistics, data skew, predicates, and bind values. |
| Are joins doing more work than expected? | Join order, input rows, buffer gets, and elapsed time. |
| Is the query spilling to temporary storage? | Plan operations, temporary-space use, and waits. |
| Did parallel execution change? | Parallel plan operations and the workload at the time. |
Step 3: Check Waits
If the plan alone does not explain the delay, inspect the waits observed during the execution. These views require suitable privileges and may not retain the affected interval indefinitely.
SELECT inst_id, sid, sql_id, event, wait_class, state
FROM gv$session
WHERE sql_id = :sql_id;SELECT sample_time, session_id, sql_id, event, wait_class
FROM gv$active_session_history
WHERE sql_id = :sql_id
ORDER BY sample_time DESC;Temporary I/O waits may indicate that a sort, hash join, or aggregation wrote intermediate data to temporary storage. Row-lock waits may indicate blocking. Interpret a wait in the context of its duration, SQL plan, and other workload; the presence of an event alone does not prove the root cause.
Common clues include direct path read temp or direct path write temp for
temporary I/O, enq: TX - row lock contention for row-lock waits, and
db file sequential read for single-block reads. A spill
occurs when an operation such as a sort or hash join writes intermediate data to
temporary storage because it cannot complete in memory. Confirm that the affected SQL
performed the work before tuning it.
Step 4: Review Statistics and Skew
Bad row estimates can lead to an unsuitable plan. If you have access, check when table and column statistics were gathered:
SELECT owner, table_name, last_analyzed, num_rows
FROM dba_tables
WHERE owner = :owner
AND table_name = :table_name;SELECT owner, table_name, column_name, histogram, num_distinct
FROM dba_tab_col_statistics
WHERE owner = :owner
AND table_name = :table_name;A skewed column has some values that occur much more often than others. Histograms can help the optimizer estimate selective predicates, but the absence of a histogram does not by itself justify gathering new statistics. Confirm the data distribution and obtain the appropriate approval before changing statistics.
Step 5: Compare Plan History
If performance changed recently, compare plan hashes and available historical evidence for the same SQL ID. A different plan hash indicates a plan change, but it does not prove that the plan caused the slowdown. Compare elapsed time, rows, workload, and waits for the affected and healthy periods. See Understanding Plan Instability.
Decide the Next Step
If the evidence points to a query problem, consider reducing data read, filtering earlier, revising joins, or adding an allowed index. Customers cannot add indexes to RDS replicated objects. If estimates, access, or permissions are unclear, record the SQL ID, plan, time window, and measured difference for support. Test a change against representative data before promoting it.
Diagnosing System-Wide Performance Issues
When several pages, jobs, or queries slow down together, establish the affected time window and compare it with a healthy period. Use RDOC’s Usage Monitoring, Session Management, AWR Reports, Top SQL, and DBMS Jobs together. Each view answers a different question; no single chart identifies the cause of a slowdown.
Step 1: Use AWR Reports
Open Retail Home → Application Navigator → Retail DB Ops Console → AWR Reports. Find an available report covering the affected period, or request a custom report if your RDOC role allows it. AWR summarizes database workload over a snapshot interval and helps you compare system load, waits, SQL activity, and plan changes. For a short incident, choose a focused interval and compare it with a similar healthy period.
Start with foreground wait events, load profile, SQL statistics, and temporary I/O. Look for changes in database time, database CPU, executions, redo, top SQL, and wait duration. Database time substantially above CPU time can indicate that sessions spent time waiting, but confirm which waits account for the difference.
In the load profile, compare DB time, DB CPU, SQL executions, and redo volume with a healthy interval. In SQL statistics, review statements ranked by elapsed time, CPU time, buffer gets, and executions. One expensive statement may require a different action from a cheap statement run very frequently. Use SQL ID and plan hash to connect the report with the query-level investigation.
Temporary I/O waits can point to spilling sorts, joins, or aggregations. enq: TX - row
lock contention can point to transaction blocking. A wait event deserves
attention when its time or frequency changed meaningfully from the baseline. Do not
treat a missing event in a top-waits table as proof that it never occurred.
Ratios such as buffer cache hit rate or parses per execution can be supporting clues. Use the underlying counters and SQL evidence before drawing a conclusion. A high buffer cache hit rate can coexist with inefficient SQL; a parse count does not by itself measure hard parses.
If you need to calculate a buffer-cache hit ratio from the AWR Instance Activity Stats, use the counters for physical reads, DB block gets, and consistent gets:
Buffer cache hit ratio =
1 - physical reads / (DB block gets + consistent gets)Use the result only when the denominator is nonzero, and compare it with a representative
baseline. For parse activity, compare parse count (total) with execute
count and review hard-parse counters separately.
For blocking or concurrency, examine the relevant wait events and active SQL. Explicit locks and DML can cause row or table contention. Latch and mutex waits can reflect contention for shared database structures. Review the duration and affected SQL before deciding on an action. RDS replicated objects have customer access restrictions; do not propose customer-created indexes or direct changes to those objects as a troubleshooting step.
If enq: TM - contention or enq: TX - row lock contention dominates the affected
interval, identify the blocking and waiting sessions and the relevant application
transaction. Do not assume that every TX wait is caused by the same SQL
statement or that ending a session is safe. Latch or mutex waits can indicate contention
in buffer-cache, library-cache, or redo-related structures; use the specific event, its
duration, and related workload before escalating.
Report retention: Generated AWR reports in RDOC remain available according to the database’s configured AWR retention period. Download reports needed beyond that period. Use Refresh Report Logs to see newly generated reports. RDOC Owners can request custom reports for available snapshot intervals.
Capture the report ID, interval, important wait events, load profile, SQL IDs, and plan hashes when escalating an incident or recording a baseline.
AWR Review Checklist
Record the snapshot IDs and time window reviewed. Then compare the affected period with a healthy period:
| Area | Evidence to capture |
|---|---|
| System load | Database time, database CPU, executions, and the change from baseline. |
| Top waits | Event, total time, and whether it represents temporary I/O, locking, or another resource. |
| Top SQL | SQL ID, elapsed time, buffer gets, executions, and plan hash. |
| Temporary storage | Relevant wait events and plan operations that may spill. |
| Notable change | New SQL, increased load or waits, or changed execution pattern. |
Write down the initial conclusion and the next check. If the evidence is inconclusive, say so and preserve the report for comparison.
For an incident record, capture these fields before moving on:
Begin and end snapshot IDs:
Affected time window and time zone:
Comparable healthy interval:
DB time and DB CPU change:
Top wait events and total time:
Top SQL IDs, plan hashes, and elapsed time:
Temporary I/O or blocking evidence:
Initial conclusion and next check:Step 2: Review Usage Monitoring and Session Management
From RDOC’s navigation menu, open Usage Monitoring to review historical CPU utilization and customer-schema storage usage. Select 24 hours, 7 days, 30 days, or 90 days. Both charts use the selected range. CPU is sampled every five minutes and storage hourly; the charts refresh every five minutes while the page is open. The available history depends on when collection began.
Open Session Management to compare customer session history with RDOC’s configured pool-capacity estimate. Its Session Count History chart includes total customer sessions and long-running SQL sessions. The All Sessions report shows current eligible customer sessions. Session counts can indicate connection pressure; they do not directly measure checked-out ORDS connections.
Table A-1 RDOC Signals to Review
| RDOC view | What to look for | How to use it |
|---|---|---|
| Usage Monitoring - CPU Utilization | Repeated high values or a change from the usual pattern. | The chart shows a 15-minute trailing mean of sampled database CPU use. Compare the affected period with AWR and Top SQL. |
| Usage Monitoring - Storage Usage | Sustained growth or usage approaching a reference line. | The chart shows allocated customer-schema storage. Its configured Soft Max and 75% Warning lines are planning references, not physical limits or evidence of an immediate performance problem. |
| Session Management - Session Count History | A rise in total sessions or long-running SQL sessions. | Compare the affected time with workload and AWR evidence. Pool Capacity is a configured estimate, not measured ORDS pool occupancy. |
| Session Management - All Sessions | Sessions currently running SQL for an extended period. | Use the SQL ID and other session details to continue the investigation. The report may be empty when no eligible sessions are active. |
The CPU chart shows individual 15-minute trailing values for 24 hours, hourly peaks for 7 days, and daily peaks for 30 or 90 days. The longer ranges retain the highest trailing value in each display period; they do not show the average for that whole hour or day. Use AWR to examine database activity during a suspected slowdown. Storage growth is usually a separate capacity-planning question.
Step 3: Triage with Top SQL
Open Top SQL from RDOC’s navigation menu. Filter active SQL by session state, including ON CPU and WAITING. Select a SQL ID to inspect its details and full text. Use this view to identify statements active now; use AWR when the affected period has already passed.
Step 4: Check DBMS Jobs
Open DBMS Jobs when the slowdown coincides with scheduled or background work. Review failed jobs, unusually long runs, and run details for jobs that started near the affected time.
Step 5: Review Sessions
Open Session Management to review Session Count History, All
Sessions, and the Session Management Log. Users with Viewer access can
review the available session information. Administrators can end an eligible session
from the report when that action is available; the MANAGEMENT.RDS_SESSION_MGMT
API also validates sessions against RDOC’s criteria.
Ending a session can interrupt custom processing and roll back uncommitted work. Confirm the owning application or process before acting. Do not infer that a session is safe to end from its name, age, or SQL duration alone. Submit a support request for sessions outside RDOC’s criteria.
Table A-2 Interpretation Tips
| Observation | Possible next step |
|---|---|
| High wait time on temporary I/O in AWR | Review sorts, joins, and temporary-space use in the affected SQL. |
| One statement dominates Top SQL or AWR | Compare its plan and workload with a healthy interval. |
| Repeated high CPU values in Usage Monitoring | Correlate the time window with AWR, Top SQL, and DBMS Jobs. |
| Customer session counts rise sharply | Review workload, long-running SQL sessions, and the configured pool-capacity estimate. Do not treat the count as measured ORDS pool occupancy. |
| Storage usage approaches a reference line | Review growth and available headroom; the line is a planning aid. |
Use the observed change to choose the next check. Compare it with a known healthy period before changing SQL, capacity, or sessions.
Understanding Plan Instability
Oracle may choose a different plan for the same SQL text when statistics, data distribution, bind values, available indexes, or optimizer behavior change. A changed plan is normal; it is a problem only when measured performance becomes worse. Compare the affected execution with a healthy period before attributing a regression to the plan.
| Possible cause | What changed |
|---|---|
| Statistics or data distribution | Row estimates and chosen access paths may change. |
| Bind values | Different selectivity may make a plan less suitable for a particular execution. |
| Available access paths | An index or object change may give the optimizer another choice. |
| SQL text | Even a small text change can yield another SQL ID. |
| Cursor or optimizer behavior | A cursor may be reparsed, or adaptive behavior may select another path. |
If you have access to historical plan information, look for multiple plan hashes for the SQL ID:
SELECT DISTINCT sql_id, plan_hash_value
FROM dba_hist_sql_plan
WHERE sql_id = :sql_id
ORDER BY plan_hash_value;This query shows that more than one plan was captured. It does not show which plan was
faster. Compare elapsed time, executions, rows, and waits from AWR or another measured
source for each relevant period. Bind sensitivity information in V$SQL
can provide context when bind values differ, but it also does not establish the cause by
itself.
If the changed plan corresponds to a measured regression, record the SQL ID, both plan hashes, affected time window, representative bind or workload context, and performance difference. Submit that evidence through the appropriate support process when a fix requires privileges or tools you do not have. Test any permitted SQL change against representative data before adopting it.