The RTRIM() function in MySQL is used to remove trailing spaces (spaces at the end) from a string.
Syntax
RTRIM(string)
Parameters
| Parameter | Description |
|---|---|
string |
Required. The string from which trailing spaces will be removed. |
Definition and Usage
- The
RTRIM()function removes all spaces that appear at the end of a string. - It does not remove spaces that are located at the beginning or in the middle of the string.
Usage Examples
Example 1: Remove trailing spaces from a string
Remove trailing spaces from the string "SQL Tutorial ":
SELECT RTRIM("SQL Tutorial ") AS RightTrimmedString;
Output:
| RightTrimmedString |
|---|
| SQL Tutorial |
Explanation: The trailing spaces at the end of "SQL Tutorial " are removed, leaving "SQL Tutorial".
Example 2: Remove trailing spaces from a CustomerName column
Remove trailing spaces from the CustomerName column:
SELECT RTRIM(CustomerName) AS RightTrimmedCustomerName
FROM Customers;
Output (example results):
| RightTrimmedCustomerName |
|---|
| JohnDoe |
| AliceSmith |
| BobJohnson |
Explanation: Any trailing spaces from the CustomerName column entries are removed.
Technical Details
- Works In: From MySQL 4.0 onwards.
- Return Type: Returns a string with the same characters as the original string, but without the trailing spaces.
- Behavior:
- Only trailing spaces (spaces at the end) are removed.
- Does not affect leading spaces (spaces at the beginning) or spaces within the string.
Applications
- Cleaning Data: Use
RTRIM()to clean up data when you need to ensure there are no extra spaces at the end of string values. - Formatting Output: When displaying data or generating reports, you might need to ensure that all strings are trimmed from the right side for better formatting or consistency.
- Data Preprocessing: Before inserting data into a database or when comparing strings, you can use
RTRIM()to make sure trailing spaces do not affect the comparison or processing.
Key Notes
RTRIM()only removes trailing spaces. If you need to remove leading spaces, useLTRIM().- The function does not affect any spaces inside the string or at the beginning of the string.