Postgres trim() function
Remove leading and trailing characters from a string
The Postgres trim()
function removes the specified characters from the beginning and/or end of a string.
This function is commonly used in data preprocessing tasks, such as cleaning user input before storing it in a database or standardizing data for comparison or analysis. For example, you might use it to remove extra spaces from product names or to standardize phone numbers by removing surrounding parentheses.
Function signature
The trim()
function has two forms:
leading | trailing | both
(optional): Specifies which part of the string to trim. If omitted, it defaults toboth
.characters
(optional): The set of characters to remove. If omitted, it defaults to spaces.string
: The input string to trim.
string
: The input string to trim.characters
(optional): The characters to remove from both ends. If omitted, it defaults to spaces.
Example usage
Consider a table products
with a product_name
column that contains product names with inconsistent spacing. We can use trim()
to standardize these names.
This query removes leading and trailing spaces from the product_name
column.
You can also use trim()
to remove specific characters from both ends of a string.
This query removes the '#' characters from both ends of the id
column.
Advanced examples
Trim only leading or trailing characters
You can specify whether to trim characters from the beginning, end, or both sides of a string.
The query above demonstrates trimming asterisks from the beginning, end, and both sides of the input
column, as shown in the following table.
Use trim() in a WHERE clause
You can use trim()
in a WHERE
clause to filter rows based on matching a trimmed value.
The query above filters for rows where the trimmed code
column starts with 'ABC', as shown in the following table:
Combine trim() with other string functions
You can combine trim()
with other string functions for more complex string manipulations.
The query above trims spaces from the email addresses and then extracts and uppercases the username part (before the '@' symbol).
Additional considerations
Performance implications
While trim()
is generally efficient, using it extensively on large datasets, especially in WHERE
clauses, may impact query performance. If you frequently filter or join based on trimmed values, consider creating a functional index on the trimmed column.
Handling NULL values
The trim()
function returns NULL if the input string is NULL. Be aware of this when working with potentially NULL columns to avoid unexpected results.
Alternative functions
ltrim()
- Removes specified characters from the beginning (left side) of a string.rtrim()
- Removes specified characters from the end (right side) of a string.btrim()
- Removes specified characters from both the beginning and end of a string.regexp_replace()
- Can be used for more complex trimming operations using regular expressions.
Resources
Last updated on