1

I have a table with array values.

create table A (v int[]);

insert into A (v) values ('{1,2,3}');
insert into A (v) values ('{}');
insert into A (v) values (NULL);
insert into A (v) values ('{4,5}');

And table for aggregating this values

create table B (v int[][]);

I need insert all rows from a to b so b.v should be

{{123},{},{},{4,5}}

How you see, also I need map null to empty array. I tired something like

insert into B (v) 
select array_agg(v) from A

But it's not worked - Can't aggreate empty or null values.

1 Answer 1

1

As described in the documentation:

Multidimensional arrays must have matching extents for each dimension. A mismatch causes an error, for example:

INSERT INTO sal_emp
    VALUES ('Bill',
    '{10000, 10000, 10000, 10000}',
    '{{"meeting", "lunch"}, {"meeting"}}');
ERROR:  multidimensional arrays must have array expressions with matching dimensions

As a solution based on this question you may

  1. Use custom domain of array type:

    create domain int_array int[]
    
  2. Use it in your target table:

    create table b(val int_array[])
    
  3. Create custom aggregate for this type:

    create aggregate array_array_agg(int_array) (
      sfunc = array_append,
      stype = int_array[],
      initcond = '{}'
    )
    
  4. And use this custom aggregate:

    insert into b(val)
    select array_array_agg(v)
    from a
    
    INSERT 0 1
    
select *
from b
val
{"{1,2,3}","{}",NULL,"{4,5}"}

fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.