Skip to content

Instantly share code, notes, and snippets.

@stevevance
Last active May 11, 2023 15:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevevance/41c914fe3d796dbbe6cdc8a658bdf16e to your computer and use it in GitHub Desktop.
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).
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;
@stevevance
Copy link
Author

Example usage:

A field in the table has an array that looks like this:

{"Homeowner Exemption"," Senior Exemption"," Senior Freeze Exemption"}

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.

SELECT array_trim('{"Homeowner Exemption"," Senior Exemption"," Senior Freeze Exemption"}')
-- results in:
-- {"Homeowner Exemption","Senior Exemption","Senior Freeze Exemption"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment