SQL TRIM Function

The SQL Trim function is used to remove empty spaces or special characters from both the left side and Right side of a string expression. The syntax of the SQL Server Trim Function

SELECT TRIM (Character_Expression)
FROM [Source]

SELECT TRIM ('Special_Characters' FROM Character_Expression)
FROM [Source]

Character_Expression: Please specify a valid Expression on which you want to remove empty spaces, or special char caters from the left and right side.

For this SQL Trim function demonstration to remove specified characters, we use the below-shown data.

SQL TRIM Function 0

SQL TRIM Function Example 1

The String TRIM Function removes space or any special character from the left and right side of a string. The following query will show multiple ways to use this string function.

DECLARE @str VARCHAR(50)
SET @str = '            Tutorial Gateway'

SELECT TRIM(@str) AS Result1;

SELECT TRIM('     Welcome to SQL           ') AS Result2;  

SELECT TRIM('      We Provide SQL Server Tutorials at Tutorial Gateway        ') AS Result3;
SQL TRIM Function 1

String TRIM Function Example 2

In this String Function example, we apply Trim function to remove special characters on both sides of a string.

DECLARE @str VARCHAR(50)
SET @str = '* Tutorial Gateway'

SELECT TRIM('*' FROM @str) AS Result1;

SELECT TRIM('# *' FROM '####     Welcome to SQL    ** ') AS Result2;  

SELECT TRIM('@ #' FROM ' @@@###$     We Provide SQL Tutorials at Tutorial Gateway  [email protected]@##      ') AS Result3;
SQL TRIM Function 2

String TRIM Function Example 3

This example will show you, How we are going to use the SQL Trim String on Column Names.

In general, we may get SQL Server data with some extra spaces due to typing mistake, or any other data entry issues. If this is the case, then you can use this function, or RTRIM or LTRIM to remove those extra leading and trailing spaces.

SELECT TRIM([FirstName]) + ' ' + TRIM([LastName]) AS FullName
      ,[Education]
      ,[Occupation]
      ,[YearlyIncome]
	  ,Sales
	  ,HireDate
 FROM [Employee]
SQL TRIM Function 3