Skip to content

sql: ORDER BY / LIMIT on the outer layer of a two-layer query is rejected #891

Open

Description

@milindsrivastava1997

Problem

A two-layer query with a plain (non-BY) ORDER BY / LIMIT on its outer layer is rejected. SQLPatternMatcher::nested_query_to_pattern returns QueryError::InvalidNestedQuery (ORDER BY / LIMIT on the outer layer is not supported), and the planner fails with a SqlParse error.

SELECT job, SUM(v) AS s FROM (
  SELECT job, instance, SUM(value) AS v FROM data
  WHERE time BETWEEN DATEADD(s, -1, NOW()) AND NOW()
  GROUP BY job, instance
) GROUP BY job
ORDER BY s DESC LIMIT 5

Equivalent PromQL: topk(5, sum by (job) (sum by (job, instance) (data)))

The same query without ORDER BY / LIMIT is supported (#819): the inner layer is planned as a single-level query and the outer SUM runs as a query-time aggregation. Ordering and truncating the outer result is not wired up: it is rejected rather than dropped, since top-k detection on a nested query only sees its inner layer.

Related: #818 (LIMIT k BY), #820 (outer SELECT without an aggregate), #821 (ORDER BY / LIMIT inside the subquery).

Reproduce

cargo test -p sql_utilities test_nested_query_rejects_outer_order_by_and_limit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions