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.
LEADINGmeans to remove characters from the start of the string.TRAILINGmeans to remove characters from the end of the string.BOTHmeans 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
-------
HelloThis example shows how to use trim() to remove whitespace from the start of a string:
SELECT trim(LEADING FROM ' Hello ');
ltrim
-----------
HelloThis example shows how to use trim() to remove trailing spaces from a string:
SELECT trim(TRAILING FROM ' Hello ');
rtrim
-----------
HelloRemove specified characters
This example shows how to remove consecutive specified characters from start and end of a string:
SELECT trim(BOTH '_#' FROM '_#_#_Hello_#_#');
btrim
-------
HelloThis 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