July 2, 2021

The SQL RTRIM function trims all the trailing spaces from the right side of the input character expression.

Description

The RTRIM function returns a character expression after removing all the blank spaces from the right side.

SQL RTRIM Usage Notes

The only argument to the RTRIM function is the character expression that is to be truncated on the right side. The data type of this character expression should be implicitly convertible to a varchar value. It can be a constant or a variable with a character or a binary data type.

The return type of the RTRIM function is varchar or nvarchar.

Syntax 

RTRIM (input _expression)

SQL RTRIM Examples

The following example shows how to use the RTRIM function.

SELECT RTRIM('TRUNCATE BLANK SPACES ON THE RIGHT ') result;
/* Answer */
SELECT RTRIM('TRUNCATE BLANK SPACES ON THE RIGHT    ') result;

The above query removes all the blank spaces on the right side of the input expression.

The following query uses the AdventureWorks2019 database.

SELECT RTRIM(LastName) LastName FROM Person.Person
/* Answer */
SELECT RTRIM(LastName) LastName
FROM Person.Person

It removes the trailing blank spaces, if any, in the LastName column values.

If you’re hard pressed for why you would want to use this function consider this scenario:

The former DBA imported data “left justified” text into a CHAR(20) column names State. You now need to query this data, but being CHAR, the column still retain spaces to the right… ugh!

If you simply cast ‘TEXAS as VARCHAR the spaces continue to vex you!

To get around this you can write the following to retrieve all cities in Texas:

 SELECT City
 FROM City
 WHERE RTRIM(STATE) = 'TEXAS' 

See Also

About the author 

Kris Wenzel

Kris Wenzel has been working with databases over the past 30 years as a developer, analyst, and DBA. He has a BSE in Computer Engineering from the University of Michigan and a MBA from the University of Notre Dame. Kris has written hundreds of blog articles and many online courses. He loves helping others learn SQL.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Are YOU READY TO START LEARNING SQL SERVER, BUT DON'T KNOW WHERE TO START?

Nothing is worse than, being excited to learn a new tool but not knowing where to start, wasting time learning the wrong features, and being overwhelmed .

But it doesn't have to be this way.

I'm Putting together a free email course to help you get started learning SQL Server.

Name*
Email*
>