Last active
March 8, 2025 23:43
-
-
Save stevevance/41c914fe3d796dbbe6cdc8a658bdf16e to your computer and use it in GitHub Desktop.
Trim the string elements of an array in PostgreSQL (wrap this function around an array or another function that returns an array, like string_to_array).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION array_trim(text[]) | |
RETURNS text[] | |
AS | |
$$ | |
DECLARE | |
text ALIAS FOR $1; | |
retVal text[]; | |
BEGIN | |
FOR I IN array_lower(text, 1)..array_upper(text, 1) LOOP | |
retVal[I] := trim(text[I]); | |
END LOOP; | |
RETURN retVal; | |
END; | |
$$ | |
LANGUAGE plpgsql | |
STABLE | |
RETURNS NULL ON NULL INPUT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
A field in the table has an array that looks like this:
There are spaces before the two instances of the word "Senior". Now, the method that input this data into the field could have trimmed the spaces off of the strings but it didn't, so we need to use Postgres to trim the spaces.