|
1 | | ---simplest and faster |
2 | | -CREATE FUNCTION public.array_unique(anyarray) |
| 1 | +create or replace function public.array_unique(anyarray) |
3 | 2 | returns anyarray |
4 | 3 | immutable |
5 | 4 | strict -- returns null if any parameter is null |
6 | 5 | parallel safe -- Postgres 10 or later |
7 | 6 | security invoker |
8 | 7 | language sql |
9 | 8 | 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 | + ); |
13 | 14 | $$; |
14 | 15 |
|
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 |
20 | 21 | 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 |
23 | 25 | language sql |
24 | 26 | 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; |
30 | 50 | $$; |
0 commit comments