SQL TRIM Function Use and Examples

Overview

The TRIM function is used to remove trailing and leading spaces (char(32)) from a string of characters. This was introduced with SQL Server 2017.

Explanation

Syntax

TRIM(expression)

Parameters

  • expression – the string to remove leading and trailing spaces.

Simple TRIM Example

The following example will TRIM the leading and trailing spaces.

SELECT TRIM('    What a   wonderful   world   ') as msg
simple TRIM example

TRIM Example Using Table Column

The following example shows how to remove trailing and leading spaces from a table column.

SELECT TRIM(AddressLine1) as addressline
FROM [Person].[Address]
Apply TRIM function to columns

Example with TRIM and CONCAT Functions

The following example shows how to use TRIM with CONCAT to trim leading and trailing spaces and then concatenate the values.

DECLARE @string1 varchar(30) = '  this is the first message   '
 
DECLARE @string2 varchar(30) = '  this is the second message  '
 
SELECT CONCAT(TRIM(@string1), ' ', TRIM(@string2)) as example
remove trailing leading spaces trim t-sql

Additional Information

2 Comments

  1. It would be nice to have the SQL version the function works in. I have SQL 2016 and saw *TRIM* – wow, I had missed it … but no, it works form 2017 forward. sigh. Thanks for the post though! Great information.

Leave a Reply

Your email address will not be published. Required fields are marked *