How to Trim Strings in PostgreSQL
The trim() function removes specified characters or spaces from a string. You can specify to trim from only the start or end of the string, or trim from both. This is best explained using examples.
You can trim "1" from start of the string:
select trim(leading '1' from '111hello111');
ltrim
----------
hello111You can trim "1" from the end of the string:
select trim(trailing '1' from '111hello111211');
rtrim
--------------
111hello1112Note: the 1's before the 2 were not trimmed, as they are not the end of the string.
You can specify multiple characters to trim. PostgreSQL will remove any combination of those characters in succession:
select trim(both 'abc' from 'abcbabccchellocbaabc');
btrim
-------
helloPostgreSQL also supports the non-standard syntax of specifying which characters to remove as the last parameter, separated by a comma:
select trim(both 'abcbabccchellocbaabc','abc');
btrim
-------
helloNot specifying where to trim from has the same result as "both":
select trim('1' from '111hello111');
btrim
-------
helloNot specifying what character to trim will result in trimming spaces:
select trim(' remove spaces from both sides ');
btrim
-------------------------------
remove spaces from both sidesrtrim() and ltrim() are special versions that only remove trailing and leading characters, respectively. These functions only accept parameters separated by commas:
select ltrim('zzzyclean this up', 'xyz');
ltrim
---------------
clean this upselect rtrim('again not specifying what to trim removes spaces ');
rtrim
--------------------------------------------------
again not specifying what to trim removes spacesPrevious
How to Delete