The SQL Trim function removes empty spaces or special characters from both the left side and Right side of a string expression, and the syntax is
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 sides.
To remove specified characters, we use the below-shown data for this Sql Server TRIM Function demonstration.
SQL TRIM Function Example
It removes space or any special character from a string’s left and right sides. The following query will show multiple ways to use this one.
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;
In this String example, we apply this method 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 $@@## ') AS Result3;
TRIM Function Example 3
This example will show how we will use the Trim String function on Column Names.
We may get SQL Server data with some extra spaces due to typing mistakes or other data entry issues. If this is the case, you can use this function or RTRIM or LTRIM to remove the extra leading and trailing spaces.
SELECT TRIM([FirstName]) + ' ' + TRIM([LastName]) AS FullName ,[Education] ,[Occupation] ,[YearlyIncome] ,Sales ,HireDate FROM [Employee]