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

CLUSTER BY

Function

The CLUSTER BY clause is used to bucket data by the specified fields and sort within the buckets by the same fields. CLUSTER BY is equivalent to using DISTRIBUTE BY and SORT BY with the same fields.

Syntax

SELECT projectItem [, ...] FROM table_reference   CLUSTER BY expression [, ...]

Parameters

Parameter

Description

expression

The bucketing and sorting expression. Supports single and multiple fields. CLUSTER BY distributes data into different buckets based on the hash value of the specified fields and sorts within the buckets by the same fields.

Precautions

  • CLUSTER BY can only sort in ascending order. ASC or DESC cannot be specified. To specify a sort direction, use the DISTRIBUTE BY + SORT BY combination.
  • CLUSTER BY is equivalent to using DISTRIBUTE BY and SORT BY with the same fields.

Examples

Bucket and sort by the score field:

SELECT * FROM student CLUSTER BY score; 

Bucket and sort by multiple fields:

SELECT * FROM student CLUSTER BY class_id, score; 

To specify descending order, use DISTRIBUTE BY + SORT BY:

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