Last active
January 13, 2022 20:50
-
-
Save silas/cf9f14b6b46a19a49ad37f43372d0c20 to your computer and use it in GitHub Desktop.
PostgreSQL array helper functions
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_distinct(anyarray) RETURNS anyarray AS $$ | |
SELECT coalesce(array_agg(x.value ORDER BY x.pos), '{}') | |
FROM ( | |
SELECT DISTINCT ON (item.value) item.value, item.pos | |
FROM unnest($1) WITH ORDINALITY item(value, pos) | |
) x | |
$$ LANGUAGE SQL | |
CREATE OR REPLACE FUNCTION array_set(anyarray) RETURNS anyarray AS $$ | |
SELECT coalesce(array_agg(x.v), '{}') | |
FROM (SELECT DISTINCT unnest($1) AS v ORDER BY 1) x | |
$$ LANGUAGE SQL |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment