The last actual plan: what LAST_QUERY_PLAN_STATS costs and what it really shows
A stored procedure was slow last night. The estimated plan from the cache says how SQL Server intended to run the query. More interesting would be how many rows actually flowed through the operators. Since SQL Server 2019, the server can record exactly that: for every plan in the cache, the counters of the last execution. Grant Fritchey introduced this in 2019 and described the overhead as very low (scarydba.com). We looked at what the option costs today on SQL Server 2019, 2022 and 2025, when you should be careful and what the last plan contains. The last point held some surprises.
In short
- Turning it on costs little. In our lab,
LAST_QUERY_PLAN_STATSdid not noticeably affect operations, not even with fully loaded cores and across point lookups, OLTP joins, range aggregations, wide plans and batch mode. - Reading is expensive, not capturing. Anyone who queries the last plan for the whole plan cache, let alone regularly, pays for it clearly. Query in a targeted way, not everything.
- Switching the option clears the database's plan cache. Everything recompiles afterwards. So turn it on at a quiet time.
- The last plan shows rows, not times. Rows per operator, spill warnings and the granted memory of the last execution: yes. Times per operator, waits and parameter values: no. The overall time in the plan is not reliable in any version.
- It is a snapshot, not a history. The next execution overwrites it, and it disappears from the cache along with the plan. Query Store provides the history.
What the option does
LAST_QUERY_PLAN_STATS is a database scoped configuration available from SQL Server 2019 on, also in Azure SQL Database and Managed Instance. It is off by default.
ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = ON;Alternatively, trace flag 2451 turns it on for the whole server. The plan can then be retrieved via the function sys.dm_exec_query_plan_stats(plan_handle). For a plan in the cache, it returns the equivalent of the actual plan of the last execution.
Under the hood, this relies on lightweight profiling, which runs for every query from SQL Server 2019 on. The option makes sure the counters are attached to the plan at the end of an execution. The dependency showed clearly in the lab: if lightweight profiling is turned off in the database, LAST_QUERY_PLAN_STATS returns no runtime values. How the many similar-sounding profiling switches fit together is shown in our overview of the profiling family.
If the option is off, the function still returns a row, but only a plan skeleton without operators. So getting plan XML back does not yet mean you have an actual plan.
What it costs
On SQL Server 2019, 2022 and 2025, we ran five typical query shapes with and without the option: point lookup, OLTP join across four tables, range aggregation, a query with a very large number of operators and a columnstore aggregation in batch mode. Each once with a single session and once with fully loaded cores, alternating and repeated several times.
The result is unspectacular, and that is the good news. The option did not noticeably affect operations in any of these shapes. A small overhead was most visible with very short queries and with plans that have many operators; with batch mode and parallel plans there was none. On SQL Server 2022 it was barely measurable, on 2019 and 2025 the measurements varied more. We found no bottleneck when many sessions ran the same plan at the same time. The plan cache did not need more memory, even with many thousands of plans.
A side observation: lightweight profiling itself, which runs for every query from SQL Server 2019 on anyway, cost more in our lab than the extra for the last plan. If you haven't turned it off, you are already paying the larger part.
For comparison: Microsoft itself gives roughly 1.5 to 2% overhead for lightweight profiling, on which the option builds, in a TPC-C-like test from the SQL Server 2016 era (SQL Server Team Blog).
When to take a closer look first
- The server runs at its CPU limit all the time and mainly processes very many short queries. Then even a small overhead counts.
- You want to switch during operations. Changing the option clears the database's plan cache, in both directions. With large databases and expensive compilations, you will feel the wave afterwards. A quiet time is better than Monday morning.
- Monitoring scripts query the last plan for the whole cache. Retrieving it per plan is clearly more expensive than without the option, because instead of a plan skeleton you now get the full plan XML. With tens of thousands of plans in the cache, a full pass becomes a load on a core. A script that does this every second slows things down measurably. Better to be targeted: the most expensive queries or a known plan (queries 1 and 2 below).
- Additional diagnostic switches such as
FORCE_SHOWPLAN_RUNTIME_PARAMETER_COLLECTION(2022 and later) have a price of their own. With short queries it was noticeable in the lab, and Microsoft itself recommends the option only for a limited time. The parameter values still did not show up in the last plan. - Risk of confusion: Extended Events sessions that capture actual plans (
query_post_execution_showplan,query_post_execution_plan_profile) are a completely different order of magnitude. See The filter that catches nothing.
If any of these points applies to your system, it is worth taking a short look with someone who knows your workload before flipping the switch.
What the last plan contains and what it doesn't
We read the plans per version and query shape from the XML and compared them with sys.dm_exec_query_stats.
Included:
- Rows, executions and end of scans per operator (
ActualRows,ActualExecutions,ActualEndOfScans), per thread for parallel plans, plus the actual execution mode. - Spill warnings (
SpillOccurred). - Granted and actually used memory of the last execution. Be careful with the "desired" memory: after a spill, it already showed the corrected value for the next execution, not the one of the execution that ran.
- The actual degree of parallelism.
Not included:
- Times and CPU per operator, I/O per operator, wait times.
- The runtime values of the parameters. Only the value the plan was compiled with.
- For very simple queries (trivial plans, such as a lookup by primary key), only the top operator. That is also what the documentation says.
The overall time (QueryTimeStats) is not reliable, and in a different way per version:
- SQL Server 2019 and 2022: on the first execution after compilation, it shows roughly the compile time, on all further executions zero.
- SQL Server 2025: the values come from the execution, but CPU time and elapsed time are swapped as soon as they differ, for example with parallel plans. Brent Ozar reported this in April 2026 (brentozar.com), and Microsoft has announced a fix.
So take the duration of an execution from sys.dm_exec_query_stats (last_elapsed_time, last_worker_time) or from Query Store, not from the plan.
In practice: parameter sniffing in the last plan
A typical case, reproduced in the lab: a stored procedure counts and sorts the tickets of one owner. Most owners have five tickets, one has 100,000. The procedure is first compiled for an owner with five tickets. The plan expects few rows and gets little memory for the sort.
Then someone calls the procedure for the large owner. Afterwards, the last actual plan shows:
- at the operators, an estimate of five rows and actually 100,000,
- at the sort, the spill warning,
- as granted memory, the small value, fully used,
- as parameter, the compiled value, not the current one.
That is enough to recognize the case. You can see the gap between estimate and reality and which operator it hits. Retesting with "some" parameter is not necessary.
The catch shows up with the next call: if a small owner comes next, the revealing plan is overwritten. The last plan shows the last execution, not the slowest one. If you want to keep the outlier, you have to be quick or you need the history from Query Store.
How to use it
All three queries only read. They require LAST_QUERY_PLAN_STATS = ON in the database concerned (or trace flag 2451).
Query 1: the last plan of a specific stored procedure.
/* PSG · Last plan · Query 1: Last actual plan of a stored procedure Run in the procedure's database and adjust the name. Read-only. Requires LAST_QUERY_PLAN_STATS = ON in this database or trace flag 2451. The times come from dm_exec_procedure_stats, not from the plan (unreliable there). Permissions: VIEW SERVER STATE; from SQL Server 2022 on, VIEW SERVER PERFORMANCE STATE is enough. Plus VIEW DEFINITION on the procedure or the database: without permission on the object, OBJECT_ID() returns NULL and the query stays empty. OPTION (MAXDOP 1): the diagnostic query should not tie up parallel workers. */SELECT OBJECT_NAME(ps.object_id, ps.database_id) AS procedure_name, ps.execution_count AS executions, ps.last_execution_time AS last_execution, ps.last_elapsed_time / 1000 AS last_duration_ms, ps.last_worker_time / 1000 AS last_cpu_ms, ps.plan_handle, qps.query_plan AS last_actual_planFROM sys.dm_exec_procedure_stats AS psCROSS APPLY sys.dm_exec_query_plan_stats(ps.plan_handle) AS qpsWHERE ps.database_id = DB_ID() AND ps.object_id = OBJECT_ID(N'dbo.MyProcedure')OPTION (MAXDOP 1);In SSMS, clicking the XML opens the plan graphically, with the actual rows at the operators.
Query 2: the last plans of the 20 most expensive plans in the cache. This is where the most important rule lives: narrow it down first, then fetch the last plan.
/* PSG · Last plan · Query 2: Last actual plans of the 20 most CPU-expensive plans in the cache Narrows down via dm_exec_query_stats first (without plan XML) and fetches the last plan only for these 20. Caution: don't run it without TOP across the whole cache, and not every second. Retrieving the plan XML costs noticeable CPU per plan; with tens of thousands of plans, a full pass takes a long time. CPU values since the respective plan was compiled, in milliseconds. Permissions: VIEW SERVER STATE; from SQL Server 2022 on, VIEW SERVER PERFORMANCE STATE is enough. Without VIEW DEFINITION on the respective database, the object_name column stays empty; the plans still come back. OPTION (MAXDOP 1): the diagnostic query should not tie up parallel workers. */WITH expensive AS ( SELECT TOP (20) qs.plan_handle, SUM(qs.execution_count) AS executions, SUM(qs.total_worker_time) / 1000 AS cpu_ms_total FROM sys.dm_exec_query_stats AS qs GROUP BY qs.plan_handle ORDER BY SUM(qs.total_worker_time) DESC)SELECT DB_NAME(t.dbid) AS database_name, OBJECT_NAME(t.objectid, t.dbid) AS object_name, expensive.executions, expensive.cpu_ms_total, expensive.plan_handle, qps.query_plan AS last_actual_planFROM expensiveCROSS APPLY sys.dm_exec_sql_text(expensive.plan_handle) AS tOUTER APPLY sys.dm_exec_query_plan_stats(expensive.plan_handle) AS qpsORDER BY expensive.cpu_ms_total DESCOPTION (MAXDOP 1);If last_actual_plan is empty or has no operators, the option is off in that database or the plan can't be cached.
Query 3: where is the estimate off? For a plan from query 1 or 2, it lists the operators with estimated and actual rows and sorts the largest deviations to the top.
/* PSG · Last plan · Query 3: Estimated versus actual rows per operator Insert the plan_handle from query 1 or 2. Read-only, but it shreds the plan XML: use it for one plan only. Estimated = EstimateRows per execution times estimated executions (1 + rebinds + rewinds); actual = sum across all threads. Operators without runtime counters (for example Compute Scalar) are missing. Factor > 1: more rows than estimated, < 1: fewer. Permissions: as for query 1, that is, with VIEW DEFINITION if the plan_handle is determined via OBJECT_ID as there. OPTION (MAXDOP 1): the diagnostic query should not tie up parallel workers. */DECLARE @plan_handle varbinary(64) = 0x0; -- insert here WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')SELECT o.node_id, o.operator, o.object_name, CAST(o.estimated AS decimal(18, 1)) AS estimated, CAST(o.actual AS decimal(18, 0)) AS actual, CAST(CASE WHEN o.estimated > 0 THEN o.actual / o.estimated END AS decimal(18, 1)) AS factorFROM ( SELECT r.value('@NodeId', 'int') AS node_id, r.value('@PhysicalOp', 'nvarchar(60)') AS operator, r.value('(*/Object/@Table)[1]', 'nvarchar(260)') AS object_name, r.value('@EstimateRows', 'float') * (1 + ISNULL(r.value('@EstimateRebinds', 'float'), 0) + ISNULL(r.value('@EstimateRewinds', 'float'), 0)) AS estimated, r.value('sum(RunTimeInformation/RunTimeCountersPerThread/@ActualRows)', 'float') AS actual FROM sys.dm_exec_query_plan_stats(@plan_handle) AS qps CROSS APPLY qps.query_plan.nodes('//RelOp') AS x(r) WHERE r.exist('RunTimeInformation') = 1) AS oORDER BY ABS(LOG(o.actual + 1) - LOG(o.estimated + 1)) DESCOPTION (MAXDOP 1);In the sniffing case from our lab, the result looks like this, the same on SQL Server 2019, 2022 and 2025:
| node_id | operator | object_name | estimated | actual | factor |
|---|---|---|---|---|---|
| 2 | Index Seek | [Tickets] | 5.0 | 100000 | 20000.0 |
| 0 | Sort | NULL | 5.0 | 100000 | 20000.0 |
| 1 | Nested Loops | NULL | 5.0 | 100000 | 20000.0 |
| 2 | Index Seek | [Tickets] | 5.0 | 100000 | 20000.0 |
| 4 | Clustered Index Seek | [Tickets] | 5.0 | 100000 | 20000.0 |
| 1 | Stream Aggregate | NULL | 1.0 | 1 | 1.0 |
Five operators were off by a factor of 20,000; only the count at the end was right. The procedure has two statements, which is why node IDs appear twice. For the same procedure, query 1 returned two executions, the last one being the slow one with the large owner. Query 2 put it at the top of the most CPU-expensive plans.
What has changed since 2019
- The foundation has stayed the same. Lightweight profiling v3 from SQL Server 2019 is still the current generation through 2025. The what's-new pages for 2022 and 2025 don't mention the function.
- Fixes: queries against the function could trigger access violations. Fixed in SQL Server 2019 CU20 and 2022 CU4. If you run older builds, you should know this.
- Permissions from 2022 on:
VIEW SERVER PERFORMANCE STATEis enough; fullVIEW SERVER STATEisn't required. - New from 2022 on:
FORCE_SHOWPLAN_RUNTIME_PARAMETER_COLLECTIONfor parameter values in lightweight plans. With a price of its own and no effect on the last plan. - Time values: unusable in 2019/2022 and in 2025, each in a different way (see above).
- Query Store hints (2022 and later): they let you give a single query a hint without changing the code. In the lab, this worked with the hint
QUERY_PLAN_PROFILE: every execution of the marked query delivered its actual plan to Extended Events (eventquery_plan_profile), including the runtime values of the parameters. Other queries were not affected. The marked query itself pays clearly on every execution, so use it only for a limited time or for rare queries. A plan guide is no longer needed for this. Details are in the overview of the profiling family.
Tools that already use the last plan
sp_BlitzCache from the First Responder Kit uses sys.dm_exec_query_plan_stats when the function exists and returns more than the regular cached plan. sp_Blitz reports an enabled option as a deviation from the default. That isn't an error, just a note that someone set it deliberately. For running queries, sp_WhoIsActive works with sys.dm_exec_query_statistics_xml, that is, with the plan while it runs. (Source code as of Nov 26, 2026.)
Snapshot and history
The last actual plan answers one question well: what happened during the last execution, row by row? It is no good for "What happened yesterday at 2 p.m.?". For that it is too short-lived, and it knows no times.
Query Store answers that question. It keeps plans, durations, CPU, wait times and plan changes over days and weeks. PSG QX analyzes exactly this data. QX shows when a query changed its plan, which executions fall outside the norm and what preceded them, without any additional capture on the server. Together this gives a complete picture: Query Store and QX tell you when and how often things get stuck, and the last plan shows, the next time it happens, at which operator.
Our recommendation
In most databases, there is little against turning on LAST_QUERY_PLAN_STATS, at a quiet time. Read in a targeted way, not the whole cache. Don't take times from the plan. And if your server runs at its limit all the time or you have monitoring scripts in place whose queries you don't know, take a closer look first or ask someone who has done this before.
How we tested
SQL Server 2019, 2022 and 2025 in Linux containers with eight cores; we did not measure separately on Windows. Synthetic data without any customer connection (500,000 orders, 2.5 million order lines, a columnstore copy, tickets with a skewed distribution). Five query shapes, each with a single session and with fully loaded cores, option on and off in alternating order, five repetitions. We measured the CPU time per call across the whole container. In addition, we looked at retrieval across a plan cache with many plans, a collector under load and a plan that many sessions run at the same time. We read the plan contents per version from the XML and compared them with sys.dm_exec_query_stats. The three queries above ran in the lab on all three versions, with full permissions and with restricted ones: the server permission alone is enough for query 2; queries 1 and 3 additionally need VIEW DEFINITION.
Sources
- Grant Fritchey, September 9, 2019: Get the Last Actual Plan With sys.dm_exec_query_plan_stats
- Microsoft Learn: sys.dm_exec_query_plan_stats, ALTER DATABASE SCOPED CONFIGURATION, Query profiling infrastructure, Trace flags
- Pedro Lopes, 2019: What if the Actual Execution Plan was always available for any query?
- SQL Server Team: Developers Choice: Query progress – anytime, anywhere
- Microsoft Support: SQL Server 2019 CU20 (KB5024276), SQL Server 2022 CU4 (KB5026717)
- Brent Ozar, April 21, 2026: There's a Bug in sys.dm_exec_query_plan_stats
- Source code: sp_BlitzCache, sp_WhoIsActive