Where to Look First When Nested MSTVFs Are Slow
A function calls a function that calls yet another function. Each level is easy to read on its own, well named and reused in several places. In applications that have grown over the years, multi-statement table-valued functions (MSTVFs) sometimes call further MSTVFs. Each of them collects intermediate results in table variables over several steps and returns a table at the end.
When such a query gets slow, the search usually starts with the execution plan. There the function appears as an inconspicuous operator with a fraction of the estimated cost. Which statement inside it uses the time is not shown in the caller’s actual plan, and every additional level makes it harder to find. This page shows how to make the work in the chain visible, where to look first and in which order to proceed.
In short
- The caller’s actual plan doesn’t show where the work is. An MSTVF appears there as a single operator with a low estimated cost. Its actual time tells you that a closer look is worthwhile, but not which statement uses the time. The function’s statements are in the estimated plan and in the plan cache.
- Often a single statement carries most of the load. In the lab it was a statement that read a large table without a suitable access path on every call.
- Check the access path first, then the form. A missing index hurts every kind of function, including after a rewrite to an inline function. The rewrite then makes the plan readable again and gives the optimizer the whole query.
- Totals across functions are misleading. In Query Store and in the plan cache, the counters of the caller and of the function’s statements overlap. If you add up every level of a chain, you count the same work several times.
What sets an MSTVF apart
SQL Server has three kinds of T-SQL functions. A scalar function returns a single value, an inline table-valued function is a single SELECT statement with parameters, and a multi-statement table-valued function fills a return table with any number of statements. The optimizer treats them very differently. It builds an inline function into the calling query as if it were a view. An MSTVF remains a closed unit to it: the optimizer knows its return table, but not how it is filled, and before execution it usually doesn’t know how many rows it will contain either.
The basics, with a lab comparison of all kinds of functions, are covered in T-SQL Functions: What the Optimizer Sees and What It Doesn’t. This series starts where functions are nested inside each other.
Why chains are different
A single MSTVF that reads a few rows through an index is rarely a problem. It gets difficult when several come together:
- Every level is an estimate for the optimizer. It plans the caller with a fixed row count for the function as long as interleaved execution doesn’t apply. In our test, interleaved execution applied only to the outermost call. For each nested call inside
INSERT … SELECT, the optimizer still used a fixed estimate for the number of rows returned. Row estimates in the chain shows which numbers that means at each level. - Calls multiply. If a function is called once per row, for example via
CROSS APPLY, its entire body runs for each of those rows, including all functions below it. A harmless-looking query can trigger dozens of function calls this way. - Every call fills a return table. Creating it, writing rows into it, reading them back: this happens even when the statements inside are cheap, and it happens serially. In a chain with many calls, it adds up.
- The work disappears from the actual plan. It only shows the caller’s query with the top-level function operator. The statements below are in the estimated plan and in the plan cache, as Invisible in the Plan shows.
What the chain looks like in your database, who calls whom and at what depth, is shown by PSG Function Tree: a read-only script for your database and a page that draws the result as a tree. The analysis runs only in your browser.
The one expensive statement
In one experiment, an MSTVF filled its return table in several steps. The last step joined a small intermediate result to a large log table that had no suitable index. Each call returned only a few dozen rows. Still, the work per call grew with the size of that table, because it was read on every call. This one statement carried almost the entire load of the function.
That is the danger of nested functions: they make such a statement hard to find and call it often. So look first for the statement whose work per call grows with the amount of data rather than with the size of the result.
This has a consequence for the rewrite. Without a suitable index, an inline version of the same logic built a temporary index on every call (Eager Index Spool). The expensive work remained; it was just visible in the plan now. Only with the suitable index did all variants use a seek. The index was the bigger lever, the rewrite to an inline function the second step.
In depth
Invisible in the plan
“According to the plan, the function costs almost nothing. So why is the query so slow?”
In depth, with labRead article →02Row estimates in the chain
“The plan says 100 rows, thousands come back. Where does the number come from?”
In depth, with labRead article →Which observation fits your case?
| Your observation | First look | In depth |
|---|---|---|
| The query is slow, but the plan shows only cheap operators and a function with a few percent | Check the estimated plan and the plan cache for the function’s statements | Invisible in the Plan |
SET STATISTICS XML returns a plan without the function’s statements | Plan cache and the function’s last actual plan | Invisible in the Plan |
STATISTICS IO reports hardly any reads, yet the query is slow | Tables inside the function are missing from the output | Invisible in the Plan |
| Nobody knows exactly which function calls which | Function dependencies as a tree | PSG Function Tree |
| The function returns thousands of rows, but the optimizer estimated only 100 | Estimated versus actual rows at the function operator | Row estimates in the chain |
| Inside the function, the plan shows 10,000 estimated rows or a table variable with one row | Estimates of the function calls and table variables at each level | Row estimates in the chain |
| Query Store shows more CPU for the functions combined than was actually used | Measurement scopes of nested calls | Where Does the Time Go? |
| The same function is sometimes fast, sometimes slow | First call after compilation | T-SQL Functions |
Where to start
- Make the chain visible. Which functions call which, how deep, and where do views or procedures sit in between? PSG Function Tree shows this from your database’s metadata. A deep chain is a candidate for review, not yet a finding.
- Find the expensive statement. The statements in the function body appear in the estimated plan and, with their own counters, in the plan cache. How to find them there and retrieve their actual plan is shown in Invisible in the Plan.
- Check the access path. If this statement reads a large table on every call, an index is often missing or a predicate isn’t sargable. An index can often be added without touching the application.
- Check the number of calls. If the caller filters earlier, fewer function calls run. That is another place to start.
- Only then change the form. Level by level from MSTVF to inline function, comparing the results after each step. Afterwards the optimizer sees the whole query again, and the caller’s plan shows the table access.
- Don’t add up; measure at the top. What counts for the effect is the load of the top-level query, i.e. the caller from the application. Totals across all function levels contain the same work several times.
What doesn’t help
- A higher compatibility level alone. From compatibility level 140, interleaved execution can improve the row estimate for suitable read-only calls. In the lab it applied to a direct call with a constant parameter, not to the correlated
CROSS APPLYand not to the inner calls of a chain. It does nothing for the expensive statement inside the function body, and table variable deferred compilation didn’t apply there to statements that use the return table (Row estimates in the chain). - Tuning only the caller’s plan. As long as the work sits in the function body, hints or indexes for the caller’s tables change little. An index that helps the function body doesn’t even change the caller’s plan.
- Wrapping the function in a scalar function. A scalar function on top of an MSTVF calls the chain once per row. In the lab, SQL Server 2022 did inline the scalar function via Scalar UDF Inlining, but the MSTVF operator remained in place for every outer row.
Sources
- Microsoft: Interleaved execution for multi-statement table-valued functions
- Microsoft: User-defined functions
- Microsoft:
sys.dm_exec_query_plan_stats - Erik Darling: Multi-Statement Functions
In depth: Invisible in the Plan · Row estimates in the chain · T-SQL Functions · Where Does the Time Go? · PSG Function Tree