Skip to main content
Sorts the elements of an array in ascending order. From v4.0, array_sort supports Lambda Comparator.

Syntax

Parameters

array: the array whose elements you want to sort. Only the ARRAY data type is supported. lambda_comparator: an optional lambda function comparator with format (x,y)->expr(x,y). The lambda comparator:
  • Must only depend on arguments x and y
  • Must return boolean or numeric type
  • Result should not be NULL
  • Must satisfy strict weak ordering requirements

Return value

Returns an array.

Usage notes

Basic Sorting

  • This function sorts the elements of an array in ascending order when used without a lambda comparator.
  • NULL values are placed at the beginning of the array that is returned.
  • The elements of the returned array have the same data type as the elements of the input array.

Lambda Comparator Sorting

  • When using a lambda comparator, the sorting order is determined by the expression result:
    • For boolean return: true means x should come before y
    • For numeric return: negative means x comes before y
  • The lambda comparator must satisfy strict weak ordering requirements:
    • Irreflexivity: For all x, expr(x, x) must return false (boolean) or non-negative (numeric)
    • Asymmetry: If expr(x, y) holds, then expr(y, x) must not hold
    • Transitivity: If expr(x, y) and expr(y, z) hold, then expr(x, z) must hold
    • Connectedness: For all x and y, one of the following must be true:
      • expr(x, y)
      • expr(y, x)
      • x = y
  • The lambda comparator expression must:
    • Only depend on parameters x and y
    • Return a boolean or numeric type
    • Never return NULL
    • Always produce consistent results for the same input values

Descending Order

If you want to sort the elements of an array in descending order, use the reverse function.

Examples

Basic Examples

The following table is used as an example:
Sort the values of column c2 in ascending order.

Lambda Comparator Examples

Sort an array of integers in descending order using a lambda comparator:
Sort an array of integers using numeric return values:
Sort an array of strings by length:
Sort an array of strings alphabetically using boolean return:
Sort an array with custom business logic (sort even numbers first, then odd numbers):
Sort an array of decimals with custom precision comparison: