Skill 1.2.2

Create scalar functions

Key Concepts

A scalar UDF is created with CREATE FUNCTION ... RETURNS type AS BEGIN ... RETURN expression END. Historically, scalar UDFs ran once per row and prevented parallelism, which made queries slow. In compatibility level 150 and later, scalar UDF inlining rewrites eligible functions into the calling query as expressions, so they no longer run row by row; sys.sql_modules.is_inlineable shows whether a function qualifies.

Functions cannot change database state: they cannot run INSERT, UPDATE or DELETE on tables, call procedures that do, or use TRY...CATCH. Adding WITH SCHEMABINDING lets the engine treat a function that does not access data as deterministic and precise, which is required to use it in a persisted or indexed computed column. RETURNS NULL ON NULL INPUT skips execution when any argument is NULL.