Summary: in this tutorial, you will learn how to use the RTRIM()
function to remove all trailing spaces of a string.
MySQL RTRIM() function overview
The RTRIM()
function takes a string argument and returns a new string with all the trailing space characters removed.
Here is the syntax of the RTRIM()
function:
RTRIM(str)
Code language: SQL (Structured Query Language) (sql)
In this syntax, the str
argument is the string that you want to remove the trailing spaces.
If the str is NULL, the function returns NULL.
In practice, you use the RTRIM()
function for cleaning and formatting text data by removing the trailing spaces.
Note that to remove the leading spaces from a string, you use the LTRIM()
function. To remove both leading and trailing spaces from a string, you use the TRIM()
function.
MySQL RTRIM() function examples
Let’s take some examples of using the RTRIM()
function.
1) Using RTRIM() function with a literal string
This example uses the RTRIM()
function to remove all trailing spaces of the string 'MySQL '
:
SELECT
RTRIM('MySQL ') result;
Code language: SQL (Structured Query Language) (sql)
Here is the result:
+--------+
| result |
+--------+
| MySQL |
+--------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)
In this example, the RTRIM()
function removes all the trailing spaces of the string 'MySQL '
. Therefore, the result is the string 'MySQL'
.
2) Using MySQL RTRIM() function to update data in a table
We’ll use the customers
table from the from the sample database:
The following example uses the RTRIM()
function in the UPDATE statement to remove all trailing spaces of customer names in the customerName
column of the customers
table:
UPDATE
customers
SET
customerName = RTRIM(customerName);
Code language: SQL (Structured Query Language) (sql)
Summary
- Use the
RTRIM()
function to remove all trailing spaces of a string.