Skip to main content

ARRAY_SORT

Sorts the elements in an array in ascending order.

Syntax

ARRAY_SORT(<array>[, 'ASC'|'DESC', 'NULLS FIRST'|'NULLS LAST'])
ParameterDefault?Description
ASCYesSpecifies that the sorting order is ascending, arranging elements from smallest to largest.
DESCNoSpecifies that the sorting order is descending, arranging elements from largest to smallest.
NULLS FIRSTYesDetermines that NULL values should appear at the beginning of the sorted output.
NULLS LASTNoDetermines that NULL values should appear at the end of the sorted output.

Examples

This example shows the array sorted in ascending order by default, with the elements arranged from smallest to largest:

SELECT ARRAY_SORT([1, 4, 3, 2]);

-[ RECORD 1 ]-----------------------------------
array_sort([1, 4, 3, 2]): [1,2,3,4]

This example sorts the array in descending order, arranging the elements from largest to smallest:

SELECT ARRAY_SORT([1, 4, 3, 2], 'DESC');

-[ RECORD 1 ]-----------------------------------
array_sort([1, 4, 3, 2], 'desc'): [4,3,2,1]

This example demonstrates how NULL values are handled in descending order, with NULLs appearing before all non-NULL values:

SELECT ARRAY_SORT([1, 4, 3, 2, NULL], 'DESC');

-[ RECORD 1 ]-----------------------------------
array_sort([1, 4, 3, 2, null], 'desc'): [NULL,4,3,2,1]

This example shows the array sorted in descending order while ensuring that NULL values appear at the end of the sorted output:

SELECT ARRAY_SORT([1, 4, 3, 2, NULL], 'DESC', 'NULLS LAST');

-[ RECORD 1 ]-----------------------------------
array_sort([1, 4, 3, 2, null], 'desc', 'nulls last'): [4,3,2,1,NULL]
Explore Databend Cloud for FREE
Low-cost
Fast Analytics
Easy Data Ingestion
Elastic Scaling
Try it today