Microsoft Learn

Documentation for SQL Server

TRIM (Transact-SQL)

Removes leading and trailing spaces or specified characters from a string and returns the resulting string.

Syntax

TRIM ( [ [ LEADING | TRAILING | BOTH ] [ character_string ] FROM ] source_string )

Parameters

Parameter Description
LEADING | TRAILING | BOTH Optional. Specifies whether leading, trailing, or both leading and trailing characters are removed. If not specified, BOTH is the default.
character_string Optional. A string literal, variable, or function return value that contains the characters to be removed from source_string. If not specified, spaces are removed. character_string can contain multiple characters.
source_string Required. The string from which characters will be removed. This can be a string literal, variable, or function return value.

Return Value

Returns a character string after specified characters have been removed from the beginning and/or end of the input string.

Remarks

The TRIM function supports Unicode characters.

If character_string is specified, it must be a string literal, variable, or function return value.

The TRIM function is the ANSI SQL standard function for removing characters.

Examples

Example 1: Removing leading and trailing spaces

SELECT TRIM('   Hello World   ');

Output:

Hello World

Example 2: Removing leading characters

SELECT TRIM( LEADING '*-' FROM '**Hello World**');

Output:

Hello World**

Example 3: Removing trailing characters

SELECT TRIM( TRAILING '.' FROM 'Hello World....');

Output:

Hello World

Example 4: Removing both leading and trailing characters

SELECT TRIM( BOTH '-=' FROM '=-Hello World-=');

Output:

Hello World

Example 5: Using with variables

DECLARE @MyString VARCHAR(50) = '  SQL TRIM Example  ';
SELECT TRIM(@MyString);

Output:

SQL TRIM Example