Different Types of SQL Server Functions
Estimated study time: 16 minutes. A clear breakdown of every function type in SQL Server.
SQL Server functions let you reuse logic inside queries instead of repeating the same calculation everywhere. Broadly, they fall into four categories: scalar, aggregate, window, and table-valued functions.
1. Scalar Functions
Return a single value based on the input. Built-in examples include UPPER(), LEN(), and GETDATE().
SELECT UPPER(first_name), LEN(first_name) FROM employees;
2. Aggregate Functions
Operate on a set of rows and return one summary value — SUM(), AVG(), COUNT(), MIN(), MAX().
SELECT department, AVG(salary) FROM employees GROUP BY department;
3. Window Functions
Perform a calculation across a set of rows related to the current row, without collapsing them into one row — RANK(), ROW_NUMBER(), LAG(), LEAD().
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employees;
4. Table-Valued Functions
Return an entire table as their result, and can be queried just like a regular table.
CREATE FUNCTION dbo.GetEmployeesByDept(@dept VARCHAR(50)) RETURNS TABLE AS RETURN SELECT * FROM employees WHERE department = @dept;
Choosing the Right Function Type
- Use scalar functions for simple, per-row transformations
- Use aggregate functions for summarizing groups of data
- Use window functions when you need row-level detail alongside a group calculation
- Use table-valued functions to package reusable, parameterized queries
Writing a User-Defined Scalar Function
Built-in functions cover common needs, but you can create your own when the same calculation appears in many queries. A scalar user-defined function (UDF) takes parameters and returns a single value.
CREATE FUNCTION dbo.fnNetSalary (@gross DECIMAL(12,2), @taxPct DECIMAL(5,2))
RETURNS DECIMAL(12,2)
AS
BEGIN
RETURN @gross - (@gross * @taxPct / 100);
END;
GO
SELECT name, salary, dbo.fnNetSalary(salary, 10) AS net_salary
FROM employees;
User-defined functions must be called with their schema name, such as dbo.. Newer SQL Server versions can automatically inline some simple scalar UDFs, which reduces the old performance penalty, but the function must meet certain requirements, so check the execution plan rather than assuming.
Inline vs Multi-Statement Table-Valued Functions
Table-valued functions come in two flavours, and the difference matters for speed.
-- Multi-statement TVF: builds a table variable step by step
CREATE FUNCTION dbo.fnTopEarners (@minSalary INT)
RETURNS @result TABLE (name VARCHAR(100), salary INT)
AS
BEGIN
INSERT INTO @result
SELECT name, salary FROM employees WHERE salary >= @minSalary;
RETURN;
END;
GO
-- Using a TVF with CROSS APPLY, once per department row
SELECT d.dept_name, e.name
FROM departments d
CROSS APPLY dbo.GetEmployeesByDept(d.dept_name) AS e;
| Type | Body | Performance |
|---|---|---|
| Inline TVF | A single SELECT statement | Expanded into the calling query like a view, so the optimiser can use indexes and good estimates |
| Multi-statement TVF | Several statements filling a table variable | Treated more like a black box, which can lead to poor plans on large data |
Functions Compared with Stored Procedures
- Functions can be used inside
SELECT,WHEREandJOIN; stored procedures are run withEXEC. - Functions cannot change data in permanent tables or use most side effects; procedures can insert, update and delete.
- Functions must return a value or table; procedures may return result sets, output parameters or nothing.
- Error handling with
TRY...CATCHis available in procedures but not inside functions.
Rule of thumb: use a function to calculate or filter, and a procedure to perform an action.
Mistakes to Avoid
- Wrapping an indexed column in a function inside
WHERE, such asWHERE YEAR(order_date) = .... This blocks index seeks; compare against a date range instead. - Using
GETDATE()repeatedly inside a long batch and expecting it to stay identical; store it in a variable first. - Expecting window functions in a
WHEREclause; filter their results in an outer query or CTE. - Forgetting that this syntax is SQL Server (T-SQL); MySQL and PostgreSQL write functions differently.
Deterministic and Non-Deterministic Functions
SQL Server classifies functions by whether they always return the same result for the same input. UPPER() is deterministic, while GETDATE() and NEWID() are not. This matters because only deterministic expressions can be used in indexed views or persisted computed columns. When you write your own function, adding WITH SCHEMABINDING helps SQL Server confirm it is safe to use in those places.