PostgreSQL – TRIM Function

The TRIM() function is used to remove specified characters or whitespace from the beginning and/or end of a string. It’s often used to clean up or manipulate strings by removing unwanted leading or trailing characters.

The syntax of the TRIM() function is as follows:

TRIM([ [ BOTH | LEADING | TRAILING ] trim_character FROM ] string )

  • BOTH, LEADING, or TRAILING: These are optional keywords that specify the direction from which to trim characters. If omitted, the default is BOTH. BOTH trims characters from both the beginning and end of the string, LEADING trims characters only from the beginning, and TRAILING trims characters only from the end.
  • trim_character: An optional parameter that specifies the character or characters to be trimmed from the string. If omitted, the function trims whitespace characters (spaces, tabs, etc.).
  • string: The input string from which characters will be trimmed.

Here are some examples of how to use the TRIM() function in PostgreSQL:

  1. Removing leading and trailing spaces from a string:

SELECT TRIM(' Hello, World! ') AS trimmed_string;

This would result in the output: "Hello, World!"

  1. Trimming specific characters from both ends of a string:

SELECT TRIM('-' FROM '--12345---') AS trimmed_string;

This would result in the output: "12345"

  1. Trimming specific characters only from the beginning of a string:

SELECT TRIM(LEADING '0' FROM '00012345') AS trimmed_string;

This would result in the output: "12345"

  1. Trimming specific characters only from the end of a string:

SELECT TRIM(TRAILING '.' FROM '12.34.56.') AS trimmed_string;

This would result in the output: "12.34.56"

Similar Posts