Skip to content

Sort is applied to every arm of a parenthesized HQL set operation #4342

Closed

Description

@hunseonglee

When a sorted query is applied to an HQL query using a parenthesized set operation, HqlSortedQueryTransformer.visitNestedQueryExpression re-enters visitOrderedQuery(ctx), which applies the transformer's Sort again at every nesting level — although visitQueryExpression explicitly passes Sort.unsorted() to non-last arms.

On main, sorting

(SELECT tb FROM Test tb WHERE tb.type = 'A') UNION (SELECT tb FROM Test tb WHERE tb.type = 'B')

by tb.Type produces:

(SELECT tb FROM Test tb WHERE tb.type = 'A' order by tb.Type asc)UNION (SELECT tb FROM Test tb WHERE tb.type = 'B' order by tb.Type asc) order by tb.Type asc

The ORDER BY is applied three times. When the arms use different aliases — e.g. (select u from User u) union (select v from Visitor v) with Sort.by("name") — the order by u.name injected into the second arm references an unknown alias and Hibernate rejects the query; even with equal aliases the per-arm ordering changes set-operation semantics.

Expected: Sort is applied exactly once, at the outermost query level, matching the invariant already asserted for FROM-subqueries. I will submit a PR with a fix and tests.

Activity

  1. added
    type: bug
    and removed
    status: waiting-for-triage
    on Sep 18, 2026
  2. self-assigned this
    on Sep 18, 2026
  3. added this to the 4.0.8 (2025.1.8) milestone on Sep 18, 2026
  4. added a commit that references this issue on Sep 18, 2026
    5604a91
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type: bug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions