T-SQL 101: #44 Trimming whitespace from strings in SQL Server

I often need to remove spaces from the front or back (or both) of strings. For a long time, the two functions we had for that were LTRIM (for left trim) and RTRIM (for right trim).  You can see them in the first two SELECT statements here:

For as long as I've used SQL Server though (also a long time), people have been asking for a TRIM function. Most developers were tired of endlessly writing LTRIM(RTRIM()) to do that. In SQL Server 2017 though, we did finally get a TRIM function. It trims both the left and right hand sides of a string.

Now while these functions are excellent and do what they need to, the thing that they don't do is remove other whitespace characters. If you need a function to do that, I'd suggest you look at our TrimWhitespace() function in our free SDU Tools for developers and DBAs. It removes all common whitespace characters including Unicode specific ones.

Learning T-SQL

It's worth your while becoming proficient in SQL. If you'd like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

3 thoughts on “T-SQL 101: #44 Trimming whitespace from strings in SQL Server”

Leave a Reply

Your email address will not be published.