skip to content

After a SQL Server database moves to compatibility level 150, one report calling a scalar UDF per row speeds up and another stays slow; how do you explain and check that?

level: seniorimportance: should knowfreq 48%

answer

  1. a 2019 rewrite of the function
  2. eligibility is per function and per query
  3. time-dependent built-ins block it
  4. sys.sql_modules.is_inlineable
  5. no UserDefinedFunction node in the plan

basics

~20 s

Compatibility level 150 turns on scalar UDF inlining, which rewrites eligible functions into the calling query. A function using GETDATE() or table variables, or a call from ORDER BY, is not inlined and still runs once per row, serially.

solid answer

~50 s

Scalar UDF inlining arrived in SQL Server 2019 and is on by default at compatibility level 150 and later. It rewrites an eligible T-SQL scalar UDF into a scalar expression or subquery inside the calling query. The optimizer can then cost it, parallelize it and drop the per-row calls. The slow report broke a rule in the function or the calling query. Common culprits are `GETDATE()`, table variables, multiple `RETURN` statements (from 2019 CU5), a CTE, or calling the function from `ORDER BY`. To check, I read `is_inlineable` in `sys.sql_modules`, which only says whether the definition is eligible. Then I look in the actual plan: an inlined call has no `UserDefinedFunction` node. The usual fix is to pass the current time in as a parameter or simplify to one `RETURN`. Controls are `WITH INLINE = OFF`, the `TSQL_SCALAR_UDF_INLINING` database scoped configuration, and the `DISABLE_TSQL_SCALAR_UDF_INLINING` hint.

code

sql · 20 lines
sql
-- Not inlineable: depends on the current time
CREATE OR ALTER FUNCTION dbo.fn_AgeInDays (@d DATE)
RETURNS INT
AS
BEGIN
    RETURN DATEDIFF(DAY, @d, GETDATE());
END;
GO
-- Inlineable rewrite: the caller supplies the reference date
CREATE OR ALTER FUNCTION dbo.fn_AgeInDaysAt (@d DATE, @asOf DATE)
RETURNS INT
AS
BEGIN
    RETURN DATEDIFF(DAY, @d, @asOf);
END;
GO
SELECT o.name, m.is_inlineable
FROM sys.sql_modules AS m
JOIN sys.objects AS o ON o.object_id = m.object_id
WHERE o.name IN (N'fn_AgeInDays', N'fn_AgeInDaysAt');

go deeper

for a junior

Recall that SQL Server 2019 can inline scalar UDFs into the calling query at compatibility level 150, removing the per-row function calls.

for a middle

Explain why non-inlined scalar UDFs are slow: per-row calls, no costing and serial plans. Know that is_inlineable reports definition eligibility only.

for a senior

Diagnose a function that stayed slow: find the blocking construct or calling context, confirm it from the actual plan, then rewrite the function or pin it with INLINE = OFF.

for a principal

Plan a compatibility-level upgrade by inventorying scalar UDFs, deciding which to make inlineable, and watching for query-hash changes in your monitoring.

## What changed at compatibility level 150 A **T-SQL scalar user-defined function** returns one value per call. Before SQL Server 2019, a query that called one paid four costs: the function ran **once per qualifying row**, the optimizer **did not cost** the statements inside it, those statements ran **one at a time** with no cross-statement optimization, and the calling query **could not use parallelism**. SQL Server 2019 introduced **scalar UDF inlining**, part of the intelligent query processing features. When a database runs at **compatibility level 150 or later**, SQL Server automatically turns an eligible scalar UDF into a scalar expression or scalar subquery and places it inside the calling query. The plan then has no UDF operator, the optimizer sees joins and aggregates that the function's queries implied, and the plan can go parallel. Microsoft's example query took 29 minutes with the UDF and 1.6 seconds once it was inlined, the same time as writing the formula by hand. No code change is needed. Raising the compatibility level is the switch. ## Why one report did not speed up Inlining is decided **per function and per query**. Both the function definition and the calling context must qualify. Common reasons a **definition** is ineligible: - It calls a **time-dependent** intrinsic function such as `GETDATE()`, or one with side effects such as `NEWSEQUENTIALID()`. - It references **table variables** or table-valued parameters, user-defined types or CTEs. - It has **more than one `RETURN`** statement (a restriction since SQL Server 2019 CU5). - It uses `EXECUTE AS` with anything other than `CALLER`, or it is natively compiled. - It accumulates in a `SELECT`, such as `SELECT @v += col FROM t`, or uses `ORDER BY` without `TOP 1`. - It references `@@ROWCOUNT`, `STRING_AGG`, remote tables or encrypted columns. Common reasons a **calling query** blocks it: - The function is used in the query's `ORDER BY`, or the query groups by a UDF call. - The calling query uses a CTE, or `GROUPING SETS`, `CUBE` or `ROLLUP`. - The function sits in a **computed column** or a `CHECK` constraint. Several of these restrictions arrived in 2019 cumulative updates (CU2 through CU11), so a function inlined on an early 2019 build may not be inlined on a later one. ## How to check 1. **Definition eligibility.** Query `sys.sql_modules.is_inlineable`. `1` means the definition uses only inlineable constructs, and `0` means it does not. The value is derived from the definition only. It does **not** promise that a given query will inline the function. It is also `1` for every inline table-valued function. 2. **What actually happened.** Capture the actual plan. If the function was inlined, the plan XML has **no `<UserDefinedFunction>` node** for it. Inlining also emits Extended Events. 3. **Configuration.** Confirm the database's compatibility level and that `TSQL_SCALAR_UDF_INLINING` is not set to `OFF` in `sys.database_scoped_configurations`. ## Fixes and controls The common fix for the time-dependent case is to **pass "now" in as a parameter**. The caller evaluates `GETDATE()` once, and the function no longer calls a time-dependent built-in. Folding several `RETURN` branches into one `RETURN` with a `CASE` expression fixes the multiple-return case. Functions doing real set work are often better rewritten as inline table-valued functions. Controls exist at three scopes: | Scope | Off | On | |---|---|---| | Database | `ALTER DATABASE SCOPED CONFIGURATION SET TSQL_SCALAR_UDF_INLINING = OFF` | `... = ON` | | One query | `OPTION (USE HINT('DISABLE_TSQL_SCALAR_UDF_INLINING'))` | omit the hint | | One function | `CREATE OR ALTER FUNCTION ... WITH INLINE = OFF` | `WITH INLINE = ON` | The query hint takes precedence over the database setting. Specifying `INLINE = ON` on an ineligible function **raises an error**, which makes it a useful assertion in deployment scripts. ## Behaviour changes to expect after inlining - The **query hash changes** for the same text, which matters if you track queries by hash. - Warnings hidden inside the function, such as divide by zero, can now surface. - Query-level join hints may stop being valid because inlining adds joins. - A view that references an inlined UDF cannot be indexed unless inlining is disabled for that function. - Functions that read `SCOPE_IDENTITY()` or `@@ERROR` can return different values because the scope changed. A function that stays slow after the upgrade is usually ineligible, not broken. Find the blocking construct, and the decision is between rewriting it and leaving that function on the old path.

  • In SQL Server, how do you assert at deployment time that a scalar UDF will be inlineable?
    Create it with `WITH INLINE = ON`. If the definition is ineligible, `CREATE FUNCTION` or `ALTER FUNCTION` raises an error rather than silently creating a function that runs per row. Without the clause, SQL Server sets the option automatically based on eligibility. A query can still decline to inline an eligible function, so check plans for hot queries too.
  • What can change in results or monitoring after SQL Server starts inlining a scalar UDF?
    The query hash changes for the same text. Warnings such as divide by zero inside the function can start appearing. Functions that read `SCOPE_IDENTITY()`, `@@ROWCOUNT` or `@@ERROR` can return different values because inlining changes statement scope, which is why newer builds block inlining when `@@ROWCOUNT` is referenced. Query-level join hints may also become invalid.

  • is_inlineable = 1 guarantees every query inlines the function
  • Scalar UDF inlining needs each function rewritten before it applies
  • Turning off TSQL_SCALAR_UDF_INLINING affects only one function
  • A scalar UDF that calls GETDATE() is inlined like any other
  • A non-inlined scalar UDF still allows a parallel plan

Assumes SQL Server 2025; scalar UDF inlining was introduced in SQL Server 2019 at compatibility level 150, and its eligibility rules tightened in 2019 cumulative updates CU2 to CU11.