The RTRIM function in Oracle is a powerful tool for cleaning data. It "Right Trims" a string, meaning it removes all specified characters from the end (or right side) of the string.
This is the opposite of LTRIM, which removes characters from the left. RTRIM is most commonly used to clean up trailing spaces or other unwanted characters from data.
What is the RTRIM Function in Oracle?
RTRIM (Right-Trim) scans a string from right to left and removes any characters that match a specified set. It stops removing characters as soon as it finds one that is not in the set.
This is useful for:
- Removing trailing spaces from user input (e.g.,
'John Doe '). - Cleaning up data that has trailing punctuation (e.g.,
'SKU-123,'). - Standardizing data by removing unwanted trailing characters.
RTRIM Function Syntax
The syntax for RTRIM is simple:
RTRIM(char, [set])
Let's break that down:
char: The original string or column you want to trim (e.g.,'Hello World ').[set](Optional): The string of characters you want to remove.- If you omit this,
RTRIMdefaults to removing a single space' '. - The order of characters in the
setdoesn't matter.RTRIM('abcxzy', 'xyz')will return'abc'.
- If you omit this,
Oracle RTRIM Function Examples
Here are two practical examples of how to use RTRIM.
Example 1: Removing Trailing Spaces (Default) using RTRIM
This is the most common use for RTRIM. Imagine a user entered their name with extra spaces at the end.
Query:
SELECT
'[' || RTRIM('John Smith ') || ']' AS "Trimmed Name"
FROM DUAL;
(We use brackets [] just to show that the spaces are truly gone.)
Result:
Trimmed Name -------------- [John Smith]
Example 2: Removing a Specific Set of Characters with RTRIM
Let's say you have a list of part numbers that sometimes have trailing commas, periods, or dashes that you need to remove.
Query:
SELECT
RTRIM('PART-ABC-123,.-,', ',-.') AS "Cleaned Part"
FROM DUAL;
Note: RTRIM will remove any combination of ,, -, and . from the end until it hits a character not in that set (the 3).
Result:
Cleaned Part ------------ PART-ABC-123
