Fix an Oracle SQL Plan Regression with SQL Plan Baselines (SPM) Step by Step
Updated: Oct 24
A classic production incident: nothing was deployed, yet a critical query that always took 2 seconds now takes 5 minutes. In most cases the SQL text did not change, but its execution plan did. New statistics, a different bind value at hard parse, or an upgrade can all make the optimizer choose a different plan, and sometimes that plan is much worse.
SQL Plan Management (SPM) lets you tell the optimizer: "For this statement, use this plan." In this post we fix a plan regression step by step with a SQL plan baseline, and then look at how to manage the baseline over time.
How SQL Plan Baselines Work
A SQL plan baseline is a set of accepted plans for one SQL statement, identified by its normalised text (the SQL handle).
When OPTIMIZER_USE_SQL_PLAN_BASELINES is TRUE (the default), the optimizer still calculates its best plan, but if that plan is not in the baseline, it uses the best accepted plan from the baseline instead.
New plans the optimizer finds are stored as unaccepted. They can be tested and accepted later; this is called evolution.
A plan marked FIXED is preferred over any non-fixed plan.
SQL Plan Management is part of Oracle Database Enterprise Edition. Loading plans from AWR uses AWR data, which requires the Diagnostics Pack licence.
Step 1: Identify the Regressed Statement
You usually start from an AWR report, a monitoring alert or a user complaint. Find the SQL_ID of the slow statement and confirm it is the one using the time.
SQL |
SELECT sql_id, plan_hash_value, executions, ROUND(elapsed_time/1e6/NULLIF(executions,0),2) AS sec_per_exec, ROUND(buffer_gets/NULLIF(executions,0)) AS gets_per_exec, SUBSTR(sql_text,1,80) AS sql_text FROM v$sql WHERE sql_text LIKE '%FROM orders o JOIN customers c%' AND sql_text NOT LIKE '%v$sql%'; |
What to expect: The SQL_ID, the plan currently in use (PLAN_HASH_VALUE) and its cost per execution. Note the SQL_ID; we use 8z4kq1xbv9r2m in the examples.
Step 2: Look at the Plan History
The key question is: which plans has this SQL used, and which one was good? AWR stores per-snapshot statistics for each SQL_ID and plan.
SQL |
SELECT s.snap_id, TO_CHAR(sn.begin_interval_time,'MM-DD HH24:MI') AS snap_time, s.plan_hash_value, s.executions_delta AS execs, ROUND(s.elapsed_time_delta/1e6/NULLIF(s.executions_delta,0),2) AS sec_per_exec, ROUND(s.buffer_gets_delta/NULLIF(s.executions_delta,0)) AS gets_per_exec FROM dba_hist_sqlstat s JOIN dba_hist_snapshot sn ON sn.snap_id = s.snap_id AND sn.instance_number = s.instance_number WHERE s.sql_id = '8z4kq1xbv9r2m' AND s.executions_delta > 0 ORDER BY s.snap_id; |
What to expect: Something like plan 1624358213 at 0.8 seconds per execution for weeks, then, from a certain snapshot, plan 3920211486 at 140 seconds. The old plan hash value is the one we want to restore.
Step 3: Compare the Good and Bad Plans
Before forcing a plan, make sure you understand the difference. DBMS_XPLAN shows both plans: the current one from the cursor cache and older ones from AWR.
SQL |
-- Current plan(s) in memory, with runtime statistics if available SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('8z4kq1xbv9r2m', NULL, 'TYPICAL'));
-- Plans stored in AWR (good and bad) SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR('8z4kq1xbv9r2m', 1624358213)); SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR('8z4kq1xbv9r2m', 3920211486)); |
What to expect: For example, the good plan uses an INDEX RANGE SCAN on ORDERS_CUST_IX with NESTED LOOPS, and the bad plan does a full scan of ORDERS with a HASH JOIN. This tells you the likely cause, such as statistics making the optimizer think the filter returns many more rows than it really does.
Step 4: Load the Good Plan into a Baseline
How you load the plan depends on where the good plan still exists.
SQL |
-- Case A: the good plan is still in the cursor cache DECLARE n PLS_INTEGER; BEGIN n := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE( sql_id => '8z4kq1xbv9r2m', plan_hash_value => 1624358213, fixed => 'NO', enabled => 'YES'); DBMS_OUTPUT.PUT_LINE('Plans loaded: ' || n); END; /
-- Case B: the good plan is only in AWR (Oracle 18c and later) DECLARE n PLS_INTEGER; BEGIN n := DBMS_SPM.LOAD_PLANS_FROM_AWR( begin_snap => 48100, end_snap => 48190, basic_filter => q'[sql_id = '8z4kq1xbv9r2m' AND plan_hash_value = 1624358213]'); DBMS_OUTPUT.PUT_LINE('Plans loaded: ' || n); END; / |
What this does: The function copies the chosen plan into the SQL Management Base (in SYSAUX) as an accepted plan for this statement. The return value should be 1. In Case B, choose a snapshot range in which the good plan was executed, which you can see in the Step 2 output. On 12c, where LOAD_PLANS_FROM_AWR does not exist, load the plan from AWR into a SQL tuning set first and then use LOAD_PLANS_FROM_SQLSET.
Step 5: Verify the Baseline
Check that the baseline exists, is enabled and accepted, and contains the plan you wanted.
SQL |
SELECT sql_handle, plan_name, enabled, accepted, fixed, origin, TO_CHAR(created,'YYYY-MM-DD HH24:MI') AS created FROM dba_sql_plan_baselines WHERE sql_text LIKE '%FROM orders o JOIN customers c%';
-- Show the plan stored in the baseline SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE( sql_handle => 'SQL_4a1f6e2b7c3d9e10', format => 'TYPICAL')); |
What to expect: One row with ENABLED=YES, ACCEPTED=YES and ORIGIN MANUAL-LOAD (or MANUAL-LOAD-FROM-AWR). The plan shown should match the good plan from Step 3. Note the SQL_HANDLE and PLAN_NAME.
Step 6: Mark the Plan as FIXED (Optional)
If other plans are later accepted for this statement (for example by automatic evolution), the optimizer chooses the cheapest accepted one. FIXED makes the optimizer prefer your plan over any non-fixed plan. Use it when you want certainty, for example during a busy business period.
SQL |
DECLARE n PLS_INTEGER; BEGIN n := DBMS_SPM.ALTER_SQL_PLAN_BASELINE( sql_handle => 'SQL_4a1f6e2b7c3d9e10', plan_name => 'SQL_PLAN_4n7vf2dy3v7h0a1b2c3d4', attribute_name => 'FIXED', attribute_value => 'YES'); END; / |
Step 7: Make the Running Application Pick Up the Baseline
The baseline is used at the next hard parse. The bad cursor may still be in the shared pool, and sessions will keep using it until it is aged out. Purge only that one cursor, so the next execution is parsed again with the baseline. Never flush the whole shared pool on a busy production system for this.
SQL |
SELECT address, hash_value FROM v$sqlarea WHERE sql_id = '8z4kq1xbv9r2m';
EXEC DBMS_SHARED_POOL.PURGE('000000085FD77CF0,1903289478', 'C'); |
What this does: DBMS_SHARED_POOL.PURGE takes "address,hash_value" and the type 'C' (cursor). It removes that SQL from the library cache. On RAC, run it on every instance where the cursor exists.
Step 8: Confirm the Optimizer Uses the Baseline
Let the application run the statement again (or run it yourself with the same binds), then check the cursor. The plan output and V$SQL tell you whether the baseline was used.
SQL |
SELECT sql_id, child_number, plan_hash_value, sql_plan_baseline, executions, ROUND(elapsed_time/1e6/NULLIF(executions,0),2) AS sec_per_exec FROM v$sql WHERE sql_id = '8z4kq1xbv9r2m';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('8z4kq1xbv9r2m', NULL, 'BASIC +NOTE')); |
What to expect: PLAN_HASH_VALUE is the good plan again, SQL_PLAN_BASELINE shows the plan name, and the Note section of the plan says "SQL plan baseline SQL_PLAN_4n7vf2dy3v7h0a1b2c3d4 used for this statement". Elapsed time per execution is back to normal.
Step 9: Find the Root Cause
The baseline stops the bleeding. Now find out why the plan changed, so the same thing does not happen to other statements.
New statistics: compare DBA_TAB_STATS_HISTORY with the time the plan changed. A gather during a data load can produce misleading statistics.
Bind peeking: different bind values at hard parse can lead to different plans. Check V$SQL_BIND_CAPTURE.
Schema change: a dropped or invisible index, or a new histogram.
Upgrade or parameter change: OPTIMIZER_FEATURES_ENABLE, new optimizer fixes.
Step 10: Review Unaccepted Plans Later (Evolution)
While the baseline is in place, the optimizer still records any new plan it finds as unaccepted. Later, you can let Oracle test those plans against the accepted one, and accept them only if they perform better.
SQL |
SELECT plan_name, accepted, origin FROM dba_sql_plan_baselines WHERE sql_handle = 'SQL_4a1f6e2b7c3d9e10';
DECLARE task VARCHAR2(128); exe VARCHAR2(128); rpt CLOB; BEGIN task := DBMS_SPM.CREATE_EVOLVE_TASK(sql_handle => 'SQL_4a1f6e2b7c3d9e10'); exe := DBMS_SPM.EXECUTE_EVOLVE_TASK(task_name => task); rpt := DBMS_SPM.REPORT_EVOLVE_TASK(task_name => task, execution_name => exe); DBMS_OUTPUT.PUT_LINE(rpt); END; / |
What to expect: A report showing the test execution of each unaccepted plan and whether it was better. To accept a recommended plan, run DBMS_SPM.ACCEPT_SQL_PLAN_BASELINE (or IMPLEMENT_EVOLVE_TASK). In 12.2 and later, the automatic SPM evolve advisor task does this every night by default.
Step 11: Remove the Baseline When No Longer Needed
If the root cause is fixed and the optimizer now chooses the good plan on its own, you can drop the baseline. Keep a record of it in your change log.
SQL |
DECLARE n PLS_INTEGER; BEGIN n := DBMS_SPM.DROP_SQL_PLAN_BASELINE(sql_handle => 'SQL_4a1f6e2b7c3d9e10'); DBMS_OUTPUT.PUT_LINE('Plans dropped: ' || n); END; / |
Summary
When a SQL statement regresses because of a plan change, use the AWR plan history to find the good plan, load it into a SQL plan baseline from the cursor cache or AWR, optionally mark it FIXED, purge the bad cursor and confirm the Note in the execution plan. Then fix the root cause and let evolution decide whether better plans should be accepted. It is one of the fastest and safest fixes a DBA has.
Comments