PostgreSQL: TRIM, BTRIM, LTRIM, and RTRIM Functions

Updated: January 5, 2024 By: Guest Contributor Post a comment

Overview

PostgreSQL provides several functions to manipulate text strings, allowing you to tidy up data and make sure it conforms to a certain format. Among these string functions are the TRIM family of functions which includes TRIM, BTRIM, LTRIM, and RTRIM. These functions are incredibly useful for data cleaning and are commonly used in the data sanitization process.

History and Purpose

TRIM functions have been part of standard SQL for many years. PostgreSQL, being compliant with the SQL standard, has included these functions since its early versions. They serve the purpose of removing unwanted characters, most often whitespace, from the start, end, or both sides of a string.

Syntax and Parameters

  • TRIM: Removes the longest string consisting only of the characters from trim_character (or whitespace, by default) from the start and end of the string source. Syntax: TRIM([LEADING|TRAILING|BOTH] [trim_character] FROM source)
  • BTRIM: A synonym for TRIM(BOTH …), BTRIM removes specified characters from both the start and end of a string. Syntax: BTRIM(source [, trim_character])
  • LTRIM: Removes the longest string that consists only of the specified characters from the start of the source string. Syntax: LTRIM(source [, trim_character])
  • RTRIM: Removes the longest string of characters that are included in the specified characters from the end of the string. Syntax: RTRIM(source [, trim_character])

The trim_character parameter is optional, and if not specified, the functions typically remove spaces. The source parameter is the string to which the trim operation is applied. These functions return a string.

Code Examples

Example 1: Basic white-space trimming

Removing leading and trailing whitespace from a text string.

SELECT TRIM('   Hello, World!  ');
-- Output: 'Hello, World!'

Example 2: Trimming specific characters

Trimming hyphens from the start and end of a string.

SELECT BTRIM('-Hello, World!-', '-');
-- Output: 'Hello, World!'

Example 3: Left trimming

Removing all ‘a’s from the starting of the string.

SELECT LTRIM('aaHello', 'a');
-- Output: 'Hello'

Example 4: Right trimming

Removing all trailing periods (.) from the string.

SELECT RTRIM('Hello.....', '.');
-- Output: 'Hello'

Conclusion

PostgreSQL’s TRIM, BTRIM, LTRIM, and RTRIM are simple yet powerful functions for manipulating text strings. They enable developers and database administrators to easily modify string data by removing unnecessary padding and specific unwanted characters. TRIM functions are a great tool for improving data quality and should be included in any data cleansing toolkit.