Updated on 2026-11-06 GMT+08:00

SORT BY

Function

The SORT BY clause is used to perform local sorting of data within each Reducer. Unlike ORDER BY which performs global sorting, SORT BY only guarantees that the data within each Reducer is sorted.

Syntax

SELECT projectItem [, ...] FROM
  table_reference SORT BY { expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] } [, ...]

Parameters

Parameter

Description

expression

The sort expression. Can be a column name or expression.

ASC

Sorts in ascending order. This is the default option.

DESC

Sorts in descending order.

NULLS FIRST

Places NULL values at the beginning of the sort result.

NULLS LAST

Places NULL values at the end of the sort result.

Precautions

  • SORT BY is a local sort. It only guarantees that data within each Reducer is sorted, not globally.
  • For global sorting, use ORDER BY.
  • SORT BY is typically used with DISTRIBUTE BY to first bucket data and then sort within buckets.
  • SORT BY supports NULLS FIRST/LAST to specify the sort position of NULL values.

Examples

Sort by score in ascending order within Reducers:

SELECT * FROM student SORT BY score; 

Sort by score in descending order within Reducers:

SELECT * FROM student SORT BY score DESC; 

Use with DISTRIBUTE BY:

SELECT * FROM student DISTRIBUTE BY class_id SORT BY score DESC; 

Sort multiple fields and specify NULL value position:

SELECT * FROM student SORT BY class_id ASC NULLS LAST, score DESC NULLS LAST;