DISTRIBUTE BY Clause

Description

The DISTRIBUTE BY clause is used to repartition the data based on the input expressions. Unlike the CLUSTER BY clause, this does not sort the data within each partition.

Syntax

  1. DISTRIBUTE 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 `DISTRIBUTE 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 result
  13. -- of the query is not deterministic. It's included here to just contrast it with the
  14. -- behavior of `DISTRIBUTE BY`. The query below produces rows where age columns are not
  15. -- clustered together.
  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. -- Unlike `CLUSTER BY` clause, the rows are not sorted within a partition.
  29. SELECT age, name FROM person DISTRIBUTE BY age;
  30. +---+-------+
  31. |age| name|
  32. +---+-------+
  33. | 25|Zen Hui|
  34. | 25| Mike A|
  35. | 18| John A|
  36. | 18| Anil B|
  37. | 16|Shone S|
  38. | 16| Jack N|
  39. +---+-------+