PostgreSQL – RTRIM Function

The rtrim function is used to remove characters from the right end (beginning) of a string. It takes two arguments: the input string and a list of characters to be removed from the right side of the input string.

Here’s the syntax for the rtrim function:
rtrim(input_string, characters_to_remove)
where
  • input_string is the string from which you want to remove characters from the right side.
  • characters_to_remove(optional) is a string containing the characters you want to remove from the right side of the input string. If you do not provide a string, rtrim function will remove the nulls from the right side.
The rtrim function will return a new string with all trailing characters from the characters_to_remove list removed from the right side of the input string.

Here’s an example of using the rtrim function:

SELECT rtrim(‘Hello, world!’, ‘!’);

In this example, the rtrim function is used to remove ‘!’ from the right side of the string 'Hello, world!'. The result of this query will be 'Hello, world' because it removed the trailing ‘!’.

You can use any list of characters in the characters_to_remove argument, and rtrim will remove all occurrences of those characters from the right side of the input string until it encounters a character that is not in the list.

RTRIM function can be used to remove the leading null characters as below:

SELECT rtrim('Hello, world!   ', ' '); -- removes trailing nulls   

or

SELECT rtrim('Hello, world!   '); -- removes trailing nulls

Similar Posts