PostgreSQL trim() Function
The PostgreSQL trim()
function removes the longest string of specified characters from the start or/and end of the specified string.
trim()
Syntax
This is the syntax of the PostgreSQL trim()
function:
trim([ LEADING | TRAILING | BOTH ] [ characters ] FROM string)
or
trim([ LEADING | TRAILING | BOTH ] [ FROM ] string [, characters ])
Parameters
string
-
Required. The string to trim.
characters
-
Optional. The characters to remove. The default value is a space.
[ LEADING | TRAILING | BOTH ]
-
Optional. It indicates where to remove characters.
LEADING
means to remove characters from the start of the string.TRAILING
means to remove characters from the end of the string.BOTH
means to remove characters from start and end of the string. The default value isBOTH
.
Return value
The PostgreSQL trim()
function removes the longest string of specified characters from the start or/and end of the specified string.
trim()
Examples
Remove spaces
This example shows how to use trim()
to remove spaces from both ends of a string:
SELECT trim(BOTH FROM ' Hello ');
btrim
-------
Hello
This example shows how to use trim()
to remove whitespace from the start of a string:
SELECT trim(LEADING FROM ' Hello ');
ltrim
-----------
Hello
This example shows how to use trim()
to remove trailing spaces from a string:
SELECT trim(TRAILING FROM ' Hello ');
rtrim
-----------
Hello
Remove specified characters
This example shows how to remove consecutive specified characters from start and end of a string:
SELECT trim(BOTH '_#' FROM '_#_#_Hello_#_#');
btrim
-------
Hello
This example shows how to remove consecutive specified characters from the start of a string:
SELECT trim(LEADING '_#' FROM '_#_#_Hello_#_#');
ltrim
-----------
Hello_#_#
This example shows how to remove consecutive specified characters from the end of a string:
SELECT trim(TRAILING '_#' FROM '_#_#_Hello_#_#');
rtrim
------------
_#_#_Hello