PostgreSQL rtrim() Function

The PostgreSQL rtrim() function removes the longest string containing only characters specified by the argument (whitespace by default) from end of a string.

You can also use ltrim() to remove specified characters from start of a string, or btrim() to remove specified characters from both ends of a string.

rtrim() Syntax

This is the syntax of the PostgreSQL rtrim() function:

rtrim(text)

or

rtrim(text, characters)

Parameters

text

Required. The string to remove characters.

characters

Optional. The string containing the characters to remove. The default is a space.

Return value

The PostgreSQL rtrim() function removes the longest string containing all the characters specified by the argument (a space by default) from the right side of a character, and returns the character-removed string.

rtrim() Examples

SELECT
    length(rtrim('a  ')) AS "length(rtrim('a  '))",
    length(rtrim('  a')) AS "length(rtrim('  a'))",
    length(rtrim(' a ')) AS "length(rtrim(' a '))";
 length(rtrim('a  ')) | length(rtrim('  a')) | length(rtrim(' a '))
----------------------+----------------------+----------------------
                    1 |                    3 |                    2

Here:

  • We only used one parameter, then rtrim() will remove spaces from end of the string.
  • To make the result look more intuitive, we use length() function to display length of the returned string.

Let’s use rtrim() to remove specified characters from end of a string:

SELECT rtrim('xxyHELLOzxy', 'xyz') AS "rtrim('xxyHELLOzxy', 'xyz')";
 rtrim('xxyHELLOzxy', 'xyz')
-----------------------------
 xxyHELLO