SQL Server TRIM Function


By:

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.

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

Related Articles






Comments For This Article




Monday, November 15, 2021 - 9:28:01 AM - Greg Robidoux Back To Top (89447)
Hi Shair, we will update these based on your recommendation.

Thanks
Greg

Friday, November 12, 2021 - 1:39:50 PM - Shair Back To Top (89443)
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.














get free sql tips
agree to terms