TRIM (Transact-SQL)
Applies to:
SQL Server 2017 (14.x) and later
Azure SQL Database
Azure SQL Managed Instance
Azure Synapse Analytics
Removes the space character char(32) or other specified characters from the start and end of a string.
Syntax
-- Syntax for SQL Server and Azure SQL Database
TRIM ( [ characters FROM ] string )
-- Syntax for Azure Synapse Analytics
TRIM ( string )
Note
To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
Arguments
characters
Is a literal, variable, or function call of any non-LOB character type (nvarchar, varchar, nchar, or char) containing characters that should be removed. nvarchar(max) and varchar(max) types aren't allowed.
string
Is an expression of any character type (nvarchar, varchar, nchar, or char) where characters should be removed.
Return Types
Returns a character expression with a type of string argument where the space character char(32) or other specified characters are removed from both sides. Returns NULL if input string is NULL.
Remarks
By default, the TRIM function removes the space character from both the beginning and the ending ends of the string. This behavior is equivalent to LTRIM(RTRIM(@string)).
Examples
A. Removes the space character from both sides of string
The following example removes spaces from before and after the word test.
SELECT TRIM( ' test ') AS Result;
Here is the result set.
test
B. Removes specified characters from both sides of string
The following example removes a trailing period and spaces from before # and after the word test.
SELECT TRIM( '.,! ' FROM ' # test .') AS Result;
Here is the result set.
# test