SQL Functions in Relational Databases

Functions are database objects that contain programming statements to perform a specific task, such as complex calculations, data manipulation, or encapsulating business logic. In SQL Server, functions can return a single value (scalar functions) or a table (table-valued functions).

Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. They are often used with the GROUP BY clause.

Example: Calculate the average salary for each department.

SELECT department_id, AVG(salary) AS average_salary
FROM employees
GROUP BY department_id;

Scalar Functions

Scalar functions return a single data value. They can be used in queries, stored procedures, and other database objects.

Example: Get the current date and time.

SELECT GETDATE();

Note: The specific syntax for scalar functions may vary slightly between different SQL dialects (e.g., SQL Server, MySQL, PostgreSQL).

Table-Valued Functions

Table-valued functions (TVFs) return a table. They can be used in the FROM clause of a query, similar to a view, but they can also accept parameters.

Example: An inline TVF to get employees hired after a specific date.

CREATE FUNCTION dbo.GetEmployeesHiredAfter (@hireDate DATE)
RETURNS TABLE
AS
RETURN
(
    SELECT EmployeeID, FirstName, LastName, HireDate
    FROM Employees
    WHERE HireDate > @hireDate
);

Usage:

SELECT * FROM dbo.GetEmployeesHiredAfter('2022-01-01');

String Functions

String functions manipulate string data.

Example: Combine first and last names.

SELECT CONCAT(FirstName, ' ', LastName) AS FullName
FROM Employees;

Date and Time Functions

Date and time functions work with date and time values.

Example: Calculate the number of days between two dates.

SELECT DATEDIFF(day, '2023-01-01', '2023-03-15') AS DaysDifference;

Numeric Functions

Numeric functions perform mathematical operations.

Example: Get the ceiling of a division.

SELECT CEILING(10.5 / 2);

System Functions

System functions return information about the database environment or the current user.

Example: Get the current database name.

SELECT DB_NAME();

JSON Functions

JSON functions allow you to work with JSON data stored in SQL Server.

Example: Extract a name from a JSON string.

DECLARE @json NVARCHAR(100) = '{"name": "John Doe", "age": 30}';
SELECT JSON_VALUE(@json, '$.name');

XML Functions

XML functions allow you to work with XML data stored in SQL Server.

Example: Querying an XML column.

-- Assuming you have an XML column named 'ProductDescription' in a table 'Products'
SELECT
    T.c.value('ProductName[1]', 'VARCHAR(100)') AS ProductName,
    T.c.value('Color[1]', 'VARCHAR(50)') AS Color
FROM
    Products
CROSS APPLY
    ProductDescription.nodes('/Product/Details') AS T(c);

This overview covers common types of SQL functions. For detailed syntax and advanced usage specific to your SQL Server version, please refer to the official Microsoft documentation.