Pinning and Reverting Execution Plans
Use these methods when a query that was fast until yesterday gets slow because it takes a different plan after a statistics update, a different bind value, or a version upgrade. The sequence is the same on all three DBs. First find the good plan and the current plan, pin the good plan, and once you fix the cause (statistics, indexes, SQL), release the pin. Pinning is first aid. The plan does not follow data changes, so review the list of pinned plans periodically.
Oracle
Required privileges: SELECT_CATALOG_ROLE to query, ADMINISTER SQL MANAGEMENT OBJECT to manage baselines.
Current plan and whether it is pinned
SELECT sql_id, child_number, plan_hash_value, executions,
ROUND(elapsed_time / NULLIF(executions, 0) / 1000) AS avg_ms,
sql_plan_baseline, sql_profile, sql_patch
FROM v$sql
WHERE sql_id = 'abcd1234efgh5';
- If
sql_plan_baseline,sql_profile, orsql_patchhas a value, that mechanism is applied to the plan. - Find old plans in AWR:
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR('abcd1234efgh5'));(AWR requires a Diagnostics Pack license.)
Pinning a plan with a SQL Plan Baseline (DBMS_SPM)
SQL Plan Management is included in Enterprise Edition and needs no separate pack. Load a good plan still in the cursor cache as a baseline.
DECLARE
n PLS_INTEGER;
BEGIN
n := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(
sql_id => 'abcd1234efgh5',
plan_hash_value => 1234567890,
fixed => 'YES');
DBMS_OUTPUT.PUT_LINE(n || ' plan(s) loaded');
END;
/
- If the good plan is not in the cache, load it from AWR:
DBMS_SPM.LOAD_PLANS_FROM_AWR(begin_snap => 100, end_snap => 110, basic_filter => q'[sql_id = 'abcd1234efgh5']')(requires Diagnostics Pack). - To attach the plan of a hinted SQL to the original SQL, pass the hinted SQL's
sql_idandplan_hash_valuetogether with the original SQL'ssql_handle.
-- Register the plan of the hinted SQL as the baseline of the original SQL (sql_handle)
n := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(
sql_id => 'hinted0sqlid1',
plan_hash_value => 987654321,
sql_handle => 'SQL_1a2b3c4d5e6f7a8b');
WARNING When a plan with
fixed => 'YES'exists, the optimizer uses the pinned plan even if it finds a better new plan. If you drop an index that the baseline references, that plan cannot be reproduced and a different plan is used instead (reproduced = 'NO').
Baseline list and usage
SELECT sql_handle, plan_name, enabled, accepted, fixed, reproduced, origin,
created, last_executed, SUBSTR(sql_text, 1, 60) AS sql_text
FROM dba_sql_plan_baselines
ORDER BY created DESC;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE(sql_handle => 'SQL_1a2b3c4d5e6f7a8b'));
- For a plan to be used,
enabled = 'YES'andaccepted = 'YES'are required. - If
optimizer_use_sql_plan_baselines(default TRUE) is FALSE, all baselines are ignored. Automatic capture is controlled byoptimizer_capture_sql_plan_baselines(default FALSE).
Releasing and dropping baselines
DECLARE
n PLS_INTEGER;
BEGIN
-- Only disable (can be re-enabled later)
n := DBMS_SPM.ALTER_SQL_PLAN_BASELINE(
sql_handle => 'SQL_1a2b3c4d5e6f7a8b',
plan_name => 'SQL_PLAN_1a2b3c4d5e6f7a8b12345678',
attribute_name => 'ENABLED',
attribute_value => 'NO');
-- Drop completely (if plan_name is omitted, all plans of that SQL)
n := DBMS_SPM.DROP_SQL_PLAN_BASELINE(
sql_handle => 'SQL_1a2b3c4d5e6f7a8b',
plan_name => 'SQL_PLAN_1a2b3c4d5e6f7a8b12345678');
END;
/
WARNING After dropping, the optimizer chooses a new plan from the next hard parse. If you back up to a staging table with
DBMS_SPM.PACK_STGTAB_BASELINEbefore dropping, you can restore it.
SQL Profile and SQL Patch
A SQL Profile is correction information (mainly cardinality correction hints) created by the SQL Tuning Advisor. It requires a Tuning Pack (and Diagnostics Pack) license.
SELECT name, category, status, force_matching, created, SUBSTR(sql_text, 1, 60) AS sql_text
FROM dba_sql_profiles
ORDER BY created DESC;
-- Accept a tuning task result as a profile / disable / drop
EXEC DBMS_SQLTUNE.ACCEPT_SQL_PROFILE(task_name => 'tune_abcd', name => 'prof_orders', force_match => TRUE);
EXEC DBMS_SQLTUNE.ALTER_SQL_PROFILE(name => 'prof_orders', attribute_name => 'STATUS', value => 'DISABLED');
EXEC DBMS_SQLTUNE.DROP_SQL_PROFILE(name => 'prof_orders');
A SQL Patch attaches a hint without changing the SQL statement. It can be used without a pack license (the function form that takes a sql_id argument is 12.2+).
DECLARE
v VARCHAR2(128);
BEGIN
v := DBMS_SQLDIAG.CREATE_SQL_PATCH(
sql_id => 'abcd1234efgh5',
hint_text => 'INDEX(@"SEL$1" "O"@"SEL$1" "ORDERS_CUST_IX")',
name => 'patch_orders');
END;
/
SELECT name, status, created FROM dba_sql_patches;
EXEC DBMS_SQLDIAG.DROP_SQL_PATCH(name => 'patch_orders');
- Check the hint's query block names and aliases with
DBMS_XPLAN.DISPLAY_CURSOR(..., format => '+ALIAS'). If they are wrong, the hint is silently ignored.
Purging only the bad-plan cursor
When you only want to force a re-parse without pinning, purge just that one cursor instead of flushing the whole shared pool.
SELECT address || ',' || hash_value AS name FROM v$sqlarea WHERE sql_id = 'abcd1234efgh5';
EXEC DBMS_SHARED_POOL.PURGE('000000008F1C2D30,1234567890', 'C');
PostgreSQL
PostgreSQL has no built-in feature to store and pin plans. Plans are rebuilt from statistics each time, so the usual way to revert is fixing the statistics (ANALYZE, ALTER TABLE ... ALTER COLUMN ... SET STATISTICS, CREATE STATISTICS). If you still need to force a plan, use the pg_hint_plan extension.
Installing pg_hint_plan and hints
pg_hint_plan is an extension installed separately (OS package or source build; for managed services, check whether it is supported). Use the extension version that matches your PostgreSQL major version.
-- postgresql.conf: shared_preload_libraries = 'pg_hint_plan' (restart required)
-- Or for the session only: LOAD 'pg_hint_plan';
CREATE EXTENSION pg_hint_plan;
/*+ IndexScan(o orders_customer_idx) NestLoop(c o) */
EXPLAIN SELECT * FROM customers c JOIN orders o ON o.customer_id = c.id WHERE c.region = 'KR';
- Write hints in a
/*+ ... */comment at the very beginning of the statement. If a table has an alias, use the alias. - To check whether a hint took effect, use
SET pg_hint_plan.debug_print = on;withclient_min_messages = log.
Attaching hints without changing the statement (hint table)
Use this when you cannot change the application SQL.
SET pg_hint_plan.enable_hint_table = on; -- per role/DB, use ALTER ROLE ... SET
-- pg_hint_plan 1.6+: by query_id (requires compute_query_id)
INSERT INTO hint_plan.hints (query_id, application_name, hints)
VALUES (-1234567890123456789, '', 'IndexScan(o orders_customer_idx)');
-- 1.5 and earlier: by normalized statement (constants replaced with ?)
-- INSERT INTO hint_plan.hints (norm_query_string, application_name, hints) VALUES (...);
- Get the
query_idfrompg_stat_statements.queryidor the Query Identifier inEXPLAIN (VERBOSE). - The table columns differ by version, so first check
\d hint_plan.hintsfor the installed version.
WARNING A hint table row applies to all sessions matching its conditions. To revert,
DELETEthat row.
Generic plan of prepared statements (plan_cache_mode)
A prepared statement may switch to a generic plan, independent of bind values, after its 5th execution. If the value distribution varies widely, it suddenly becomes slow at that point. PostgreSQL 12+.
SHOW plan_cache_mode; -- auto (default)
ALTER ROLE app SET plan_cache_mode = 'force_custom_plan'; -- plan with the bind values each time
-- Conversely, to reduce planning cost use 'force_generic_plan'
- It can also be set per function:
ALTER FUNCTION f(int) SET plan_cache_mode = 'force_custom_plan'; - Check which kind was used with
generic_plansandcustom_plans(14+) inpg_prepared_statements.
Narrowly scoped planner settings
This is a way to disable a plan method for only a specific function or role, without an extension. Do not apply it to a whole session.
ALTER FUNCTION report_monthly(date) SET enable_nestloop = off;
-- Revert
ALTER FUNCTION report_monthly(date) RESET enable_nestloop;
SQL Server
Required privileges: VIEW DATABASE STATE to query Query Store, ALTER on the database for plan forcing and hints. Query Store is available in all editions from 2016+, and on 2022 it is on by default for newly created DBs.
Turning on Query Store and checking status
ALTER DATABASE sales SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);
SELECT actual_state_desc, desired_state_desc, readonly_reason,
current_storage_size_mb, max_storage_size_mb
FROM sys.database_query_store_options;
- If
actual_state_descisREAD_ONLY, it is out of space and no longer recording (checkreadonly_reasonandmax_storage_size_mb).
Comparing performance per plan for one query
SELECT q.query_id, p.plan_id, p.is_forced_plan,
SUM(rs.count_executions) AS execs,
ROUND(SUM(rs.avg_duration * rs.count_executions) / SUM(rs.count_executions) / 1000, 1) AS avg_ms,
MAX(rs.last_execution_time) AS last_exec,
SUBSTRING(qt.query_sql_text, 1, 80) AS query_text
FROM sys.query_store_query q
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
JOIN sys.query_store_plan p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id
WHERE qt.query_sql_text LIKE N'%FROM dbo.orders%'
GROUP BY q.query_id, p.plan_id, p.is_forced_plan, qt.query_sql_text
ORDER BY q.query_id, avg_ms;
- If the same
query_idhas severalplan_idvalues with very different average times, the plan has changed. The unit ofavg_durationis microseconds. - The "Regressed Queries" report in SSMS uses the same data.
Forcing and unforcing a plan
EXEC sp_query_store_force_plan @query_id = 42, @plan_id = 7;
EXEC sp_query_store_unforce_plan @query_id = 42, @plan_id = 7;
-- Whether forcing is failing
SELECT query_id, plan_id, force_failure_count, last_force_failure_reason_desc
FROM sys.query_store_plan
WHERE is_forced_plan = 1;
WARNING If you drop or rename an index used by the forced plan, forcing fails and the optimizer builds the plan as usual (
force_failure_countincreases). Forcing remains in the DB, so unforce it after fixing the cause of the problem.
Automatic plan correction (FORCE_LAST_GOOD_PLAN)
SQL Server 2017+. If a plan change makes a query slow, it automatically forces the last good plan. This is an Enterprise Edition feature.
ALTER DATABASE CURRENT SET AUTOMATIC_TUNING (FORCE_LAST_GOOD_PLAN = ON);
SELECT name, reason, score, state, details
FROM sys.dm_db_tuning_recommendations;
Query Store hints (2022+)
Attach OPTION(...) hints to a query without changing the statement. Because it pins hints rather than a specific plan, it breaks less when the data changes.
EXEC sys.sp_query_store_set_hints @query_id = 42, @query_hints = N'OPTION (RECOMPILE)';
EXEC sys.sp_query_store_set_hints @query_id = 42, @query_hints = N'OPTION (MAXDOP 1, USE HINT(''DISABLE_PARAMETER_SNIFFING''))';
SELECT query_hint_id, query_id, query_hint_text, source_desc,
query_hint_failure_count, last_query_hint_failure_reason_desc
FROM sys.query_store_query_hints;
EXEC sys.sp_query_store_clear_hints @query_id = 42;
USE PLAN and flushing the plan cache
These are the pre-Query Store methods. USE PLAN embeds the plan XML directly in the statement, so use it only when you can change the SQL (if you cannot change the statement, attach a plan guide with sp_create_plan_guide).
SELECT * FROM dbo.orders WHERE customer_id = @id
OPTION (USE PLAN N'<ShowPlanXML xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan" ...>...</ShowPlanXML>');
To discard only that plan and force a recompile, without pinning:
SELECT cp.plan_handle, st.text
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
WHERE st.text LIKE N'%FROM dbo.orders%';
DBCC FREEPROCCACHE (0x06000500F1D2C3B4A5968778695A4B3C2D1E0F00000000000000000000000000);
WARNING Running
DBCC FREEPROCCACHEwithout an argument flushes the instance-wide plan cache, and CPU spikes on compilation for a while. To flush just one DB, useALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;(2016+) in that DB.