The One Costly Statement: Why an MSTVF Reads the Same Table Again and Again
In part 1, you found the statement inside the function that does most of the work. The obvious next step is to rewrite the multi-statement table-valued function (MSTVF) as an inline table-valued function. In our example, that wasn’t enough without a suitable index: the rewritten function still read the whole events table on every call. Using one example in four forms, this page shows what happens without an index, what a suitable index changes, why SQL Server doesn’t always report the missing index, and why an existing index can stay useless when the data type doesn’t match and SQL Server has to apply an implicit conversion. We tested the access paths and the German version of the query on SQL Server 2017, 2019, 2022, and 2025, the English version of the query on 2017 and 2022, and the comparison with a table four times as large on 2022 only.
In short
- Without a suitable index, the costly statement read the whole table on every call, and inside the MSTVF even once per shipment. The work grows with the table, not with the result: with a table four times as large, every measured form read four times as much, and the result stayed the same.
- Without an index, the form of the function only decided how SQL Server read the table. The MSTVF scanned the table once per shipment. With many shipments, the inline function built a temporary index over the whole table on every execution (eager index spool); with few shipments, it also scanned once per shipment. With a suitable index, all four forms reached the events with a seek.
- SQL Server didn’t always report the missing index, and not where you would look. For the scan in the MSTVF, the suggestion appeared only in the plan of the function’s statement, not in the caller’s plan. For the eager index spool, there was none at all.
- An index doesn’t help when the column is converted. An
nvarcharparameter compared with avarcharcolumn led to an index scan under a SQL collation, inside the MSTVF on every call of the function. Under a Windows collation, the seek remained.
The example: the same logic in four forms
The synthetic shop from the previous parts, with about two million shipment events. We want the latest status of every shipment of an order, in four forms:
- MSTVF as in part 1: collects the shipments in
@sand writes the result to the return table withCROSS APPLY (SELECT TOP (1) …), - MSTVF with a detour: writes the same step to a local table variable first, as in part 2,
- inline function with the same query,
- a query without a function.
Part 1 shows the code of the MSTVF and the inline function, part 2 the version with the detour. Without a function, the same logic looks like this:
SELECT sh.ShipmentId, e.Status, e.EventTimeFROM dbo.Shipments AS shCROSS APPLY (SELECT TOP (1) ev.Status, ev.EventTime FROM dbo.ShipmentEvents AS ev -- this is where the work is WHERE ev.ShipmentId = sh.ShipmentId ORDER BY ev.EventTime DESC) AS eWHERE sh.OrderId = 200003;We called every form for an order with 30 shipments, through CROSS APPLY for the five orders of one customer with seven shipments in total (for the MSTVFs, that means five function calls), and for an order with 2,000 shipments, each twice in a row. All forms returned the same rows in all cases.
Without a suitable index
The events table had no index that starts with ShipmentId. So every form has to read to find the events of a shipment. How it did that depended on the form:
| Form | 30 shipments | 7 shipments (five orders) | 2,000 shipments |
|---|---|---|---|
| MSTVF | scan per shipment: 30 scans | 7 scans | 2,000 scans |
| MSTVF with a detour | from 2019 on (level 150+) eager index spool, one scan; 2017: 30 scans | 7 scans | from 2019 on spool, one scan; 2017: 2,000 scans |
| inline function | eager index spool, one scan | 7 scans | eager index spool, one scan |
| without a function | as inline | as inline | as inline |
Each of these scans reads the whole events table with its roughly two million rows. With 2,000 shipments, the MSTVF read it 2,000 times, for 2,000 result rows. An eager index spool reads it once and builds a temporary index from it, which SQL Server then searches for each shipment. That is less, but still the whole table for a few dozen or a few thousand result rows.
Three observations:
- The MSTVF never got a spool. The optimizer estimated a single execution of the scan; there were actually 30 or 2,000. This matches part 2: the statement writes to the return table, and as there, the optimizer estimated one row for
@s. The version with the detour got the spool from 2019 on if the first call, which shapes the plan, had enough shipments. - With few outer rows, the inline function also chose a scan per row. For the five orders, the optimizer estimated only three to eight shipments and did without the spool.
- The spool was rebuilt on every execution. With 30 shipments, the plan shows one build and 29 reuses, and on the second call another build: the scan below it read the whole table each time. The plan stays in the cache, the temporary index doesn’t. This agrees with Microsoft’s description, according to which an index spool exists only for the duration of the query.
The work grows with the table. With an events table four times as large (on SQL Server 2022 only), the same orders and the same results, every measured form without an index read exactly four times as many rows; we left out the MSTVF with 2,000 shipments. This exact pattern gives the costly statement away: the result stays small, the work per call grows with the data.
With a suitable index
CREATE INDEX IX_ShipmentEvents_ShipmentId_EventTime ON dbo.ShipmentEvents (ShipmentId, EventTime DESC) INCLUDE (Status);ShipmentId serves the equality search, EventTime DESC provides the order for TOP (1), and Status is an INCLUDE column of the index so that no lookup is needed. If two events of a shipment can have the same time, the “latest status” needs a second, unique sort key anyway.
With this index, all four forms looked the same on all versions: nested loops with one index seek per shipment that reads exactly one row, the newest entry. No scan, no spool. The rows read matched the number of shipments, with the original table and with the table four times as large.
For this access, the index made the difference between the forms irrelevant. The MSTVFs still fill their table variables, and the version with the detour fills an additional one; the index doesn’t change that. Rewriting as an inline function is therefore still worthwhile, because the optimizer then sees the whole query and the caller’s plan can be checked. In this example, however, it was the second step, not the first.
Where SQL Server reports the missing index
The optimizer writes index suggestions into the plan, and SQL Server collects them in the sys.dm_db_missing_index_* views. In our example, whether and where a suggestion appeared depended on the form:
| Access | Suggestion in the function’s plan | Suggestion in the caller’s plan | Missing index views |
|---|---|---|---|
| scan per shipment in the MSTVF | yes | no | yes, from SQL Server 2019 on mapped to the function’s statement |
| scan per shipment in the inline function or the query | – | yes | yes |
| eager index spool | no | no | no |
| with a suitable index | no | no | no |
- You find the suggestion from the function in the plan of its statement, here the second
INSERT, not in the caller’s plan. If you look only at the actual plan of the slow query, you won’t find a suggestion. Get the plan of the function’s statement from the plan cache as in part 1. - An eager index spool is a reason to check the index, even without a suggestion. No missing index suggestion appeared for this access; Paul White and Erik Darling describe the same. In the plan, you recognize it by the physical operator “Index Spool” with the logical operation “Eager Spool”. Its seek columns show what is searched for; they don’t give you a complete index.
- In our tests, the counter in the views counted executions of the statement, not scans. The sum of
user_seeksanduser_scansof the suggestion group went up by two for two calls of the MSTVF with 30 scans each, and by ten for two calls over five orders each. From SQL Server 2019 on,sys.dm_db_missing_index_group_stats_querymaps the suggestion to the function’s statement. - The suggestion was incomplete. It named only
ShipmentId, withoutINCLUDE. But the statement looks for the newest entry per shipment and reads the status. We tested the index with all three columns from above; we didn’t test an index that follows the suggestion alone.
When the index exists and still doesn’t help
A missing index isn’t the only reason for a scan. Often the index exists, but the predicate doesn’t fit it. A well-known case: the column is varchar, and the application passes the value as nvarchar. Because nvarchar has the higher data type precedence, SQL Server converts the column, not the value.
In the shop, a function looks up the latest status for a tracking number. Shipments.TrackingNo is varchar(20) with its own index, the parameter is nvarchar(20):
CREATE FUNCTION dbo.tvf_ShipmentStatusByTracking (@TrackingNo nvarchar(20))RETURNS @t TABLE (ShipmentId int NOT NULL, Status tinyint NOT NULL, EventTime datetime2(0) NOT NULL)ASBEGIN INSERT @t (ShipmentId, Status, EventTime) SELECT sh.ShipmentId, e.Status, e.EventTime FROM dbo.Shipments AS sh CROSS APPLY (SELECT TOP (1) ev.Status, ev.EventTime FROM dbo.ShipmentEvents AS ev WHERE ev.ShipmentId = sh.ShipmentId ORDER BY ev.EventTime DESC) AS e WHERE sh.TrackingNo = @TrackingNo; -- varchar column = nvarchar parameter RETURN;END;In our tests, whether this hurts depended on the collation of the column, the same on all four versions. The table shows the lookup of a single tracking number, as an MSTVF, an inline function and a query without a function:
| Parameter | Collation of the column | Access to Shipments | Warning in the plan |
|---|---|---|---|
nvarchar(20) | SQL collation (SQL_Latin1_General_CP1_CI_AS) | index scan over all of the roughly 300,000 tracking numbers | Type conversion … may affect "SeekPlan" |
nvarchar(20) | Windows collation (Latin1_General_CI_AS) | index seek over a small range (two rows) | none |
varchar(20) | both | index seek | none |
Microsoft documents the rule for data type precedence; which plans result from it is our observation. When an inline function ran the lookup for many tracking numbers from a table, the optimizer chose other plans in some cases, which we don’t generalize here. In the MSTVF, the scan repeats on every call of the function: for 2,000 tracking numbers, the function read the whole index 2,000 times. Like the index suggestion, the warning appears only in the plan of the function’s statement. There was no missing index suggestion here; the index already exists.
The fix is in the data type: give the function’s parameter the type of the column, here varchar(20). Check first that its length and character set cover every value that can arrive. Then SQL Server converts the passed value once instead of every row of the column, and the seek also worked when the caller passed N'…'. Whether the application sends strings as nvarchar depends on the driver and its settings; with Microsoft’s JDBC driver, for example, Unicode is the default.
What this means for the rewrite
For this status query, the suitable access path was the first step: create the index or correct the data type. Both worked in every form of the function and often need no change to the application. After that, rewriting as an inline function pays off, because it removes the fixed estimates and the return table and makes the caller’s plan meaningful. Without an index, in our tests it replaced the scan per row with a spool that reads the whole table on every execution, and with few shipments it kept the scan per shipment. Whether a change works is shown by the work of the top-level query, not by the sum over all function levels (overview).
Query: costly access paths in MSTVF statements
The following query searches the plans that are currently in the cache for the current database for statements in multi-statement functions whose plan points to a missing or unusable access path: scans of larger tables, eager index spools, missing index suggestions and conversion warnings. Each row belongs to exactly one statement. With @mstvf_only = 0, it checks all statements of the database; inline functions then appear through the plans of their callers. It examines all matching plans before it limits the output; @top_rows limits the output only. An early filter such as @function_name = N'dbo.tvf_OrderStatus' is a good way in.
Query: costly access paths in MSTVF statements
/* PSG · Nested MSTVFs · Query 3: Costly access paths in MSTVF statements Costly access paths in multi-statement TVF statements, from the plan cache As of Nov 27, 2026 · German version tested on SQL Server 2017 CU31, 2019 CU32, 2022 CU27, 2025 CU10; this English version run on 2017 CU31 and 2022 CU27 WARNING: Read-only (plan cache DMVs). Changes no data, objects, database or server settings; it only sets session options (NOCOUNT, QUOTED_IDENTIFIER) and creates two temporary tables in tempdb (#psg_plans, #psg_findings) that are dropped at the end. The two DROP TABLE IF EXISTS statements at the start drop temporary tables #psg_... of the same names in your own session: run it in a new query window if possible. The query reads statistics and text of every statement in the plan cache of the instance, fetches the statement plan of every statement of the current database (or of every MSTVF statement) and shreds the plans with a scan, spool, missing index request or conversion warning with XQuery. @top_rows limits the output only, not this work; on a large or busy server this can use noticeable CPU and memory (early filter: @function_name). Run it at your own risk, on a test system or outside peak load first. Statement text and expressions from the plan cache may contain confidential values: review the output before you share it. - Parameters: @top_rows limits the output only (after the work on all plans). @min_table_rows filters scan findings only (spools, missing indexes and conversions stay). @function_name filters early, before the plans are fetched and shredded, and is the best way in, e.g. @function_name = N'dbo.tvf_OrderStatus'. If @function_name is not NULL but not a valid name (PARSENAME returns NULL, e.g. more than four parts), the query stops with a message instead of running without a filter. - Run it in the database that contains the functions. Permissions: VIEW SERVER STATE (2017/2019) or VIEW SERVER PERFORMANCE STATE (2022 and later); without it SQL Server raises a permission error (Msg 300). The login must also see the functions in the metadata (VIEW DEFINITION on the function, schema or database is enough). With the server permission alone the list therefore stays empty for @mstvf_only = 1 if the login cannot see the metadata (e.g. a login without roles); logins that can see the metadata (e.g. sysadmin, db_owner) need nothing more. A note at the end gives the number of modules that are not visible; with @mstvf_only = 0 they appear as "module (name not visible)" with object_id. - Scope: only plans that are in the cache right now, only statements that were executed at least once since they were compiled, whose text belongs to the current database (dbid), and only tables of the current database (scans and spools; no table variables, no temporary tables, no system objects). Missing: evicted plans, ad hoc plan stubs (optimize for ad hoc workloads), statements with OPTION (RECOMPILE) (last plan only, often not cached) and plans that cannot be converted to xml (nested too deeply; counted only). Default @mstvf_only = 1: statements in multi-statement functions only (sys.objects.type = 'TF'). Inline functions have no plan of their own; their accesses appear with @mstvf_only = 0 in the plan of the caller (without the name of the inline function). The query does not list seeks: an empty list alone does not confirm a good access path (the plan may also be missing, see above). To check, repeat the same call and open the actual plan of the function. - Mapping: every row comes from a row of sys.dm_exec_query_stats (plan_handle and offsets) and its statement plan (sys.dm_exec_text_query_plan), so executions, text and position belong to the statement. stmt_comp_id (StatementCompId) and node_id (NodeId) tie the row to the cached and to the last actual plan. - finding_type: Scan Table Scan, Clustered Index Scan or Index Scan on a table with at least @min_table_rows rows (TableCardinality). columns = columns of the table in the predicate of the scan. A scan on the inner side of a nested loops runs again for every outer row. If it sits directly under an eager index spool, note says so: it reads the table for the spool. (A lazy spool does not get this note.) Eager Index Spool Temporary index that SQL Server rebuilds from the base table on every execution of the statement (reading the table). columns = equality (prefix), range_columns = StartRange/EndRange, details = output columns of the spool. There is no missing index request for it. If the spool has a complex input (joins, filters), table_name names the first base table found. Missing Index Index suggestion in the plan (MissingIndexGroup): columns = EQUALITY, range_columns = INEQUALITY, details = INCLUDE, impact = improvement in percent estimated by the optimizer (untested). Conversion Warning PlanAffectingConvert, only if the expression contains a column of a table of the current database. details = ConvertIssue ("Seek Plan": can prevent a seek; "Cardinality Estimate": can disturb the estimate) and expression. table_name/columns = first column reference in the expression that can be resolved. Which side is converted is shown by the expression in details: for [t].[ColumnW]=CONVERT_IMPLICIT(varchar(20),[s].[Column],0), columns shows ColumnW, but [s].[Column] is converted. - estimated_executions = 1 + EstimateRebinds + EstimateRewinds at the operator, per execution of the statement. In MSTVFs it often rests on an estimate of 1 row for a table variable (see part 2) and can then be far below the actual number. table_rows = TableCardinality; estimated_rows_read = EstimatedRowsRead per execution of the operator (missing if the plan does not give it). - last_executions / last_rows_read (SQL Server 2019 and later): ActualExecutions or ActualRowsRead of the last execution, summed over all threads, from sys.dm_exec_query_plan_stats; queried only for the rows that are returned. The columns are filled if SQL Server keeps the last actual plan: with the database option LAST_QUERY_PLAN_STATS = ON or server-wide with trace flag 2451 (then also without the option). The query does not evaluate the option but always asks from 2019 on; query_note states the setting of the option. In the lab, 2022 and 2025 returned the last plan anyway for some of the statements (all statements in modules, but only 7 of 13 ad hoc and prepared statements; cause not clarified) with the option off and without the trace flag; 2019 then returned nothing (NULL). For an MSTVF this is the last call of the function. For an eager index spool, last_rows_read is ActualRows of the child operator below it, i.e. the rows the input delivered (with a filtered input ActualRowsRead can be higher). The last actual plan does not always contain ActualRowsRead (not for function plans in the lab): then NULL. NULL = no run-time data (before 2019, no last plan, counter missing, missing index, conversion). - statement_executions: execution_count of the statement since its compilation (for an MSTVF: calls of the function that executed this statement). Several findings of the same statement show the same value. - @function_name: 'name' searches all schemas, 'schema.name' exactly this object (also procedures, with @mstvf_only = 0).*/SET NOCOUNT ON;SET QUOTED_IDENTIFIER ON; DECLARE @mstvf_only bit = 1; -- 1 = MSTVF statements only; 0 = all statements of the database (inline functions via their callers)DECLARE @min_table_rows bigint = 1000; -- skip scans of smaller tables (TableCardinality)DECLARE @function_name nvarchar(300) = NULL; -- NULL = all modules, else 'name' or 'schema.name'DECLARE @top_rows int = 100; -- number of rows, ordered by executionsDECLARE @text_length int = 120; -- characters of statement text -- Invalid name (PARSENAME = NULL, e.g. more than four parts): stop instead of running without a filterIF @function_name IS NOT NULL AND PARSENAME(@function_name, 1) IS NULLBEGIN RAISERROR(N'@function_name is not a valid name (expected: name or schema.name, special characters in square brackets). Stopped, nothing was read.', 16, 1); RETURN;END; DECLARE @f_name sysname = PARSENAME(@function_name, 1), @f_schema sysname = PARSENAME(@function_name, 2);DECLARE @db nvarchar(260) = QUOTENAME(DB_NAME()); DROP TABLE IF EXISTS #psg_plans;DROP TABLE IF EXISTS #psg_findings;CREATE TABLE #psg_plans ( id int IDENTITY(1, 1) PRIMARY KEY, plan_handle varbinary(64) NOT NULL, start_offset int NOT NULL, statement_executions bigint NOT NULL, object_type nvarchar(60) NULL, object_name nvarchar(300) NULL, statement_text nvarchar(max) NULL, x xml NULL);CREATE TABLE #psg_findings ( plan_id int NOT NULL, stmt_comp_id int NULL, node_id int NULL, sort_order tinyint NOT NULL, finding_type nvarchar(30) NOT NULL, table_name nvarchar(400) NULL, columns nvarchar(max) NULL, range_columns nvarchar(max) NULL, details nvarchar(max) NULL, estimated_executions float NULL, table_rows float NULL, estimated_rows_read float NULL, impact float NULL, note nvarchar(400) NULL); -- 1. Statements of the current database with a plan; convert only plans with a scan, eager spool, missing index or conversion warning to xmlINSERT #psg_plans (plan_handle, start_offset, statement_executions, object_type, object_name, statement_text, x)SELECT qs.plan_handle, qs.statement_start_offset, qs.execution_count, CASE WHEN cp.objtype = N'Adhoc' THEN N'ad hoc' WHEN cp.objtype = N'Prepared' THEN N'prepared' WHEN o.object_id IS NOT NULL THEN o.type_desc WHEN st.objectid IS NOT NULL THEN N'module (name not visible)' ELSE cp.objtype END, CASE WHEN cp.objtype IN (N'Adhoc', N'Prepared') THEN N'-' WHEN o.object_id IS NOT NULL THEN SCHEMA_NAME(o.schema_id) + N'.' + o.name ELSE CONCAT(N'object_id ', st.objectid) END, LEFT(LTRIM(REPLACE(REPLACE(REPLACE(SUBSTRING(st.text, qs.statement_start_offset / 2 + 1, (CASE WHEN qs.statement_end_offset = -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1), NCHAR(13), N' '), NCHAR(10), N' '), NCHAR(9), N' ')), @text_length), TRY_CONVERT(xml, tqp.query_plan)FROM sys.dm_exec_query_stats AS qsINNER JOIN sys.dm_exec_cached_plans AS cp ON cp.plan_handle = qs.plan_handleCROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) AS stCROSS APPLY sys.dm_exec_text_query_plan(qs.plan_handle, qs.statement_start_offset, qs.statement_end_offset) AS tqpLEFT JOIN sys.objects AS o ON o.object_id = st.objectidWHERE st.dbid = DB_ID() AND (@mstvf_only = 0 OR o.type = 'TF') AND (@f_name IS NULL OR (o.name = @f_name AND (@f_schema IS NULL OR SCHEMA_NAME(o.schema_id) = @f_schema))) AND ( tqp.query_plan LIKE N'%PhysicalOp="Table Scan"%' OR tqp.query_plan LIKE N'%PhysicalOp="Clustered Index Scan"%' OR tqp.query_plan LIKE N'%PhysicalOp="Index Scan"%' OR tqp.query_plan LIKE N'%LogicalOp="Eager Spool"%' OR tqp.query_plan LIKE N'%<MissingIndexes>%' OR tqp.query_plan LIKE N'%<PlanAffectingConvert %')OPTION (MAXDOP 1); -- Modules whose metadata the login cannot see (cannot be checked with @mstvf_only = 1)DECLARE @not_visible int = 0, @not_readable int = 0; SELECT @not_visible = COUNT(DISTINCT st.objectid)FROM sys.dm_exec_query_stats AS qsCROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) AS stLEFT JOIN sys.objects AS o ON o.object_id = st.objectidWHERE st.dbid = DB_ID() AND st.objectid IS NOT NULL AND o.object_id IS NULL AND @mstvf_only = 1OPTION (MAXDOP 1); SELECT @not_readable = COUNT(*) FROM #psg_plans WHERE x IS NULLOPTION (MAXDOP 1); -- 2a. Scans on tables of the current databaseWITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_findings (plan_id, stmt_comp_id, node_id, sort_order, finding_type, table_name, columns, estimated_executions, table_rows, estimated_rows_read, note)SELECT p.id, s.stmt.value(N'(@StatementCompId)[1]', N'int'), r.op.value(N'(@NodeId)[1]', N'int'), 2, N'Scan', v.sch + N'.' + v.tab + ISNULL(N'.' + v.idx, N''), NULLIF(REPLACE(r.op.query(N'for $c in distinct-values(*/Predicate//ColumnReference[@Database = sql:variable("@db") and @Table = sql:column("v.tab")]/@Column) return concat("[", $c, "]")').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), 1 + ISNULL(r.op.value(N'(@EstimateRebinds)[1]', N'float'), 0) + ISNULL(r.op.value(N'(@EstimateRewinds)[1]', N'float'), 0), r.op.value(N'(@TableCardinality)[1]', N'float'), r.op.value(N'(@EstimatedRowsRead)[1]', N'float'), CONCAT(r.op.value(N'(@PhysicalOp)[1]', N'nvarchar(60)'), CASE WHEN r.op.value(N'(../../@PhysicalOp)[1]', N'nvarchar(60)') = N'Index Spool' AND r.op.value(N'(../../@LogicalOp)[1]', N'nvarchar(60)') = N'Eager Spool' THEN N'; feeds an eager index spool' END)FROM #psg_plans AS pCROSS APPLY p.x.nodes(N'/ShowPlanXML/BatchSequence/Batch/Statements/*') AS s(stmt)CROSS APPLY s.stmt.nodes(N'*[local-name() = "QueryPlan" or local-name() = "Condition" or local-name() = "CursorPlan"]//RelOp[@PhysicalOp = "Table Scan" or @PhysicalOp = "Clustered Index Scan" or @PhysicalOp = "Index Scan"]') AS r(op)CROSS APPLY (SELECT r.op.value(N'(*/Object/@Database)[1]', N'nvarchar(260)') AS dbn, r.op.value(N'(*/Object/@Schema)[1]', N'nvarchar(260)') AS sch, r.op.value(N'(*/Object/@Table)[1]', N'nvarchar(260)') AS tab, r.op.value(N'(*/Object/@Index)[1]', N'nvarchar(260)') AS idx) AS vWHERE v.dbn = @db AND v.sch IS NOT NULL AND v.sch <> N'[sys]' AND ISNULL(r.op.value(N'(@TableCardinality)[1]', N'float'), 0) >= @min_table_rowsOPTION (MAXDOP 1); -- 2b. Eager index spools on tables of the current databaseWITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_findings (plan_id, stmt_comp_id, node_id, sort_order, finding_type, table_name, columns, range_columns, details, estimated_executions, table_rows, note)SELECT p.id, s.stmt.value(N'(@StatementCompId)[1]', N'int'), r.op.value(N'(@NodeId)[1]', N'int'), 1, N'Eager Index Spool', v.sch + N'.' + v.tab, NULLIF(REPLACE(r.op.query(N'for $c in Spool/*[local-name() = "SeekPredicateNew" or local-name() = "SeekPredicate"]//Prefix/RangeColumns/ColumnReference return concat("[", string($c/@Column), "]")').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), NULLIF(REPLACE(r.op.query(N'for $c in Spool/*[local-name() = "SeekPredicateNew" or local-name() = "SeekPredicate"]//*[local-name() = "StartRange" or local-name() = "EndRange"]/RangeColumns/ColumnReference return concat("[", string($c/@Column), "]")').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), NULLIF(REPLACE(r.op.query(N'for $c in OutputList/ColumnReference return concat("[", string($c/@Column), "]")').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), 1 + ISNULL(r.op.value(N'(@EstimateRebinds)[1]', N'float'), 0) + ISNULL(r.op.value(N'(@EstimateRewinds)[1]', N'float'), 0), r.op.value(N'(Spool/RelOp/@TableCardinality)[1]', N'float'), N'no missing index request; rebuilt per execution'FROM #psg_plans AS pCROSS APPLY p.x.nodes(N'/ShowPlanXML/BatchSequence/Batch/Statements/*') AS s(stmt)CROSS APPLY s.stmt.nodes(N'*[local-name() = "QueryPlan" or local-name() = "Condition" or local-name() = "CursorPlan"]//RelOp[@PhysicalOp = "Index Spool" and @LogicalOp = "Eager Spool"]') AS r(op)CROSS APPLY (SELECT r.op.value(N'(Spool/RelOp//Object[@Database = sql:variable("@db")]/@Schema)[1]', N'nvarchar(260)') AS sch, r.op.value(N'(Spool/RelOp//Object[@Database = sql:variable("@db")]/@Table)[1]', N'nvarchar(260)') AS tab) AS vWHERE v.tab IS NOT NULL AND v.sch IS NOT NULL AND v.sch <> N'[sys]'OPTION (MAXDOP 1); -- 2c. Missing index requests in the planWITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_findings (plan_id, stmt_comp_id, sort_order, finding_type, table_name, columns, range_columns, details, impact, note)SELECT p.id, s.stmt.value(N'(@StatementCompId)[1]', N'int'), 3, N'Missing Index', CASE WHEN m.mi.value(N'(@Database)[1]', N'nvarchar(260)') = @db THEN N'' ELSE m.mi.value(N'(@Database)[1]', N'nvarchar(260)') + N'.' END + m.mi.value(N'(@Schema)[1]', N'nvarchar(260)') + N'.' + m.mi.value(N'(@Table)[1]', N'nvarchar(260)'), NULLIF(REPLACE(m.mi.query(N'data(ColumnGroup[@Usage = "EQUALITY"]/Column/@Name)').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), NULLIF(REPLACE(m.mi.query(N'data(ColumnGroup[@Usage = "INEQUALITY"]/Column/@Name)').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), NULLIF(REPLACE(m.mi.query(N'data(ColumnGroup[@Usage = "INCLUDE"]/Column/@Name)').value(N'.', N'nvarchar(max)'), N'] [', N'], ['), N''), g.grp.value(N'(@Impact)[1]', N'float'), N'optimizer suggestion, untested'FROM #psg_plans AS pCROSS APPLY p.x.nodes(N'/ShowPlanXML/BatchSequence/Batch/Statements/*') AS s(stmt)CROSS APPLY s.stmt.nodes(N'QueryPlan/MissingIndexes/MissingIndexGroup') AS g(grp)CROSS APPLY g.grp.nodes(N'MissingIndex') AS m(mi)OPTION (MAXDOP 1); -- 2d. Conversion warnings (PlanAffectingConvert) with a column of a table of the current database-- The expression usually names the column with an alias ([sh].[TrackingNo]); the table for it is in the-- ColumnReference of the plan with the same alias. Four-part names ([db].[schema].[table].[column]) are read directly.WITH XMLNAMESPACES (DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')INSERT #psg_findings (plan_id, stmt_comp_id, sort_order, finding_type, table_name, columns, details, note)SELECT p.id, s.stmt.value(N'(@StatementCompId)[1]', N'int'), 4, N'Conversion', COALESCE(PARSENAME(t.part, 3) + N'.' + PARSENAME(t.part, 2), c.sch + N'.' + c.tab), COALESCE(QUOTENAME(PARSENAME(t.part, 1)), QUOTENAME(al.col_name)), CONCAT(w.cv.value(N'(@ConvertIssue)[1]', N'nvarchar(60)'), N': ', a.expression), CASE w.cv.value(N'(@ConvertIssue)[1]', N'nvarchar(60)') WHEN N'Seek Plan' THEN N'may prevent a seek' ELSE N'may affect the estimate' ENDFROM #psg_plans AS pCROSS APPLY p.x.nodes(N'/ShowPlanXML/BatchSequence/Batch/Statements/*') AS s(stmt)CROSS APPLY s.stmt.nodes(N'QueryPlan/Warnings/PlanAffectingConvert') AS w(cv)CROSS APPLY (SELECT w.cv.value(N'(@Expression)[1]', N'nvarchar(max)') AS expression) AS aOUTER APPLY (SELECT LEFT(SUBSTRING(a.expression, q.pos, 1000), PATINDEX(N'%[ ),=]%', SUBSTRING(a.expression, q.pos, 1000) + N' ') - 1) AS part FROM (SELECT CHARINDEX(@db + N'.', a.expression) AS pos) AS q WHERE q.pos > 0) AS tOUTER APPLY (SELECT SUBSTRING(a.expression, d.pos - CHARINDEX(N'[', REVERSE(LEFT(a.expression, d.pos))) + 1, CHARINDEX(N'[', REVERSE(LEFT(a.expression, d.pos)))) AS alias, SUBSTRING(a.expression, d.pos + 3, CHARINDEX(N']', a.expression + N']', d.pos + 3) - d.pos - 3) AS col_name FROM (SELECT CHARINDEX(N'].[', a.expression) AS pos) AS d WHERE d.pos > 0 AND t.part IS NULL) AS alOUTER APPLY (SELECT s.stmt.value(N'(.//ColumnReference[@Alias = sql:column("al.alias") and @Column = sql:column("al.col_name")]/@Database)[1]', N'nvarchar(260)') AS dbn, s.stmt.value(N'(.//ColumnReference[@Alias = sql:column("al.alias") and @Column = sql:column("al.col_name")]/@Schema)[1]', N'nvarchar(260)') AS sch, s.stmt.value(N'(.//ColumnReference[@Alias = sql:column("al.alias") and @Column = sql:column("al.col_name")]/@Table)[1]', N'nvarchar(260)') AS tab WHERE al.alias IS NOT NULL) AS cWHERE t.part IS NOT NULL OR (c.dbn = @db AND c.sch <> N'[sys]')OPTION (MAXDOP 1); -- 3. Result; last_* from the last actual plan: from SQL Server 2019 on always queried, independent of the database-- option (so trace flag 2451 works too); dynamic so that the query runs on 2017DECLARE @has_plan_stats bit = 0;DECLARE @lqps nvarchar(20) = NULL; SELECT @has_plan_stats = 1 FROM sys.all_objectsWHERE name = N'dm_exec_query_plan_stats' AND schema_id = SCHEMA_ID(N'sys')OPTION (MAXDOP 1); SELECT @lqps = CONVERT(nvarchar(20), value) FROM sys.database_scoped_configurationsWHERE name = N'LAST_QUERY_PLAN_STATS'OPTION (MAXDOP 1); -- CAST AS nvarchar(max): otherwise a concatenation is cut at 4,000 charactersDECLARE @node_source nvarchar(max) = CAST(N'(SELECT o.op.query(N''.'') AS op FROM sys.dm_exec_query_plan_stats(p.plan_handle) AS ps CROSS APPLY ps.query_plan.nodes(N''(//*[@StatementCompId = sql:column("t.stmt_comp_id")]/*[local-name() = "QueryPlan" or local-name() = "Condition" or local-name() = "CursorPlan"]//RelOp[@NodeId = sql:column("t.node_id")])[1]'') AS o(op))' AS nvarchar(max)); DECLARE @last_exec_expr nvarchar(max) = CAST(CASE WHEN @has_plan_stats = 1 THEN N'CASE WHEN t.node_id IS NOT NULL THEN (SELECT k.op.value(N''sum(/RelOp/RunTimeInformation/RunTimeCountersPerThread/@ActualExecutions)'', N''float'') FROM ' + @node_source + N' AS k WHERE k.op.exist(N''/RelOp/RunTimeInformation/RunTimeCountersPerThread'') = 1) END' ELSE N'CAST(NULL AS float)' END AS nvarchar(max)); DECLARE @last_rows_expr nvarchar(max) = CAST(CASE WHEN @has_plan_stats = 1 THEN N'CASE WHEN t.node_id IS NOT NULL THEN (SELECT CASE WHEN t.finding_type = N''Eager Index Spool'' THEN k.op.value(N''sum(/RelOp/Spool/RelOp/RunTimeInformation/RunTimeCountersPerThread/@ActualRows)'', N''float'') WHEN k.op.exist(N''/RelOp/RunTimeInformation/RunTimeCountersPerThread/@ActualRowsRead'') = 1 THEN k.op.value(N''sum(/RelOp/RunTimeInformation/RunTimeCountersPerThread/@ActualRowsRead)'', N''float'') END FROM ' + @node_source + N' AS k WHERE k.op.exist(N''/RelOp/RunTimeInformation/RunTimeCountersPerThread'') = 1) END' ELSE N'CAST(NULL AS float)' END AS nvarchar(max)); DECLARE @query_note nvarchar(400) = CONCAT(CASE WHEN @has_plan_stats = 0 OR @lqps IS NULL THEN N'last_* not available before SQL Server 2019' WHEN @lqps IN (N'0', N'OFF') THEN N'LAST_QUERY_PLAN_STATS OFF: last_* filled only if SQL Server keeps the last plan anyway (trace flag 2451; in the lab from 2022 for some statements)' ELSE N'LAST_QUERY_PLAN_STATS ON' END, N'; statement plans not convertible to xml: ', @not_readable); DECLARE @sql nvarchar(max) = CAST(N'' AS nvarchar(max)) + N'WITH XMLNAMESPACES (DEFAULT ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'')SELECT TOP (@top_rows) p.object_type, p.object_name, p.start_offset / 2 + 1 AS statement_start_char, p.statement_text, p.statement_executions, t.finding_type, t.table_name, t.columns, t.range_columns, t.details, t.estimated_executions, t.table_rows, t.estimated_rows_read, t.impact, ' + @last_exec_expr + N' AS last_executions, ' + @last_rows_expr + N' AS last_rows_read, t.note, @query_note AS query_note, CONVERT(varchar(130), p.plan_handle, 1) AS plan_handle, t.stmt_comp_id, t.node_idFROM #psg_findings AS tINNER JOIN #psg_plans AS p ON p.id = t.plan_idORDER BY p.statement_executions DESC, p.object_name, p.start_offset, t.sort_order, t.node_idOPTION (MAXDOP 1);'; EXEC sys.sp_executesql @sql, N'@top_rows int, @query_note nvarchar(400)', @top_rows = @top_rows, @query_note = @query_note; IF @not_readable > 0 PRINT CONCAT(N'Note: ', @not_readable, N' statement plan(s) not convertible to xml (nested too deeply), not checked.');IF @not_visible > 0 PRINT CONCAT(N'Note: ', @not_visible, N' module(s) with cached plans whose metadata this login cannot see (VIEW DEFINITION missing): not checked.'); DROP TABLE #psg_plans;DROP TABLE #psg_findings;How to read the result:
finding_typesays what was found:Scan,Eager Index Spool,Missing IndexorConversion. A statement can have several rows, for example a scan and a missing index together.table_nameandcolumnsshow where something is missing: for a scan, the column in the predicate; for a spool, its seek columns; for a missing index, the suggested equality columns. For a conversion, they show the first column in the expression; which side is converted is shown by the expression indetails.statement_executionscounts how often the statement ran since it was compiled; for an MSTVF, how often the function executed it. Many executions with a scan of a large table (table_rows) are the first candidate.estimated_executionsis what the optimizer expects per execution of the statement. In MSTVFs, it often shows 1, because the table variable is estimated with one row; in the example, the scan actually ran 30 or 2,000 times. From SQL Server 2019 on,last_executionsshows the real number from the last call of the function if SQL Server keeps the last actual plan, for example withLAST_QUERY_PLAN_STATSor trace flag 2451. Without either, the column stayed empty on 2019 in the lab; on 2022 and 2025, it was filled for some of the statements anyway.impactfor a missing index is the optimizer’s estimate, untested. Check the key order andINCLUDEyourself.- Empty list or a note on modules that aren’t visible: if the login can’t see the metadata of the functions (for example without
VIEW DEFINITION), their statements are missing; the query then gives the number of modules the login can’t see. An empty list doesn’t mean that all access paths are good: the query doesn’t list seeks, and it sees only what is in the cache right now.
From the lab database on SQL Server 2022, without an index on ShipmentEvents.ShipmentId (excerpt: selected rows, columns shortened):
| object_name | statement_executions | finding_type | table_name | columns | estimated_executions | table_rows | last_executions |
|---|---|---|---|---|---|---|---|
| dbo.tvf_OrderStatus | 6 | Scan | ShipmentEvents (Clustered Index) | ShipmentId | 1 | 2,007,000 | 30 |
| dbo.tvf_OrderStatus | 6 | Missing Index | ShipmentEvents | ShipmentId | |||
| dbo.tvf_OrderStatus_Detour | 6 | Eager Index Spool | ShipmentEvents | ShipmentId | 30 | 2,007,000 | 1 |
| dbo.tvf_ShipmentStatusByTracking | 7 | Scan | Shipments (IX_Shipments_TrackingNo) | TrackingNo | 1 | 302,333 | 1 |
| dbo.tvf_ShipmentStatusByTracking | 7 | Conversion | Shipments | TrackingNo |
The first row is the scan per shipment: estimated at one execution, actually 30 in the last call. The third is the spool of the version with the detour, without an index suggestion. The last two show the tracking number: the index is scanned, and the cause is in the conversion warning (details: Seek Plan: CONVERT_IMPLICIT(nvarchar(20),[sh].[TrackingNo],0)=[@TrackingNo]). The column table_rows is the optimizer’s estimate of the table size and can differ slightly from the actual row count.
How to proceed
- Find the costly statement. Query 1 from part 1 shows the statements in MSTVFs with their counters.
- Check the access path. The query above shows scans, spools, index suggestions and conversions in these statements. An eager index spool points to a missing index, even without a suggestion.
- Correct the index or the data type, on a test system first. Then repeat the same call with the same parameters, compare the results and open the actual plan of the function’s statement as in part 1: a seek instead of a scan or spool.
- Rewrite after that, level by level, comparing the results.
How we tested
We built the example on SQL Server 2017 CU31, 2019 CU32, 2022 CU27, and 2025 CU10, each at the default compatibility level (140 to 170), in Developer Edition on Linux. The basis was a shop schema with about two million shipment events, orders with 30 and 2,000 shipments, and five orders of one customer with seven shipments in total. Each of the four forms ran without an index and with a suitable index. As a separate case, the lookup of a tracking number in a varchar column ran under a SQL collation and a Windows collation, queried with an nvarchar and a varchar parameter, as an MSTVF, an inline function and a query without a function. On SQL Server 2022, the comparison also ran with an events table four times as large. We recorded the actual plans of the function’s statements for every call and analyzed plan shape, executions of the scans, rows read, spools, index suggestions and warnings, plus the missing index views. All forms returned the same rows. We didn’t collect timings.
Limits: synthetic schema, Linux rather than Windows, one example with TOP (1) per shipment, no load. The table four times as large only on 2022 and without the MSTVF with 2,000 shipments. We didn’t test an index that follows the optimizer’s suggestion exactly.
Sources
- Microsoft: Showplan logical and physical operators reference: Index Spool and Eager Spool
- Microsoft: Tune nonclustered indexes with missing index suggestions
- Microsoft: Data type precedence (Transact-SQL)
- Microsoft (archive): Implicit Conversions – Ouch!
- Microsoft (archive): Character data type conversion when using SQL Server JDBC drivers
- Paul White: The Eager Index Spool and The Optimizer
- Erik Darling: Eager Index Spools
- Solomon Rutzky: Impact on indexes when mixing varchar and nvarchar types
More in this series: Back to the overview: Nested MSTVFs · Invisible in the plan · Row estimates in the chain · PSG Function Tree