How to Trim Strings

In order to trim spaces Postgres provides 3 main functions: trim which removes spaces from the start and the end of any string. The functions ltrim and rtrim allow to remove spaces only in the start(left) or the end(right) of the string.

select trim(‘ hello    ‘), ltrim(‘ hello    ‘), rtrim(‘ hello    ‘);
trim ltrim rtrim
"hello" "hello        " " hello"

However the trim function not only removes spaces, they can remove any character. Let’s take a look at an example to remove the character “-”.

select trim(‘-hello------’,’-’), ltrim(‘-hello------’,’-’),
 rtrim(‘-hello------’,’-’);
trim ltrim rtrim
“hello” “hello-----“ “-hello”

There is also a variation of the trim function called btrim (b from both) which works as a combination of ltrim and rtrim.

select btrim(‘-hello------’,’-’)
Btrim
“hello”

IN THIS PAGE