Viewing Cached Execution Plans
A command like EXPLAIN PLAN builds a plan from scratch right now, and it may differ from the plan that actually ran, because bind values, session settings, and statistics are not the same as they were then. When investigating a slow execution, look at the plan the DB actually used.
Oracle and SQL Server have a server-wide plan cache, so you can look up plans executed by other sessions. PostgreSQL has no such cache, so you either log the plan at execution time or re-run the statement yourself.
Oracle
Required privileges: SELECT on V$SQL, V$SQL_PLAN, V$SQL_PLAN_STATISTICS_ALL, V$SESSION (SELECT_CATALOG_ROLE). Querying AWR requires a Diagnostics Pack license.
Finding the SQL_ID and child
SELECT sql_id, child_number, plan_hash_value, executions,
ROUND(elapsed_time / NULLIF(executions, 0) / 1000) AS ms_per_exec,
is_bind_sensitive, is_bind_aware, last_active_time,
SUBSTR(sql_text, 1, 80) AS sql_text
FROM v$sql
WHERE sql_text LIKE '%orders%customer_id%'
AND sql_text NOT LIKE '%v$sql%'
ORDER BY last_active_time DESC;
- If one SQL_ID has several children, a separate plan was built because of differences in environment or binds. Check the reason in the columns that are
'Y'inV$SQL_SHARED_CURSOR. - A different
plan_hash_valuemeans a different plan.
Plan in the cache
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR('7h35uxf5uhmm1', 0, 'TYPICAL +PEEKED_BINDS'));
-- The statement just executed in this session
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));
- Passing
NULLas the second argument (child_number) shows all children. +PEEKED_BINDSshows the bind values peeked when the plan was built.ALLSTATS LASTshows the actual row count (A-Rows) and the estimated row count (E-Rows) for each step. Execution statistics are required, so add the/*+ GATHER_PLAN_STATISTICS */hint to the statement, or runALTER SESSION SET statistics_level = ALL;in the session before executing.
Past plans (AWR)
Plans that were evicted from the cache, or old plans, may still be in AWR.
-- Which plan this SQL used over time
SELECT sn.begin_interval_time, st.plan_hash_value, st.executions_delta,
ROUND(st.elapsed_time_delta / NULLIF(st.executions_delta, 0) / 1000) AS ms_per_exec
FROM dba_hist_sqlstat st
JOIN dba_hist_snapshot sn
ON sn.snap_id = st.snap_id AND sn.dbid = st.dbid AND sn.instance_number = st.instance_number
WHERE st.sql_id = '7h35uxf5uhmm1'
ORDER BY sn.begin_interval_time;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_AWR('7h35uxf5uhmm1'));
- If
plan_hash_valuechanges at some point andms_per_execgrows, a plan change is the cause. - In 12.2+,
DBMS_XPLAN.DISPLAY_WORKLOAD_REPOSITORYreplacesDISPLAY_AWR.DISPLAY_AWRstill works in 19c. - To pin a good plan, use a SQL Plan Baseline (
DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE).
Purging a single cursor from the cache
Use this to make only a specific SQL statement re-plan after fixing statistics.
SELECT address, hash_value FROM v$sqlarea WHERE sql_id = '7h35uxf5uhmm1';
EXEC DBMS_SHARED_POOL.PURGE('000000007A6B1C30,3478127841', 'C'); -- 'address,hash_value'
WARNING That SQL is hard parsed on its next execution.
ALTER SYSTEM FLUSH SHARED_POOL;purges all SQL, so do not use it in production. It causes a sudden burst of hard parses and library cache contention.
PostgreSQL
Required privileges: for EXPLAIN, the privilege to run the query. To LOAD auto_explain in a session, superuser.
Viewing the execution plan
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 42;
-- Show the generic plan with the parameter placeholders as-is (PostgreSQL 16+)
EXPLAIN (GENERIC_PLAN) SELECT * FROM orders WHERE customer_id = $1;
ANALYZEactually executes the statement and shows the actual row count and time for each step.BUFFERSis the number of blocks read.- Adding
SETTINGS(12+) also shows planner settings that differ from the defaults.
WARNING
EXPLAIN ANALYZEactually executes the statement. INSERT, UPDATE, and DELETE change data, so wrap them asBEGIN; EXPLAIN ANALYZE ...; ROLLBACK;.
Logging executed plans (auto_explain)
To see the plan another session actually used, have auto_explain write the plans of slow statements to the server log.
-- This session only (superuser)
LOAD 'auto_explain';
SET auto_explain.log_min_duration = '500ms';
SET auto_explain.log_analyze = on;
SET auto_explain.log_buffers = on;
-- Server-wide: put in postgresql.conf and restart
-- shared_preload_libraries = 'pg_stat_statements,auto_explain'
-- auto_explain.log_min_duration = '1s'
- The log contains the plan built with the actual bind values at that time.
- To see statements inside procedures or functions too, set
auto_explain.log_nested_statements = on.
WARNING
auto_explain.log_analyze = onmeasures the execution time of every statement, including those that do not exceed the threshold, so load increases. When enabling it server-wide, reduce the overhead withauto_explain.log_timing = offorauto_explain.sample_rate.
Plans of prepared statements
PostgreSQL keeps plans only for prepared statements within each session. You cannot see another session's.
SELECT name, statement, prepare_time,
generic_plans, custom_plans -- PostgreSQL 14+
FROM pg_prepared_statements;
- After the fifth execution, it may switch to a generic plan. If the value distribution varies widely, this can make the statement slow. Setting
plan_cache_mode(12+) toforce_custom_planbuilds a plan tailored to the values each time. - To discard this session's plans, use
DISCARD PLANS;orDEALLOCATE name;.
SQL Server
Required privileges: VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+). To flush the cache, ALTER SERVER STATE (per database, ALTER ANY DATABASE SCOPED CONFIGURATION). To force a plan, ALTER on that database.
Finding cached plans
SELECT TOP (20) cp.usecounts, cp.objtype, cp.size_in_bytes / 1024 AS size_kb,
cp.plan_handle, LEFT(t.text, 100) AS sql_text, qp.query_plan
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) t
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp
WHERE t.text LIKE '%orders%customer_id%'
AND t.text NOT LIKE '%dm_exec_cached_plans%'
ORDER BY cp.usecounts DESC;
- Clicking
query_plan(XML) in SSMS opens it as a graphical plan. This is the estimated plan and has no actual row counts. - For a single statement inside a batch, or when the XML is too deep and
query_plancomes back NULL, usesys.dm_exec_text_query_plan(plan_handle, statement_start_offset, statement_end_offset). - To see it together with per-statement statistics, start from
sys.dm_exec_query_statsandCROSS APPLYthe same functions.
Actual plan of the last execution (2019+)
ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = ON;
SELECT qps.query_plan
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_query_plan_stats(cp.plan_handle) qps
WHERE cp.plan_handle = 0x06000700...;
Returns the plan containing the actual row counts of the last execution. Turning the setting on adds a small overhead.
Past plans and plan forcing (Query Store)
SELECT q.query_id, p.plan_id, p.is_forced_plan, p.last_execution_time,
TRY_CAST(p.query_plan AS xml) AS plan_xml,
LEFT(qt.query_sql_text, 100) 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
WHERE qt.query_sql_text LIKE '%orders%customer_id%'
ORDER BY q.query_id, p.last_execution_time DESC;
If one query_id has several plan_id values, the plan has changed at some point. To compare performance, join sys.query_store_runtime_stats on plan_id (Top SQL by load).
EXEC sp_query_store_force_plan @query_id = 48, @plan_id = 49;
EXEC sp_query_store_unforce_plan @query_id = 48, @plan_id = 49;
WARNING A forced plan keeps being used even when the data distribution changes. If the plan becomes unusable, for example because an index is dropped, forcing fails and the optimizer falls back to normal optimization (check
force_failure_countandlast_force_failure_reason_desc).
Flushing the plan cache
DBCC FREEPROCCACHE (0x06000700...); -- a single plan
EXEC sp_recompile N'dbo.usp_get_orders'; -- plans that use the procedure or table
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE; -- the whole current DB (2016+)
DBCC FREEPROCCACHE; -- the whole instance
WARNING Flushed plans are recompiled on the next execution, which causes a momentary CPU spike, and the cumulative statistics in
sys.dm_exec_query_statsare lost as well. In production, flush only one plan byplan_handle. Do not useDBCC FREEPROCCACHEwithout an argument.