SQL Server RTRIM Function

Summary: in this tutorial, you will learn how to use the SQL Server RTRIM() function to truncate all trailing blanks from a string.

SQL Server RTRIM() function overview

The RTRIM() function returns a string after truncating all trailing blanks. The following is the syntax of the RTRIM() function:

RTRIM(input_string)
Code language: SQL (Structured Query Language) (sql)

In this syntax, the input_string is an expression of character or binary data. It can be a literal string, variable, or column.

The input_string must evaluate to a value of a data type, except for TEXT, NTEXT and IMAGE, that can be implicitly convertible to VARCHAR. Otherwise, you must use the CAST() function to convert it to a character string explicitly.

SQL Server RTRIM() function examples

Let’s take some examples of using the RTRIM() function.

A) Using RTRIM() function with literal strings

This example uses the RTRIM() function to truncate trailing blanks of the string 'SQL Server RTRIM function ':

SELECT 
    RTRIM('SQL Server RTRIM Function   ') result;
Code language: SQL (Structured Query Language) (sql)

Here is the output:

result
----------------------------
SQL Server RTRIM Function

(1 row affected)

B) Using RTRIM() function to clean up blanks in tables

Suppose you want to remove trailing blanks in one or more column of a table. To do this, to do this you can use the following UPDATE statement:

UPDATE 
    table_name
SET 
    column_name = RTRIM(column_name);
Code language: SQL (Structured Query Language) (sql)

For example, to remove all trailing blanks of the values in the first_name column in the sales.customers table, you use the following statement:

UPDATE 
    sales.customers
SET 
    first_name = RTRIM(first_name);
Code language: SQL (Structured Query Language) (sql)

In this tutorial, you have learned how to use the SQL Server RTRIM() function to remove the trailing blanks from a string.

Was this tutorial helpful?