Lesson 2 of 3 Views and User-Defined Functions

Scalar User-Defined Functions and Inlining

This lesson explains scalar user-defined functions, their restrictions and how scalar UDF inlining changed their performance.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe what scalar functions can and cannot do.
  • Explain scalar UDF inlining and how to check eligibility.
  • Identify when to replace a scalar function with an inline table-valued function.

Writing a scalar function

A scalar UDF declares parameters and a return type and contains a BEGIN...END body that ends with RETURN. Functions can read data but cannot change database state, call non-deterministic built-ins that have side effects, use TRY...CATCH or execute dynamic SQL.

CREATE OR ALTER FUNCTION Sales.fnNetPrice (@ListPrice decimal(10,2), @DiscountPct decimal(5,2))
RETURNS decimal(10,2)
WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
AS
BEGIN
    RETURN ROUND(@ListPrice * (1 - @DiscountPct / 100.0), 2);
END;

SCHEMABINDING lets the engine verify that a function that does not access data is deterministic and precise, which is required to use it in a persisted or indexed computed column. RETURNS NULL ON NULL INPUT returns NULL without running the body when any argument is NULL.

True or false

Scalar UDF rules

Exam skills 1.2.2

Decide whether each statement about scalar functions is true.

Log in to try this activity Interactive activities are free with an account.

Scalar UDF inlining

Before SQL Server 2019, a scalar UDF in a query ran once per row in a separate context, could not be parallelized, and was invisible to the optimizer's cost model, which made such queries very slow. From compatibility level 150, scalar UDF inlining transforms eligible functions into relational expressions inside the calling query. sys.sql_modules.is_inlineable shows whether a function qualifies; functions that use certain constructs, such as table variables in some patterns, time-dependent functions or EXECUTE AS, are not inlined. Inlining can be disabled per function with WITH INLINE = OFF or per query with a hint.

Scenario questions

Inlining

Exam skills 1.2.2

Choose the explanation or fix for each inlining situation.

Log in to try this activity Interactive activities are free with an account.

When to use a scalar function

Scalar functions suit small, reusable calculations, such as formatting, unit conversion or a business rule used in many queries. A calculation that only one query uses is simpler as an expression, and logic that returns several values or rows belongs in a table-valued function. When a scalar function reads tables row by row and is not inlineable, rewriting it as an inline table-valued function used with CROSS APPLY often performs far better.

Worked example

A slow report

A report calls dbo.fnCustomerTier(CustomerID), which looks up the customer's total sales, for each of 2 million rows. The database runs at compatibility level 140 and the report takes ten minutes. What should the developer try first?

Raise the compatibility level to 150 or later (170 is current) and check sys.sql_modules.is_inlineable for the function. If it is inlineable, the optimizer folds it into the query as a join and aggregate instead of 2 million separate executions. If it is not, rewrite it as an inline table-valued function and use CROSS APPLY. Adding an index on CustomerID helps each lookup but leaves the row-by-row execution in place.

Check yourself

Which catalog column shows whether a scalar UDF can be inlined?

Show answer

sys.sql_modules.is_inlineable.

Exam Tips

Remember for the exam

  • Slow queries that call scalar UDFs: check is_inlineable and use compatibility level 150+.
  • Use a function in an indexed computed column: deterministic and schema-bound.
  • Functions cannot modify data or use TRY...CATCH.
  • Non-inlineable data-access UDF: rewrite as an inline TVF with CROSS APPLY.