LIMIT Clause

Description

The LIMIT clause is used to constrain the number of rows returned by the SELECT statement. In general, this clause is used in conjunction with ORDER BY to ensure that the results are deterministic.

Syntax

  1. LIMIT { ALL | integer_expression }

Parameters

  • ALL

    If specified, the query returns all the rows. In other words, no limit is applied if this option is specified.

  • integer_expression

    Specifies a foldable expression that returns an integer.

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. -- Select the first two rows.
  10. SELECT name, age FROM person ORDER BY name LIMIT 2;
  11. +------+---+
  12. | name|age|
  13. +------+---+
  14. |Anil B| 18|
  15. |Jack N| 16|
  16. +------+---+
  17. -- Specifying ALL option on LIMIT returns all the rows.
  18. SELECT name, age FROM person ORDER BY name LIMIT ALL;
  19. +-------+---+
  20. | name|age|
  21. +-------+---+
  22. | Anil B| 18|
  23. | Jack N| 16|
  24. | John A| 18|
  25. | Mike A| 25|
  26. |Shone S| 16|
  27. |Zen Hui| 25|
  28. +-------+---+
  29. -- A function expression as an input to LIMIT.
  30. SELECT name, age FROM person ORDER BY name LIMIT length('SPARK');
  31. +-------+---+
  32. | name|age|
  33. +-------+---+
  34. | Anil B| 18|
  35. | Jack N| 16|
  36. | John A| 18|
  37. | Mike A| 25|
  38. |Shone S| 16|
  39. +-------+---+
  40. -- A non-foldable expression as an input to LIMIT is not allowed.
  41. SELECT name, age FROM person ORDER BY name LIMIT length(name);
  42. org.apache.spark.sql.AnalysisException: The limit expression must evaluate to a constant value ...