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 Trim function demonstration, 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 the TRIM function.

-- SQL Server TRIM 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 are using Trim function to remove special characters from a string.

-- SQL Server TRIM Function
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 Server String Trim 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 TRIM, or RTRIM or LTRIM to trim those extra spaces.

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