T-SQL Functions

Explore the power of Transact-SQL functions for data manipulation and retrieval.

Introduction to T-SQL Functions

What are T-SQL Functions?

T-SQL functions are pre-defined routines that perform a specific task, typically involving data. They accept input parameters, perform operations, and return a single value. Functions are crucial for manipulating data, performing calculations, and enhancing the readability and reusability of your SQL code.

Types of T-SQL Functions

Scalar Functions

Scalar functions return a single value for each row processed. These are the most common type of function.

Example Function: GETDATE()

GETDATE()

Description

Returns the current database system date and time.

Usage Example

SELECT GETDATE() AS CurrentDateTime;

Aggregate Functions

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

Example Function: COUNT()

COUNT(expression)

Description

Returns the number of rows that match a specified criterion.

Usage Example

SELECT COUNT(*) AS NumberOfOrders FROM Orders;

Table-Valued Functions (TVFs)

Table-valued functions return a table as their result set. They can be used in the FROM clause of a query.

Example Function: dbo.GetEmployeeByDepartment()

CREATE FUNCTION dbo.GetEmployeeByDepartment (@DepartmentID INT)
RETURNS TABLE
AS
RETURN
(
    SELECT EmployeeID, FirstName, LastName
    FROM Employees
    WHERE DepartmentID = @DepartmentID
);

Description

Returns a list of employees belonging to a specific department.

Usage Example

SELECT EmployeeID, FirstName, LastName
FROM dbo.GetEmployeeByDepartment(3);

Commonly Used T-SQL Functions

Numeric Functions

System Functions

Function Details

LEN()

Syntax

LEN(string_expression)

Description

Returns the number of characters in a string expression, excluding trailing blanks.

Example

SELECT LEN('SQL Functions') AS StringLength;
-- Result: 13

LEFT()

Syntax

LEFT(character_expression, number_of_characters)

Description

Returns the left part of a character string with the specified number of characters.

Example

SELECT LEFT('Transact-SQL', 8) AS LeftPart;
-- Result: Transact

SUBSTRING()

Syntax

SUBSTRING(expression, start, length)

Description

Returns a part of a character, binary, text or image expression. Starts at the specified position and returns the specified number of characters.

Example

SELECT SUBSTRING('SQL Server Functions', 5, 6) AS MiddlePart;
-- Result: Server

UPPER()

Syntax

UPPER(character_expression)

Description

Converts a character expression to uppercase.

Example

SELECT UPPER('mixedCaseString') AS UppercaseString;
-- Result: MIXEDCASESTRING

LOWER()

Syntax

LOWER(character_expression)

Description

Converts a character expression to lowercase.

Example

SELECT LOWER('MixedCaseString') AS LowercaseString;
-- Result: mixedcasestring

REPLACE()

Syntax

REPLACE(string_expression, string_to_replace, replacement_string)

Description

Returns the character string where all occurrences of a specified string are replaced with another specified string.

Example

SELECT REPLACE('Hello World', 'World', 'SQL') AS ReplacedString;
-- Result: Hello SQL

TRIM()

Syntax

TRIM( [ [ LEADING | TRAILING | BOTH ] [ characters FROM ] ] string_expression )

Description

Removes leading and/or trailing spaces or specified characters from a string.

Example

SELECT TRIM('   Spaces   ') AS TrimmedString;
-- Result: Spaces

ABS()

Syntax

ABS(numeric_expression)

Description

Returns the absolute value of a numeric expression.

Example

SELECT ABS(-100.5) AS AbsoluteValue;
-- Result: 100.5

ROUND()

Syntax

ROUND(numeric_expression, length [, function])

Description

Returns a numeric value, rounded to the specified number of decimal places.

Example

SELECT ROUND(123.4567, 2) AS RoundedValue;
-- Result: 123.46

CEILING()

Syntax

CEILING(numeric_expression)

Description

Returns the smallest integer greater than or equal to the specified numeric expression.

Example

SELECT CEILING(10.2) AS CeilingValue;
-- Result: 11

FLOOR()

Syntax

FLOOR(numeric_expression)

Description

Returns the largest integer less than or equal to the specified numeric expression.

Example

SELECT FLOOR(10.8) AS FloorValue;
-- Result: 10

POWER()

Syntax

POWER(numeric_expression, exponent)

Description

Returns the value of a numeric expression raised to the specified power.

Example

SELECT POWER(2, 5) AS PowerResult;
-- Result: 32

GETDATE()

Syntax

GETDATE()

Description

Returns the current database system date and time as a datetime value.

Example

SELECT GETDATE() AS CurrentDateTime;

DATEPART()

Syntax

DATEPART(datepart, date)

Description

Returns an integer representing the specified part of a specified date.

Example

SELECT DATEPART(year, '2023-10-27') AS YearPart;
-- Result: 2023

DATENAME()

Syntax

DATENAME(datepart, date)

Description

Returns a character string representing the specified part of a specified date.

Example

SELECT DATENAME(weekday, '2023-10-27') AS DayName;
-- Result: Friday

DATEDIFF()

Syntax

DATEDIFF(datepart, startdate, enddate)

Description

Returns the difference between two dates, in the specified datepart.

Example

SELECT DATEDIFF(day, '2023-10-20', '2023-10-27') AS DaysDifference;
-- Result: 7

DATEADD()

Syntax

DATEADD(datepart, number, date)

Description

Returns a specific date with a specified interval added to it.

Example

SELECT DATEADD(week, 1, '2023-10-27') AS DateAfterOneWeek;
-- Result: 2023-11-03

USER_NAME()

Syntax

USER_NAME([user_id])

Description

Returns the name of the database user associated with the specified user ID.

Example

SELECT USER_NAME() AS CurrentUserName;

DB_NAME()

Syntax

DB_NAME([database_id])

Description

Returns the name of the specified database.

Example

SELECT DB_NAME() AS CurrentDatabaseName;

HOST_NAME()

Syntax

HOST_NAME()

Description

Returns the network computer name of the client that is connected to SQL Server.

Example

SELECT HOST_NAME() AS ClientHostName;