The SQL RTRIM function trims all the trailing spaces from the right side of the input character expression.
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.
RTRIM (input _expression)
SQL RTRIM Examples
The following example shows how to use the RTRIM function.
/* 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.
/* 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'