Skip to content

Commit 761e64a

Browse files
author
Rinat Mukhtarov
committed
array_unique() improved, test added
1 parent e5ead2f commit 761e64a

File tree

1 file changed

+37
-17
lines changed

1 file changed

+37
-17
lines changed

functions/array/array_unique.sql

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,50 @@
1-
--simplest and faster
2-
CREATE FUNCTION public.array_unique(anyarray)
1+
create or replace function public.array_unique(anyarray)
32
returns anyarray
43
immutable
54
strict -- returns null if any parameter is null
65
parallel safe -- Postgres 10 or later
76
security invoker
87
language sql
98
set search_path = ''
10-
AS $$
11-
SELECT array_agg(DISTINCT x) --using DISTINCT implicitly sorts the array
12-
FROM unnest($1) t(x);
9+
as $$
10+
select array(
11+
select distinct t.x --using DISTINCT implicitly sorts the array
12+
from unnest($1) t(x)
13+
);
1314
$$;
1415

15-
CREATE FUNCTION public.array_unique(
16-
anyarray, -- input array
17-
boolean -- flag to drop nulls
18-
)
19-
RETURNS anyarray
16+
create or replace function public.array_unique(
17+
anyarray, -- input array
18+
boolean -- flag to drop nulls
19+
)
20+
returns anyarray
2021
immutable
21-
returns null on null input
22-
parallel safe
22+
strict -- returns null if any parameter is null
23+
parallel safe -- Postgres 10 or later
24+
security invoker
2325
language sql
2426
set search_path = ''
25-
AS $$
26-
SELECT array_agg(DISTINCT x) --using DISTINCT implicitly sorts the array
27-
FROM unnest($1) t(x)
28-
--WHERE CASE WHEN $2 THEN x IS NOT NULL ELSE true END;
29-
WHERE NOT $2 OR x IS NOT NULL;
27+
as $$
28+
select array(
29+
SELECT DISTINCT t.x --using DISTINCT implicitly sorts the array
30+
FROM unnest($1) t(x)
31+
WHERE NOT $2 OR t.x IS NOT NULL
32+
);
33+
$$;
34+
35+
--TEST
36+
do $$
37+
begin
38+
assert public.array_unique('{}'::int[]) = '{}'::int[];
39+
assert public.array_unique('{1,1,2,2,null,null}'::int[]) = '{null,1,2}';
40+
assert public.array_unique('{x,x,y,y,null,null}'::text[]) = '{null,x,y}';
41+
42+
assert public.array_unique('{}'::int[], false) = '{}'::int[];
43+
assert public.array_unique('{1,1,2,2,null,null}'::int[], false) = '{null,1,2}';
44+
assert public.array_unique('{x,x,y,y,null,null}'::text[], false) = '{null,x,y}';
45+
46+
assert public.array_unique('{}'::int[], true) = '{}'::int[];
47+
assert public.array_unique('{1,1,2,2,null,null}'::int[], true) = '{1,2}';
48+
assert public.array_unique('{x,x,y,y,null,null}'::text[], true) = '{x,y}';
49+
end;
3050
$$;

0 commit comments

Comments
 (0)