PostgreSQL btrim() Function

The PostgreSQL btrim() function removes the longest string containing only characters specified by the argument from the start and end of the given string.

You can also use ltrim() to remove specified characters from the start of a string, or user rtrim() to remove from the end of a string.

btrim() Syntax

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

btrim(text)

or

btrim(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 btrim() function removes the longest string containing only characters specified by the argument (one space by default) from the start and end of a character, and returns the string.

btrim() Examples

SELECT
    length(btrim('a  ')) AS "length(btrim('a  '))",
    length(btrim('  a')) AS "length(btrim('  a'))",
    length(btrim(' a ')) AS "length(btrim(' a '))";
 length(btrim('a  ')) | length(btrim('  a')) | length(btrim(' a '))
----------------------+----------------------+----------------------
                    1 |                    1 |                    1

Here,

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

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

SELECT
    btrim('xxyHELLOzxy', 'xyz') AS "'xxyHELLOzxy'";
 'xxyHELLOzxy'
---------------
 HELLO