The symptom
A scalar user-defined function looks like a cheap call in the query text. In the plan it is a Compute Scalar with a tiny estimated cost. What SQL Server really does is run the function body as a separate statement for every row that reaches it. Whatever the function reads is missing from the plan and from STATISTICS IO, and the whole query runs on one thread.
Since SQL Server 2019 the optimizer can inline many scalar functions into the calling query, which removes all three problems. It cannot inline every function, and inlining is off below compatibility level 150. The query plan viewer flags a function that was not inlined. The examples use a shop schema with 20,000 customers and 400,000 orders.
Diagnose it
A query that looks cheap and is not
This function counts a customer's orders. WITH INLINE = OFF makes it behave the way every scalar function behaves below compatibility level 150, and the way a function that cannot be inlined behaves on any version:
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
GO
CREATE FUNCTION dbo.CustomerOrderCount (@CustomerId int)
RETURNS int
WITH INLINE = OFF
AS
BEGIN
RETURN (SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @CustomerId);
END;
GO
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
GO
SELECT COUNT(*)
FROM dbo.Customers AS c
WHERE dbo.CustomerOrderCount(c.CustomerId) > 20;
Table 'Customers'. Scan count 1, logical reads 115, physical reads 0
CPU time = 606 ms, elapsed time = 637 ms.
The statistics list 115 page reads on Customers and nothing for Orders, although the function read that table 20,000 times. The CPU time, more than half a second for a query that reads 115 pages, is the only sign of it.
What the plan says
Capture the actual plan with SET STATISTICS XML ON, or with Include Actual Execution Plan in your client. Two things in the XML give the function away:
SET STATISTICS XML ON;
GO
SELECT COUNT(*)
FROM dbo.Customers AS c
WHERE dbo.CustomerOrderCount(c.CustomerId) > 20;
GO
SET STATISTICS XML OFF;
<QueryPlan DegreeOfParallelism="0" NonParallelPlanReason="TSQLUserDefinedFunctionsNotParallelizable"
<UserDefinedFunction FunctionName="[learnfx].[dbo].[CustomerOrderCount]">
O UserDefinedFunction element sits inside a Compute Scalar ou Filter operator. The NonParallelPlanReason on the root says the function is why the query ran on one thread; parallel plans that do not run in parallel lists the other reasons. (learnfx is the name of the test database.)
Count the calls
sys.dm_exec_function_stats keeps the totals the query's own statistics leave out:
SELECT OBJECT_NAME(object_id) AS function_name, execution_count,
total_worker_time, total_logical_reads
FROM sys.dm_exec_function_stats
WHERE database_id = DB_ID();
CustomerOrderCount 40000 1625467 161678
The columns are the function name, the number of executions, the CPU time in microseconds and the logical reads. The two runs above called the function 40,000 times. Each call is an index seek of a few pages, cheap on its own; the cost is paying for a separate statement 20,000 times per query.
Find out whether a function can be inlined
A function with a time-dependent call such as GETDATE() is one of the kinds that cannot be inlined. sys.sql_modules says so:
CREATE FUNCTION dbo.OrderAgeDays (@OrderDate datetime2)
RETURNS int
AS
BEGIN
RETURN DATEDIFF(day, @OrderDate, GETDATE());
END;
GO
SELECT o.name, m.is_inlineable, m.inline_type
FROM sys.sql_modules AS m
JOIN sys.objects AS o ON o.object_id = m.object_id
WHERE o.type = 'FN'
ORDER BY o.name;
CustomerOrderCount 1 0
OrderAgeDays 0 0
The columns are the name, is_inlineable e inline_type. CustomerOrderCount could be inlined but has inlining turned off. OrderAgeDays cannot be inlined at all. Also check the two switches that apply to the whole database:
SELECT name, value FROM sys.database_scoped_configurations
WHERE name = 'TSQL_SCALAR_UDF_INLINING';
SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME();
Inlining needs the configuration set to 1 and a compatibility level of 150 or higher.
Fix it
Let SQL Server inline the function
If the function is inlineable and something switched inlining off, switch it back on. For a function created WITH INLINE = OFF, alter it without the option:
ALTER FUNCTION dbo.CustomerOrderCount (@CustomerId int)
RETURNS int
AS
BEGIN
RETURN (SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @CustomerId);
END;
GO
SELECT COUNT(*)
FROM dbo.Customers AS c
WHERE dbo.CustomerOrderCount(c.CustomerId) > 20;
Table 'Orders'. Scan count 20000, logical reads 64698, physical reads 0
Table 'Customers'. Scan count 8, logical reads 340, physical reads 0
CPU time = 186 ms, elapsed time = 30 ms.
The reads on Orders are now visible, the query ran in parallel, and the elapsed time fell from more than half a second to a few hundredths. In the plan XML the root element carries ContainsInlineScalarTsqlUdfs="1" e o UserDefinedFunction element is gone.
Rewrite the function as an inline table-valued function
An inline table-valued function is a view with parameters. The optimizer expands it into the calling query on every version, with no compatibility level to depend on:
CREATE FUNCTION dbo.CustomerOrderCounts (@CustomerId int)
RETURNS TABLE
AS
RETURN (SELECT COUNT(*) AS OrderCount FROM dbo.Orders WHERE CustomerId = @CustomerId);
GO
SELECT COUNT(*)
FROM dbo.Customers AS c
CROSS APPLY dbo.CustomerOrderCounts(c.CustomerId) AS oc
WHERE oc.OrderCount > 20;
Table 'Customers'. Scan count 1, logical reads 115, physical reads 0
Table 'Orders'. Scan count 1, logical reads 701, physical reads 0
Here the optimizer went further than the inlined scalar function allowed: it read the index on Orders once, grouped it, and joined the result to Customers, in place of 20,000 separate seeks.
Replace a simple calculation with the expression
A function that only computes something from its arguments is usually better written out. The function version cannot be inlined because of GETDATE():
SELECT COUNT(*) FROM dbo.Orders WHERE dbo.OrderAgeDays(OrderDate) > 1000;
SELECT COUNT(*) FROM dbo.Orders WHERE DATEDIFF(day, OrderDate, GETDATE()) > 1000;
CPU time = 868 ms, elapsed time = 993 ms.
CPU time = 38 ms, elapsed time = 38 ms.
Both read the same 2,579 pages. The first line is the function version: the call adds most of a second of CPU for 400,000 rows. Neither form can use an index on OrderDate; for that, compare the bare column with a computed date, as the non-sargable predicates guide shows.
When to leave it alone
A scalar function called for a handful of rows costs nothing worth fixing: in the select list of a query that returns ten rows, or on a variable in a stored procedure. The same goes for a function the plan shows as inlined. Rewrite the ones that sit in a WHERE clause, a join condition or the select list of a query that handles many thousands of rows.
The checklist
Work through it in order. Each step gives you the evidence for the next one.
- Look for a UserDefinedFunction element or a NonParallelPlanReason of TSQLUserDefinedFunctionsNotParallelizable in the plan XML.
- Do not trust STATISTICS IO for this query; read the function's totals from sys.dm_exec_function_stats.
- Check is_inlineable in sys.sql_modules for the function.
- Check TSQL_SCALAR_UDF_INLINING and the database compatibility level (150 or higher).
- Inlineable: remove WITH INLINE = OFF or turn inlining back on.
- Not inlineable: rewrite it as an inline table-valued function with CROSS APPLY, or write the expression in the query.
- Capture the plan again and confirm the function call is gone and the plan can go parallel.
Questions that come up
Why is a scalar user-defined function slow in SQL Server?
Unless it is inlined, SQL Server runs the function body as a separate statement for every row. A query over 400,000 rows makes 400,000 calls. The calls cannot be spread over several threads, so the whole query also runs serial.
Why does STATISTICS IO show no reads for the table my function queries?
STATISTICS IO reports the reads of the calling statement only. Reads made inside a scalar function that was not inlined are left out, and the plan shows no operators for them. sys.dm_exec_function_stats has the real totals per function.
What is scalar UDF inlining?
From SQL Server 2019, at compatibility level 150 or higher, the optimizer can replace a call to a scalar function with the function's logic, as if you had written a subquery. The reads then show in the plan and the query can run in parallel. Not every function qualifies; sys.sql_modules.is_inlineable shows which do.
How do I know whether my function was inlined?
In the actual plan XML, an inlined call leaves ContainsInlineScalarTsqlUdfs="1" on the QueryPlan element and no UserDefinedFunction element. A call that was not inlined shows the UserDefinedFunction element and a NonParallelPlanReason of TSQLUserDefinedFunctionsNotParallelizable.
Is an inline table-valued function faster than a scalar function?
Usually, and on every version. An inline table-valued function is expanded into the calling query like a view, so the optimizer can join, group and parallelize across it. A scalar function gets that treatment only when it is inlineable and inlining is on.