CLUSTER BY Clause

Description

The CLUSTER BY clause is used to first repartition the data based on the input expressions and then sort the data within each partition. This is semantically equivalent to performing a DISTRIBUTE BY followed by a SORT BY. This clause only ensures that the resultant rows are sorted within each partition and does not guarantee a total order of output.

Syntax

  1. CLUSTER BY { expression [ , ... ] }

Parameters

  • expression

    Specifies combination of one or more values, operators and SQL functions that results in a value.

Examples

  1. CREATE TABLE person (name STRING, age INT);
  2. INSERT INTO person VALUES
  3. ('Zen Hui', 25),
  4. ('Anil B', 18),
  5. ('Shone S', 16),
  6. ('Mike A', 25),
  7. ('John A', 18),
  8. ('Jack N', 16);
  9. -- Reduce the number of shuffle partitions to 2 to illustrate the behavior of `CLUSTER BY`.
  10. -- It's easier to see the clustering and sorting behavior with less number of partitions.
  11. SET spark.sql.shuffle.partitions = 2;
  12. -- Select the rows with no ordering. Please note that without any sort directive, the results
  13. -- of the query is not deterministic. It's included here to show the difference in behavior
  14. -- of a query when `CLUSTER BY` is not used vs when it's used. The query below produces rows
  15. -- where age column is not sorted.
  16. SELECT age, name FROM person;
  17. +---+-------+
  18. |age| name|
  19. +---+-------+
  20. | 16|Shone S|
  21. | 25|Zen Hui|
  22. | 16| Jack N|
  23. | 25| Mike A|
  24. | 18| John A|
  25. | 18| Anil B|
  26. +---+-------+
  27. -- Produces rows clustered by age. Persons with same age are clustered together.
  28. -- In the query below, persons with age 18 and 25 are in first partition and the
  29. -- persons with age 16 are in the second partition. The rows are sorted based
  30. -- on age within each partition.
  31. SELECT age, name FROM person CLUSTER BY age;
  32. +---+-------+
  33. |age| name|
  34. +---+-------+
  35. | 18| John A|
  36. | 18| Anil B|
  37. | 25|Zen Hui|
  38. | 25| Mike A|
  39. | 16|Shone S|
  40. | 16| Jack N|
  41. +---+-------+