Collection Functions
Collection Functions
Functions for working with arrays/lists, maps, and structs. Examples run in the shared demo; Copy includes any required model.
UNNEST
Expands an array or list into a set of rows, where each row contains one element from the array/list. This typically changes the grain of the query, hence the KEY purpose.
INDEX_ACCESS
Use array[index] to retrieve an element with a one-based integer index: array[1] is the first element. INDEX_ACCESS is the operation name, not a callable function. Out-of-bounds behavior depends on the backend.
MAP_ACCESS
Use map[key] to retrieve a value. MAP_ACCESS is the operation name, not a callable function. The key type must match the map's key type; missing-key behavior depends on the backend.
ATTR_ACCESS
Use struct.field to retrieve a named field. ATTR_ACCESS is the operation name, not a callable function. The field must exist in the declared struct type.
STRUCT
Constructs a record using value -> field_name bindings. Each field has its own type.
ARRAY
Use square brackets to construct an array from compatible values. ARRAY describes the type; use [a, b] in queries.
Array Literals
Square brackets build an array inline. With only constants, the array is a single fixed value. When any element is a concept, the array is built per row from that row's values, and it belongs to the same keys as those concepts.
select
order_id,
# one fixed value, the same on every row
[1, 2, 3] as fixed_buckets,
# a different array for each order
[order_total, coalesce(order_total, 0.0)] as order_amounts;
Membership and Formatting
contains(array, value) tests membership, while the string overload tests for a substring. array_to_string accepts arrays of non-string values too:
select
contains([1, 2, 3], 2) as has_two,
array_to_string([1, 2, 3], ', ') as number_list;
The results are true and '1, 2, 3'. Numeric array elements do not need an explicit cast before formatting.
MAP_KEYS
Returns an array containing all the keys in the input map.
MAP_VALUES
Returns an array containing all the values in the input map.
GENERATE_ARRAY
Generates an array from a start, end, and required step. The example returns [1, 3, 5, 7, 9]. Endpoint behavior can vary by backend.
ARRAY_DISTINCT
Returns an array with all duplicate values removed.
ARRAY_SORT
Sorts array elements. The optional second argument is the unquoted keyword asc or desc; the default is ascending. Descending support depends on the backend.
ARRAY_TRANSFORM
Applies a user defined function to each element of an array and returns a new array of the results. You must define the function prior to use.
ARRAY_FILTER
Returns only the array elements for which a user-defined function returns true. Define the function first, then pass it with an @ prefix.
ARRAY_TO_STRING
Converts an array to a string, with elements separated by a given delimiter.
ARRAY_SUM
Computes the sum of all numeric elements in an array.