Skip to content

Instantly share code, notes, and snippets.

@ryanguill
Created December 21, 2016 16:41
Show Gist options
  • Save ryanguill/6c0e82dc7dee9d025bd27ad2abc274b9 to your computer and use it in GitHub Desktop.
Save ryanguill/6c0e82dc7dee9d025bd27ad2abc274b9 to your computer and use it in GitHub Desktop.
in postgres, there currently isnt a function to combine two arrays and remove duplicates - this will do that.
CREATE OR REPLACE FUNCTION mergeArrays (a1 ANYARRAY, a2 ANYARRAY) RETURNS ANYARRAY AS $$
SELECT ARRAY_AGG(x ORDER BY x)
FROM (
SELECT DISTINCT UNNEST($1 || $2) AS x
) s;
$$ LANGUAGE SQL STRICT;
@NewEXE
Copy link

NewEXE commented Mar 13, 2019

Very nice, thanks!

@drmatthewclark
Copy link

doesn't seem to work when one of the arrays is empty.

@ryanguill
Copy link
Author

doesn't seem to work when one of the arrays is empty.

It looks like it works to me - an empty array you must define as the kind of data type in the array, but it works.

https://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=ae6385a5b138c262008de6f0b35986e5

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