Sorts elements in an array in ascending or descending order. NULL elements are placed at the beginning of the returned array in ascending order, and at the end in descending order.
Syntax
array<T> sort_array(array<T> <a>[, <isasc>])Parameters
Required
a: The array to sort.Tis the element data type, which can be any supported data type.
Optional
isasc: The sort order.truesorts in ascending order;falsesorts in descending order. Default:true.
Return value
Returns a value of the ARRAY type.
Examples
Example 1: Sort multiple array columns in ascending order
The t_array table has the following columns and data:
+------------+---------+--------------+
| c1 | c2 | c3 |
+------------+---------+--------------+
| [a, c, f, b] | [4, 5, 7, 2, 5, 8] | [You, Me, Him] |
+------------+---------+--------------+Sort each array column in ascending order (the default):
-- Returns [a, b, c, f] [2, 4, 5, 5, 7, 8] [Him, Me, You].
select sort_array(c1), sort_array(c2), sort_array(c3) from t_array;Example 2: Sort with NULL elements in ascending order
NULL is treated as the minimum value and placed at the beginning of the result:
-- Returns [null, 10, 20, 30, 30, 40, 50].
select sort_array(array(10, 20, 40, 30, 30, null, 50));Example 3: Sort in descending order with NULL elements
NULL is placed at the end of the result when sorting in descending order:
-- Returns [50, 40, 30, 30, 20, 10, null].
select sort_array(array(10, 20, 40, 30, 30, null, 50), false);Related functions
SORT_ARRAY is a complex type function. For more information about functions that process ARRAY, MAP, STRUCT, and JSON data, see Complex type functions.