LIMIT 子句

适用于:check marked yes Databricks SQL check marked yes Databricks Runtime

限制查询返回的行数。 通常,此子句会与 ORDER BY 结合使用,以确保结果是确定的。

语法

LIMIT { ALL | integer_expression }

参数

  • ALL

    如果指定了它,查询将返回所有行。 换句话说,如果指定了此选项,则没有限制。

  • integer_expression

    一个返回整数的文本表达式。

示例

> CREATE TEMP VIEW person (name, age)
    AS VALUES ('Zen Hui', 25),
              ('Anil B' , 18),
              ('Shone S', 16),
              ('Mike A' , 25),
              ('John A' , 18),
              ('Jack N' , 16);

-- Select the first two rows.
> SELECT name, age FROM person ORDER BY name LIMIT 2;
 Anil B  18
 Jack N  16

-- Select the 4th and 5th rows by alphabetical order.
> SELECT name, age FROM person ORDER BY name LIMIT 2 OFFSET 3;
  Mike A  25
 Shone S  16

-- Specifying ALL option on LIMIT returns all the rows.
> SELECT name, age FROM person ORDER BY name LIMIT ALL;
  Anil B  18
  Jack N  16
  John A  18
  Mike A  25
 Shone S  16
 Zen Hui  25

-- A function expression as an input to LIMIT.
> SELECT name, age FROM person ORDER BY name LIMIT length('SPARK');
  Anil B  18
  Jack N  16
  John A  18
  Mike A  25
 Shone S  16

-- A non-literal expression as an input to LIMIT is not allowed.
SELECT name, age FROM person ORDER BY name LIMIT length(name);
Error: The limit expression must evaluate to a constant value