Skip to content

Distinct array aggregation ​

Use array_agg(DISTINCT ...) to collect unique admitted values into an array. An aggregate ORDER BY defines the resulting element order.

The CoordinatorDB function is array_agg; groupArrayDistinct is not a callable alias.

Collect distinct values ​

sql
CREATE TABLE labels (value INTEGER);
INSERT INTO labels VALUES (2), (1), (2), (NULL);
sql
SELECT array_agg(DISTINCT value ORDER BY value NULLS LAST)
FROM labels
FORMAT csv;
text
"[1,2,null]"

Array aggregation retains NULL as an element. DISTINCT keeps one copy of it.

Exclude missing elements ​

Use FILTER when the result should contain only present values:

sql
SELECT array_agg(DISTINCT value ORDER BY value)
       FILTER (WHERE value IS NOT NULL)
FROM labels
FORMAT csv;
text
"[1,2]"

See array_agg for empty input and element types, and array functions for operations on the result.