From 27e8ea7025e8e6958994573cc81ba25bffb7019a Mon Sep 17 00:00:00 2001 From: Paul Trowbridge Date: Fri, 4 Nov 2022 13:37:00 -0400 Subject: [PATCH] function to add an element to an array and get all unique elements only --- postgres/jsonb_array_add_distinct.sql | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 postgres/jsonb_array_add_distinct.sql diff --git a/postgres/jsonb_array_add_distinct.sql b/postgres/jsonb_array_add_distinct.sql new file mode 100644 index 0000000..577bdd9 --- /dev/null +++ b/postgres/jsonb_array_add_distinct.sql @@ -0,0 +1,23 @@ +CREATE OR REPLACE FUNCTION public.jsonb_array_add_distinct(_arr jsonb, _add text) RETURNS jsonb AS +$$ +DECLARE + _ret jsonb; + +BEGIN + +SELECT + jsonb_agg(DISTINCT x.ae) +INTO + _ret +FROM + ( + SELECT jsonb_array_elements_text(_arr) ae + UNION ALL + SELECT _add ae + ) x; + +RETURN _ret; + +END; +$$ +language plpgsql