SQL Server TRIM() Function

The TRIM() function in SQL Server removes leading and trailing spaces (or other specified characters) from a string. This is a very common and useful function for data cleaning and ensuring data consistency.



TRIM(): Definition and Usage

Extra whitespace at the beginning or end of a string can interfere with comparisons and other operations. TRIM() efficiently removes both leading and trailing spaces by default, but you can also specify other characters to remove.

Syntax

Syntax

TRIM([characters FROM] string)
      

The characters part is optional. If omitted, only leading and trailing spaces are removed. Otherwise, it specifies the characters to be removed from both ends of the string.

Parameter Values

Parameter Description
characters (Optional) The characters to remove from the beginning and end of the string. If omitted, only spaces are removed.
string The input string. This is required.

Related Functions

For removing only leading or trailing spaces, see the LTRIM() and RTRIM() functions.

Examples

Removing Leading and Trailing Spaces

This example removes spaces from the beginning and end of a string.

Syntax

SELECT TRIM('    SQL Tutorial!    ') AS TrimmedString;
      
Output

SQL Tutorial!
      

Removing Specific Characters

This example removes leading and trailing spaces and the characters '#' and '!'.

Syntax

SELECT TRIM('#! ' FROM '    #!SQL Tutorial!    ') AS TrimmedString;
      
Output

SQL Tutorial