BigQuery · Array function
BigQuery ARRAY_REVERSE
ARRAY_REVERSE(arr) returns the same array with its elements in the opposite order. Use it to read event paths or histories newest first, or together with ARRAY_SLICE to take the most recent N items.
ARRAY_REVERSE flips the current order of an array: the last element becomes the first. It does not sort. For a descending sort, rebuild the array with ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY x DESC).
An empty array stays empty and a NULL array returns NULL. Arrays built with ARRAY_AGG have no guaranteed order unless the aggregate has its own ORDER BY, and reversing an arbitrary order gives another arbitrary order.
Often you don't need to reverse at all: ARRAY_AGG(x ORDER BY ts DESC) builds the array newest first, ARRAY_LAST reads the final element, and ARRAY_SLICE accepts negative offsets to take elements from the end.
Syntax
ARRAY_REVERSE(value)Arguments and return value
| Argument | Description |
|---|---|
value | The ARRAY to reverse. Any element type. |
Returns: An ARRAY with the same element type, in reverse order. NULL if the input is NULL.
Examples
Reverse a lifecycle path
SELECT ARRAY_REVERSE(['signup', 'trial', 'paid']) AS newest_first;| newest_first |
|---|
| [paid, trial, signup] |
Reversing is not sorting
SELECT
ARRAY_REVERSE([3, 1, 2]) AS reversed,
ARRAY(SELECT x FROM UNNEST([3, 1, 2]) AS x ORDER BY x DESC) AS sorted_desc;| reversed | sorted_desc |
|---|---|
| [2, 1, 3] | [3, 2, 1] |
Last two touchpoints, newest first
WITH journeys AS (
SELECT 'u1' AS user_id, ['organic', 'email', 'paid_search', 'direct'] AS touchpoints
)
SELECT
user_id,
ARRAY_SLICE(ARRAY_REVERSE(touchpoints), 0, 1) AS last_two_newest_first
FROM journeys;| user_id | last_two_newest_first |
|---|---|
| u1 | [direct, paid_search] |
Empty and NULL input
SELECT
ARRAY_REVERSE(ARRAY<INT64>[]) AS empty_input,
ARRAY_REVERSE(CAST(NULL AS ARRAY<INT64>)) IS NULL AS null_input;| empty_input | null_input |
|---|---|
| [] | true |
Common mistakes
- Using ARRAY_REVERSE to sort in descending order. It only flips the existing order.
- Reversing an ARRAY_AGG built without ORDER BY. The input order is arbitrary, so the output is too.
- Reversing only to read the last element.
ARRAY_LAST(arr)is shorter and doesn't build a new array.
FAQ
How do I reverse an array in BigQuery?
ARRAY_REVERSE(arr) returns the same elements in the opposite order.
How do I sort an array in descending order?
Rebuild it: ARRAY(SELECT x FROM UNNEST(arr) AS x ORDER BY x DESC). When you are aggregating anyway, sort inside the aggregate: ARRAY_AGG(x ORDER BY x DESC).
How do I get the last N elements of an array?
ARRAY_SLICE(arr, -N, -1) returns them in their original order; ARRAY_SLICE(ARRAY_REVERSE(arr), 0, N - 1) returns them newest first.
Related
More array functions
All BigQuery array functions · All functions · BigQuery error messages
