Skip to content

Resolve a JOIN USING key from an alias only for the outermost JOIN - #123103

Merged
novikd merged 3 commits into
masterfrom
vdimir/join-using-alias-outermost-join
Oct 6, 2026
Merged

novikd merged 3 commits into
masterfrom
vdimir/join-using-alias-outermost-join

Conversation

@vdimir

@vdimir vdimir commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Related: #121975

Stacked on #121975, which this branch is based on.

With analyzer_compatibility_join_using_top_level_identifier = 1 the alias lookup for a JOIN USING identifier ran for every JOIN of the query. When a projection alias coincides with the USING key of an inner JOIN and its expression refers to the right side, the key could not be resolved:

WITH m AS (SELECT 'a' AS symbol, 'x' AS lp, 1 AS pos),
     b AS (SELECT 'a' AS symbol, 'x' AS lp, 2 AS net_volume),
     dttm AS (SELECT toDateTime('2026-01-01 00:00:00') AS Dttm)
SELECT if(m.symbol = '', b.symbol, m.symbol) AS symbol,
       if(m.lp = '', b.lp, m.lp) AS lp,
       b.net_volume + m.pos AS pos,
       dttm.Dttm AS last_updated
FROM m
FULL OUTER JOIN b USING (symbol, lp)
FULL OUTER JOIN dttm ON 1 = 1
-- Unknown expression or function identifier `b.symbol`. In scope SELECT if(symbol = '', b.symbol, m.symbol) AS symbol FROM m

The old analyzer, which the setting emulates, rewrote a query with several joins into nested subqueries (JoinToSubqueryTransformVisitor). An inner JOIN therefore never saw an alias of the outer query and resolved its USING key from the left table; the query above returns a row there (checked on 26.3 with enable_analyzer = 0). An aliased USING key on the outermost JOIN of such a query was an error in the old analyzer, while the new analyzer has supported it since 03716_multiple_joins_using_top_level_identifier; that stays as is.

resolveJoin now consults the aliases only for the JOIN at the root of the query's join tree (ARRAY JOIN nodes above it do not count), and inner JOINs resolve the key from their left table. The hint about the setting in the UNKNOWN_IDENTIFIER message is limited to the same case. An inner JOIN whose USING key currently resolves from an alias will resolve from the left column instead, or fail when there is none, which is what the old analyzer did.

The alias probe also re-resolves the already resolved left join tree, so an inner USING join below an aliased outermost USING key failed on master as well:

SELECT a + 1 AS b, t3.c FROM (SELECT 1 AS a, 10 AS k) t1 JOIN (SELECT 10 AS k) t2 USING (k) JOIN (SELECT 2 AS b, 7 AS c) t3 USING (b)
-- JOIN INNER JOIN ... USING (k) USING clause expected identifier. Actual: k. (BAD_ARGUMENTS)

The USING branch of resolveJoin returns early for a list that already holds columns, the same way the ON branch is idempotent through resolved expressions.

Not changed: with an ARRAY JOIN on the left side of the JOIN the alias is not applied at all (04002_join_using_top_level_array_join, 04075_array_join_using_compatibility_setting), although the old analyzer applied it there.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

With analyzer_compatibility_join_using_top_level_identifier = 1, a JOIN USING identifier is resolved from an alias of the query only for the outermost JOIN; an inner JOIN of a query with several joins resolves it from its left table, as the old analyzer did. This fixes UNKNOWN_IDENTIFIER for queries such as SELECT if(m.symbol = '', b.symbol, m.symbol) AS symbol FROM m FULL JOIN b USING (symbol) FULL JOIN dttm ON 1 = 1, and a USING clause expected identifier error when an inner USING join is placed below an aliased outermost USING key.

Close #121591
🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/123103]

Version info

  • Merged into: 26.10.1.1665-master (included in 26.10 and later)
  • Backported to: 26.9.30.8, 26.8.38.11, 26.3.66.4

@vdimir
vdimir added this pull request to stack #123104 September 30, 2026 16:21
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6f6ce01]

Summary: ✅


AI Review

Summary

This PR narrows analyzer_compatibility_join_using_top_level_identifier so only the outermost JOIN can synthesize its USING key from a query alias, and it reworks the alias probe to stop re-resolving the left join tree. The remaining problem is that the synthetic probe scope still drops the enclosing alias environment, so chained aliases that the setting promises to honor still fail with UNKNOWN_IDENTIFIER; I cannot approve until that is fixed.

Findings

❌ Blockers

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:6136] alias_visitor only collects aliases nested inside the cloned projection_node, but left_subquery_scope never inherits the rest of the query's alias / WITH tables. As a result, chained aliases still break in the new probe path: queries such as WITH x + 1 AS a, a + 1 AS b SELECT count() FROM (SELECT 0 AS x) t1 JOIN (SELECT 2 AS b) t2 USING (b) or SELECT x + 1 AS a, a + 1 AS b FROM (SELECT 0 AS x) t1 JOIN (SELECT 2 AS b) t2 USING (b) still resolve the cloned b against only the left join tree and throw UNKNOWN_IDENTIFIER. That violates the setting's documented contract that aliases defined elsewhere in the query are considered.
    Suggested fix: resolve the cloned expression through a child scope of the original query that preserves the current alias / WITH environment while overriding the visible join tree to the left side only, or explicitly copy the relevant alias maps (aliases / global_with_aliases, including duplicate-alias bookkeeping) into left_subquery_scope before resolveExpressionNode. Add regression coverage for both the chained-SELECT and chained-WITH forms.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required: keep the enclosing alias / WITH environment visible inside the synthetic alias probe and add focused regression tests for chained aliases.

LLVM Coverage Report

Measured on commit 6f6ce01.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 68/70 (97.14%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Sep 30, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6f6ce012d with master 728262641 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+33.02 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/Resolve/QueryAnalyzer.cpp.o 1.49 MiB 1.53 MiB +32.89 KiB (+2.15%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

8 translation units recompiled, 31 s compile time in total, 8 of them have a recent master baseline.

Job report

Base automatically changed from vdimir/join-using-with-clause-alias to master October 1, 2026 08:55
@vdimir
vdimir force-pushed the vdimir/join-using-alias-outermost-join branch from 5a0c275 to 8dd6861 Compare October 1, 2026 08:55
const auto & resolved_nodes = left_subquery->getProjection().getNodes();
if (resolved_nodes.size() == 1)
auto & projection_node = left_subquery->getProjection().getNodes().front();
QueryExpressionsAliasVisitor alias_visitor(left_subquery_scope.aliases);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alias_visitor only collects aliases nested inside projection_node, but this fresh left_subquery_scope never inherits the rest of the query's alias tables. That breaks chained aliases that the setting says should work from "the query", for example WITH x + 1 AS a, a + 1 AS b SELECT count() FROM (SELECT 0 AS x) t1 JOIN (SELECT 2 AS b) t2 USING (b) or SELECT x + 1 AS a, a + 1 AS b FROM (SELECT 0 AS x) t1 JOIN (SELECT 2 AS b) t2 USING (b): the cloned b expression still contains identifier a, and resolveExpressionNode here can only see the left join tree, so it throws UNKNOWN_IDENTIFIER.

I think the probe still needs to inherit the enclosing alias / WITH environment (or resolve through a child scope of the original query) before resolving the cloned expression.

vdimir and others added 2 commits October 1, 2026 14:18
With `analyzer_compatibility_join_using_top_level_identifier` the alias lookup ran for every `JOIN` of the query.
A projection alias that refers to the right side of an inner `JOIN`, such as
`if(m.symbol = '', b.symbol, m.symbol) AS symbol` over `FROM m FULL JOIN b USING (symbol) FULL JOIN dttm ON 1 = 1`,
therefore failed with `UNKNOWN_IDENTIFIER`. The old analyzer rewrote a query with several joins into nested
subqueries, so an inner `JOIN` never saw such an alias and resolved the key from its left table; only the outermost
`JOIN` does now.

The alias probe also re-resolved the already resolved left join tree, so an inner `USING` join below an aliased
outermost `USING` key failed with `USING clause expected identifier`; the `USING` branch of `resolveJoin` returns
early for a list that is already resolved.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…tree again

`try_resolve_identifier_from_query_projection` built a query whose join tree was the already resolved left side of the
`JOIN` and resolved that query. An inner `USING` join below an aliased outermost `USING` key therefore failed with
`USING clause expected identifier`: its `USING` list held columns by then. The probe now keeps a fresh scope over the
left side, takes over the table expression data of its leaves from the current scope and resolves only the aliased
expression with `resolveExpressionNode`. Nothing is resolved twice, so the early return for an already resolved
`USING` list is gone. The query node of the probe stays as the scope of the resolution: an unqualified matcher inside
the expression, such as `tuple(*) AS k`, finds the left side only through the nearest query scope, which the test now pins.

The outermost `JOIN` check is evaluated on demand, and the comments no longer claim the old analyzer used an alias for
the outermost `JOIN` of a multi-join query: it rejected that shape altogether, so only an inner `JOIN` resolving its key
from the left table is old-analyzer behaviour.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vdimir
vdimir force-pushed the vdimir/join-using-alias-outermost-join branch 3 times, most recently from 8296ff4 to 590de1f Compare October 1, 2026 12:43
…d resolve it as in `PREWHERE`

The probe of `try_resolve_identifier_from_query_projection` resolves the aliased expression in a fresh scope over the
already resolved left side, but the scope held only the table expression data of the leaves. A qualified matcher finds
its table only through `alias_name_to_table_expression_node`, so `tuple(t1.*) AS k ... USING (k)` failed with
`Qualified matcher t1.* does not find table`, even for a single `JOIN`. The scope now also registers the aliases of the
leaves and counts `joins_count` and `using_joins_count` over the left side, as `resolveQuery` does for a join tree.

The synthesized key is an ALIAS column of its source table and is computed right after that table is read, before the
joins of the left side. A column of a `USING` key inside the left side therefore has to keep the type it is read with:
resolving `t1.a` with the supertype of an inner `USING (a)` raised a `LOGICAL_ERROR` (`Unexpected return type from
tuple`) when the alias action ran on the read column. The probe scope sets `allow_resolve_from_using = false`, the
mechanism `PREWHERE` uses for the same reason, next to the existing `join_use_nulls = false`. As in `PREWHERE`, an
unqualified matcher that expands the key column of the inner `USING` join from both of its tables has no single source
table and does not become a key.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@novikd novikd self-assigned this Oct 5, 2026
@novikd
novikd added this pull request to the merge queue Oct 6, 2026
Merged via the queue into master with commit 4925b13 Oct 6, 2026
149 checks passed
@novikd
novikd deleted the vdimir/join-using-alias-outermost-join branch October 6, 2026 13:31
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
`CollectPrewhereTableExpressionVisitor` did not descend into `LAMBDA`, so a column read only inside
a lambda body escaped the check that PREWHERE reads one table. Once an unqualified matcher in a
lambda expands like the direct one, `CROSS JOIN`, `JOIN ... ON` and `PASTE JOIN` put the right
table's columns there, and the query failed later with `NOT_FOUND_COLUMN_IN_BLOCK` or a
`Cannot capture column` logical error instead of `ILLEGAL_PREWHERE`. Lambda parameters are
skipped by their `LAMBDA_ARGS` source, as `CollectSourceColumnsVisitor` does.

04647 section 12e compared a lambda matcher in PREWHERE with explicit columns of the merged USING
key, which the lambda form matched only because of the scope bug fixed in this PR. Its oracle is
now the same matcher written directly in PREWHERE. In 04683 the expansion under
`analyzer_compatibility_join_using_top_level_identifier` follows master after ClickHouse#123103.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@novikd novikd added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Nov 13, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 13, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Nov 16, 2026
Cherry pick #123103 to 26.3: Resolve a JOIN USING key from an alias only for the outermost JOIN
robot-clickhouse added a commit that referenced this pull request Nov 16, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Nov 16, 2026
Cherry pick #123103 to 26.8: Resolve a JOIN USING key from an alias only for the outermost JOIN
robot-clickhouse added a commit that referenced this pull request Nov 16, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Nov 16, 2026
Cherry pick #123103 to 26.9: Resolve a JOIN USING key from an alias only for the outermost JOIN
robot-clickhouse added a commit that referenced this pull request Nov 16, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 16, 2026
Backport #123103 to 26.8: Resolve a JOIN USING key from an alias only for the outermost JOIN
clickhouse-gh Bot added a commit that referenced this pull request Nov 16, 2026
Backport #123103 to 26.9: Resolve a JOIN USING key from an alias only for the outermost JOIN
alexey-milovidov added a commit that referenced this pull request Nov 16, 2026
Backport #123103 to 26.3: Resolve a JOIN USING key from an alias only for the outermost JOIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Analyzer: UNKNOWN_IDENTIFIER when alias resolution fails and analyzer_compatibility_join_using_top_level_identifier=1

5 participants