ARRAY_SORT

Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API

Sorts the elements of an array in ascending or descending order.

Syntax

array_sort(<input_array>[, ascending])

Arguments

Required

  • <input_array>: The array to sort.

Optional

  • ascending: A boolean flag that indicates the sort order. When true (default), sorts in ascending order. When false, sorts in descending order.

Returns

Returns an array with elements sorted in the specified order. NULL values are always first in the output array.

Considerations

  • NULL values are always first in the output array, regardless of sort order.
  • The default sort order is ascending.

Examples

Sort in Ascending Order

Sort an array in ascending order (default behavior).

SELECT array_sort(array[3, 1, 4, 1, 5, 9, 2, 6]) AS result;

Returns array[1, 1, 2, 3, 4, 5, 6, 9], sorted in ascending order.

Sort in Descending Order

Sort an array in descending order using the optional flag.

SELECT array_sort(array[3, 1, 4, 1, 5, 9, 2, 6], false) AS result;

Returns array[9, 6, 5, 4, 3, 2, 1, 1], sorted in descending order.

Sort with NULL Values

Sort an array that contains NULL values.

SELECT array_sort(array[3, null, 1, null, 2]) AS result;

Returns array[null, null, 1, 2, 3]. NULL values are first, followed by the sorted non-NULL values.

Related Documentation