Skip to main content
Aggregates values (including NULL) in a column into an array (multiple rows to one row), and optionally order the elements by specific columns. From v3.0, array_agg() supports using ORDER BY to sort elements.

Syntax

Parameters

  • col: the column whose values you want to aggregate. Supported data types are BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, VARCHAR, CHAR, DATETIME, DATE, ARRAY (since v3.1), MAP (since v3.1), and STRUCT (since v3.1).
  • col0: the column which decides the order of col. There may be more than one ORDER BY column.
  • [desc | asc]: specifies whether to sort the elements in ascending order (default) or descending order of col0.
  • [nulls first | nulls last]: specifies whether null values are placed at the first or last place.

Return value

Returns a value of the ARRAY type, optionally sorted by col0.

Usage notes

  • The order of the elements in an array is random, which means it may be different from the order of the values in the column if no ORDER BY columns or no sorted by order by columns are specified.
  • The data type of the elements in the returned array is the same as the data type of the values in the column.
  • Returns NULL if the input is empty and without group-by columns.
  • ARRAY_AGG_DISTINCT() is an alias of ARRAY_AGG(DISTINCT).

Examples

Take the following data table as an example:
Example 1: Group the values in column a and aggregate values in column pv into an array by ordering a by name.
Example 2: Aggregate values in column pv into an array with ordering by name.
Example 3: Aggregate values in column pv using the WHERE clause. If no data in pv meets the filter condition, a NULL value is returned.

Keywords

ARRAY_AGG, ARRAY