Scalar functions look innocent…
…until your query goes from 50 ms → 12 seconds.
-- ❌ Never do this inside SELECT SELECT Id, dbo.GetUserScore(Id) FROM Users;
💥 Why They’re Slow
-
⛓ Executed row-by-row
-
🚫 Breaks parallelism
-
📉 Kills execution plans
-
🐌 Turns queries into RBAR (“Row By Agonizing Row”)
✔ The Fix
Use Inline Table-Valued Functions instead:
CREATE FUNCTION dbo.GetUserScore(@id INT) RETURNS TABLE AS RETURN (SELECT Score FROM Scores WHERE UserId = @id);
💡 Bonus
Scalar UDF Inlining in SQL 2019 helps — but don’t rely on magic.
