Here is an approach using a recursive cte:
with recursive
data as (select array[1, 2, 3] arr),
keys as (select generate_subscripts(d.arr, 1) as rn from data d),
cte as (
select d.arr initial_arr, array[d.arr[k.rn]] new_arr, array[k.rn] used_rn
from data d
cross join keys k
union all
select initial_arr, c.new_arr || c.initial_arr[k.rn], used_rn || k.rn
from cte c
inner join keys k on not (k.rn = any(c.used_rn))
)
select new_arr from cte
Starting from a given array (here defined by cte data
), the idea is to extract all array indexes with generate_subscript()
(cte keys
), and then recursively walk the array. We need to keep track of the keys that we already used so we pick each value only once.
This produces all possible combinations. If you want only the 1-element and 2-elements combinations, you can add a where
clause in the recursive cte, like where array_length(c.new_ar) < 2
.
Demo on DB Fiddle