Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API
Collects the input values from a group into an array using an optional, user-supplied order.
Syntax
array_agg([DISTINCT] <value> [ORDER BY <sort_expression> [ASC | DESC] [NULLS { FIRST | LAST }] [, ...]] [NULL ON NULL | ABSENT ON NULL])
Use with GROUP BY to build one array per group:
SELECT <group_columns>,
array_agg(<value> ORDER BY <sort_expression>)
FROM <table>
GROUP BY <group_columns>;
Arguments
Required
<value>: The expression collected into the array. Its result type becomes the element type of the returned array.
Optional
DISTINCT: Keeps only distinct values. When you useDISTINCT, theORDER BYexpression (including its collation) must match<value>.ORDER BY <sort_expression> [, ...]: Orders the elements within the array (an aggregate-local ordering). Each sort key acceptsASC/DESCandNULLS FIRST/NULLS LAST.NULL ON NULL: CollectsNULLinputs asNULLarray elements. This is the default.ABSENT ON NULL: SkipsNULLinputs so they don't appear in the array.
Returns
An array whose element type matches <value>.
Null handling:
- With the default
NULL ON NULL,NULLinputs are kept asNULLarray elements. - With
ABSENT ON NULL,NULLinputs are dropped. A group whose values are allNULLreturns an empty array ([]).
Considerations
array_aggkeepsNULLs by default (NULL ON NULL).- The
FILTERclause isn't supported forarray_agg. - When you combine
DISTINCTwithORDER BY, the sort expression (and its collation) must match the aggregated value. - If no
ORDER BYis specified, the resulting array has an implementation-defined, non-deterministic order. array_aggwithORDER BYisn't supported in combination withROLLUP,CUBE, orGROUPING SETS.- To turn the resulting array into a delimited string, use
ARRAY_TO_STRING. To expand an array back into rows, useUNNEST.
Examples
Aggregate values in a specified order, dropping NULLs
Order the elements by timestamp and skip NULL events.
SELECT array_agg(event ORDER BY timestamp ABSENT ON NULL)
FROM (VALUES ('completed', 2), (NULL, 3), ('started', 1)) AS events(event, timestamp);
Returns ["started","completed"].
Keep NULLs (default behavior)
Without ABSENT ON NULL, NULL inputs are collected as NULL elements.
SELECT array_agg(v ORDER BY k)
FROM (VALUES (1, 1), (NULL, 2), (3, 3)) AS t(v, k);
Returns [1,NULL,3].
One array per group
Build a sorted array of product names for each category.
SELECT category,
array_agg(product_name ORDER BY product_name)
FROM products
GROUP BY category;