Skip to content

Instantly share code, notes, and snippets.

@silas
Last active January 13, 2022 20:50
Show Gist options
  • Save silas/cf9f14b6b46a19a49ad37f43372d0c20 to your computer and use it in GitHub Desktop.
Save silas/cf9f14b6b46a19a49ad37f43372d0c20 to your computer and use it in GitHub Desktop.
PostgreSQL array helper functions
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