13

Having problems when using array_agg when a row contains an empty array ({}).

This is my SQL query:

SELECT service_name, metric_name, array_agg(value_textarray)
FROM service_data
WHERE service_name = 'ActivityDataService'
GROUP BY service_name, metric_name

Where the column definitions are the following:

service_name - text
metric_name - text
value_textarray - text[]

When I execute the query and I have empty array ({}) in the database, I get the following error:

ERROR:  cannot accumulate empty arrays

How should I go about fixing this?

4
  • 2
    Simply add "and array <> empty" to the WHERE clause? Commented Apr 18, 2017 at 12:46
  • 2
    Indeed. AND value_textarray <> '{}' took the cake. Thanks. Commented Apr 18, 2017 at 12:49
  • 2
    Alternatively: and coalesce(cardinality(value_textarray),0) = 0 Commented Apr 18, 2017 at 14:20
  • Be careful, if you filter empty arrays in where clause then you will miss that records Commented Apr 30 at 9:58

2 Answers 2

17

I had the same issue where I couldn't filter the empty array and I found this function. This function avoids the 'accumulating empty arrays' error.

CREATE AGGREGATE array_accum (anyarray)
(
    sfunc = array_cat,
    stype = anyarray,
    initcond = '{}'
);  

source: https://gist.github.com/ryandotsmith/4602274

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

1 Comment

This works and can probably be customized to allow concatenation null arrays.
4
SELECT service_name, metric_name, array_agg(value_textarray) filter(where value_textarray <> '{}')
FROM service_data
WHERE service_name = 'ActivityDataService'
GROUP BY service_name, metric_name

You also can add filter(where value_textarray <> '{}') right after array_agg(value_textarray)

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.