(select 'head1' "heads", array_agg(distinct head1 order by head1) "values" from flattable) union all (select 'head2' "heads", array_agg(distinct head2 order by head2) "values" from flattable) union all (select 'head3' "heads", array_agg(distinct head3 order by head3) "values" from flattable) -- output: -- -- heads | values -- -------+----------------------- -- head1 | {val1,val2,val3,val6} -- head2 | {val2,val4,val7} -- head3 | {val3,val5} -- (3 rows)