Search code examples
arrayspostgresqlaggregate-functionsjsonb

Aggregate concatenate jsonb arrays


Having a table named example_table with one column named example_column of type JSONB and every value in the column being an array.

Having the values in 2 rows be: [1, 2] and [3]

How can I aggregate-concatenate the values in example_column?

The result should be: [1, 2, 3]

I tried using:

select json_agg(example_column) from example_table

but that returns [[1, 2,], [3]]


Solution

  • Use the function jsonb_array_elements(example_column), example:

    with example_table(example_column) as (
    values
        (jsonb '[1, 2]'),
        (jsonb '[3]')
    )
    
    select jsonb_agg(value)
    from example_table
    cross join jsonb_array_elements(example_column) 
    
    jsonb_agg 
    -----------
     [1, 2, 3]
    (1 row)
    

    Update. You can define the sort order of aggregated elements and/or remove duplicates, e.g.:

    with example_table(id, example_column) as (
    values
        (1, jsonb '[1, 2]'),
        (2, jsonb '[3]'),
        (3, jsonb '[3, 1]')
    )
    
    select 
        jsonb_agg(value order by id) as agg1,
        jsonb_agg(value order by value) as agg2,
        jsonb_agg(distinct value order by value) as agg3
    from example_table
    cross join jsonb_array_elements(example_column) 
    
          agg1       |      agg2       |   agg3    
    -----------------+-----------------+-----------
     [1, 2, 3, 3, 1] | [1, 1, 2, 3, 3] | [1, 2, 3]
    (1 row)