How to Remove Trailing Whitespace in SQL Server

In SQL Server, we can use the RTRIM() function to remove trailing blanks from a given string. Trailing blanks are white spaces, tabs, etc that come at the end of the string.

Example

Here’s a basic example:

SELECT RTRIM('Cat ');

Result:

---
Cat

To make the effect more apparent, here’s an example of a trimmed string and an untrimmed string side-by-side. This example also includes multiple leading whitespaces – all of which are removed.

SELECT 
    'Cat       ' AS 'A', 
    RTRIM('Cat       ') AS 'B';

Result:

A           B  
----------  ---
Cat         Cat   

It’s important to note that it’s only trailing whitespace that’s trimmed when using this syntax. If there’s another character after the whitespace, the function will have no effect:

SELECT RTRIM('Cat       Food');

Result:

Cat       Food

However, as from SQL Server 2022, we can include a second argument to specify which characters to trim.

In our case, we can do this:

SELECT RTRIM('Cat       Food', ' Food');

Result:

Cat

However, when we do this, we need to include the space as one of the characters to trim. Omitting this will trim the specified characters, while leaving any whitespace intact:

SELECT 
  RTRIM('Cat       Food', ' Food') + 'Z' AS 'r1',
  RTRIM('Cat       Food', 'Food') + 'Z' AS 'r2';

Result:

r1              r2             
--------------- ---------------
CatZ            Cat       Z     

Similar Functions

You can also use LTRIM() to remove leading whitespace (and specified characters), and TRIM() to remove spaces (or other characters) from both sides of the string.