One of the most common string manipulation tasks in SQL is trimming or removing the whitespace characters from a given input string.
In this tutorial, we will learn about the RTRIM() function which plays a crucial role in string trimming.
SQL RTRIM()
In SQL, the RTRIM() function stands for right trim. The function allows us to remove any and/or trailing (rightmost) characters from a given string value.
This function is particularly useful when dealing with data that may contain unnecessary whitespace at the end of strings which allows us to cleanup the values from the database.
Syntax:
The syntax for the RTRIM() function in SQL may vary slightly depending on the database engine. In MySQL, the syntax is as follows:
The “string_to_trim” specifies the input string from which we wish to remove any leading whitespace characters.
SQL RTRIM() Example Usage (MySQL)
Let us look at some practical examples on how to use the RTRIM() function. We will start with a basic usage and then proceed to cover some more advanced examples.
Example 1: Sample Data
Before diving into the queries, consider an example table that contains the employee data as shown in the following:
Suppose we wish to retrieve the “job_title” from the table where the leading whitespace characters are removed. We can use the RTRIM() function as demonstrated in the following:
Output:
Example 2: Trimming Specific Characters
By default, the RTRIM() function removes the space characters from the input string. However, we can specify the specific characters that we wish to remove from the input string.
For example, to remove all occurrence of the tab character, we can use the “\t” value as shown in the following example:
This should remove all tab characters from the strings in the specified column.
NOTE: You can specify any supported character.
Conclusion
In this tutorial, we learned about the RTRIM() function in SQL to discover how to trim any occurrence of the specified characters from a given string.