By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
User-defined functions (UDFs) in SQL allow you to encapsulate reusable logic, enhancing code maintainability and performance. They come in two primary types: scalar functions and table-valued functions. Understanding the distinction is crucial for database optimization and performance tuning. Incorrect usage can lead to inefficient queries, slowing down applications and frustrating end-users. For example, using a scalar function in a WHERE clause can cause row-by-row processing, significantly degrading performance.
sql CREATE FUNCTION dbo.GetStringLength (@input NVARCHAR(100)) RETURNS INT AS BEGIN RETURN LEN(@input) END
⚠️ Pitfall: Avoid complex logic that can be handled by built-in functions.
Define an Inline Table-Valued Function
sql CREATE FUNCTION dbo.SplitString (@input NVARCHAR(100), @delimiter CHAR(1)) RETURNS TABLE AS RETURN ( SELECT value FROM STRING_SPLIT(@input, @delimiter) )
⚠️ Pitfall: Incorrect delimiter can lead to unexpected results.
Define a Multi-Statement Table-Valued Function
sql CREATE FUNCTION dbo.GenerateDateRange (@startDate DATE, @endDate DATE) RETURNS @DateTable TABLE (DateValue DATE) AS BEGIN DECLARE @currentDate DATE = @startDate WHILE @currentDate <= @endDate BEGIN INSERT INTO @DateTable (DateValue) VALUES (@currentDate) SET @currentDate = DATEADD(DAY, 1, @currentDate) END RETURN END
⚠️ Pitfall: Loops can be inefficient; consider set-based operations.
Using Functions in Queries
sql SELECT dbo.GetStringLength(Name) AS NameLength FROM Employees
⚠️ Pitfall: Scalar functions in WHERE clauses can degrade performance.
Optimizing with Table-Valued Functions
sql SELECT e.Name, d.DateValue FROM Employees e CROSS APPLY dbo.GenerateDateRange(e.HireDate, GETDATE()) d
Experts view user-defined functions as tools for modularizing and optimizing SQL code. They focus on the performance implications of each function type, favoring inline table-valued functions for their efficiency and avoiding scalar functions in critical performance paths.
Exam trap: Questions involving performance tuning.
The mistake: Overusing multi-statement table-valued functions.
Exam trap: Scenarios requiring efficient data retrieval.
The mistake: Ignoring deterministic properties.
Exam trap: Questions on query optimization.
The mistake: Complex logic in scalar functions.
Scenario: You need to calculate the age of employees from their birthdates.Question: Write a scalar function to calculate age.Solution:
CREATE FUNCTION dbo.CalculateAge (@birthdate DATE) RETURNS INT AS BEGIN RETURN DATEDIFF(YEAR, @birthdate, GETDATE()) - CASE WHEN DATEADD(YEAR, DATEDIFF(YEAR, @birthdate, GETDATE()), @birthdate) > GETDATE() THEN 1 ELSE 0 END END
Answer: The function calculates the age based on the birthdate.Why it works: Uses date functions to accurately determine the age.
Scenario: You need to split a comma-separated string into individual values.Question: Write an inline table-valued function to split the string.Solution:
CREATE FUNCTION dbo.SplitString (@input NVARCHAR(100), @delimiter CHAR(1)) RETURNS TABLE AS RETURN ( SELECT value FROM STRING_SPLIT(@input, @delimiter) )
Answer: The function splits the string into a table of values.Why it works: Utilizes the built-in STRING_SPLIT function for efficiency.
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.