In the case of queries with set operations (UNION, INTERSECT, EXCEPT)
the ORDER BY must happen later (i.e. nearer to the root of the AST).
E.g.

  SELECT deptno FROM emp
  UNION ALL
  SELECT deptno FROM dept
  ORDER BY deptno

is parsed as

  OrderBy(Union(Select(From emp), Select(From dept)))

When there is no set operation, the parser does the same thing for
consistency. E.g.

  SELECT deptno
  FROM emp
  ORDER BY deptno

is parsed as

  OrderBy(Select(From emp))

The name-resolution rules are different when there are no set
operators; the ORDER BY is allowed to see columns that are not
projected, and is allowed to use table aliases.

SqlValidatorImpl.performUnconditionalRewrites [1] pushes the ORDER BY
into a SELECT (but not into a set operator); the above query becomes
Select(From emp OrderBy deptno).

Julian

[1] 
https://github.com/apache/calcite/blob/4c9011c388f826c36463ae7da875ddb525104376/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java#L1457

On Mon, Nov 6, 2023 at 1:52 AM LakeShen <[email protected]> wrote:
>
> Hi David,
>
> Could you give an example to explain your problem? It’s better to help
> others to understand your problem.
>
> Best,
> LakeShen
>
> David Lin <[email protected]> 于2023年11月6日周一 16:50写道:
>
> > Hi,
> >
> >
> > I've been exploring the Calcite parser and encountered a specific sequence
> > in the parsing of nodes in the syntax tree. It appears that the ORDER_BY
> > node is visited before the SELECT node in the parsing process. I'm curious
> > if this order of node visitation is an expected behavior, and whether there
> > is a means to modify the sequence to have the parser visit the SELECT node
> > before ORDER_BY.
> >
> >
> > Your assistance on this matter would be greatly appreciated.
> >
> >
> > Best regards,
> >
> > David
> >

Reply via email to