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