Skip to content

Instantly share code, notes, and snippets.

@Jeetah
Created March 4, 2024 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jeetah/c1e03e1c1c80e4cb47d713bddd095907 to your computer and use it in GitHub Desktop.
Save Jeetah/c1e03e1c1c80e4cb47d713bddd095907 to your computer and use it in GitHub Desktop.
SQL function to select distinct elements from an Postgres array
CREATE FUNCTION array_distinct(
anyarray, -- input array
boolean DEFAULT false -- flag to ignore nulls
) RETURNS anyarray AS $f$
SELECT array_agg(DISTINCT x)
FROM unnest($1) t(x)
WHERE CASE WHEN $2 THEN x IS NOT NULL ELSE true END;
$f$ LANGUAGE SQL IMMUTABLE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment