Skip to content

Support UNIQUE predicate that tests for no duplicate rows in a subquery - #99877

Open
ai-mountain wants to merge 91 commits into
ClickHouse:masterfrom
ai-mountain:feat-unique-subquery-predicate
Open

ai-mountain wants to merge 91 commits into
ClickHouse:masterfrom
ai-mountain:feat-unique-subquery-predicate

Conversation

@ai-mountain

@ai-mountain ai-mountain commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Implement the SQL standard UNIQUE predicate that returns true when all rows in a subquery are distinct and false when duplicates exist. Empty subqueries return true (vacuously unique).

The implementation follows the same pattern as EXISTS:

  • Parser: UniqueLayer class parses UNIQUE(subquery) syntax
  • Analyzer: rewrites to the scalar subquery ifNull((SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)), 1), which is resolved like any other scalar subquery
  • Correlated subqueries are supported (decorrelated by the planner); the old analyzer rejects UNIQUE with a clear error

Closes: #99609

Changelog category (leave one):

  • New Feature

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

Added UNIQUE(subquery) predicate that returns true when all rows in the subquery are distinct. It behaves according to the SQL standard: duplicates yield false, empty subqueries yield true.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ff0cbf5]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED

AI Review

Summary

Adds the UNIQUE(subquery) predicate through parser support and a scalar aggregate rewrite. Two reproducible defects remain in projection renaming: remote execution rejects a valid INTERPOLATE query, and repeated renaming silently changes IN results. Reviewed head: ff0cbf575c7e18da395ea1fc1374a0398c845573.

Findings

❌ Blockers

  • Interpolation names are lost when producing shard SQL. At src/Analyzer/QueryNode.cpp:605 and :636-637, QueryNode::toASTImpl emits the renamed projection with the original INTERPOLATE target. SELECT UNIQUE(SELECT number + 10 AS x FROM remote('127.0.0.1:9000', numbers(2)) ORDER BY number WITH FILL TO 4 INTERPOLATE (x AS x + 1)) throws UNKNOWN_IDENTIFIER for x instead of returning 1. Preserve the original-name mapping through conversion to shard SQL. The same failure affects CTE column aliases over remote. Existing finding, reopened after verifying the claimed fix.

  • A second override discards the original interpolation names. At src/Analyzer/QueryNode.cpp:70-86, resolveProjectionColumns replaces the saved original names with aliases from the previous override. Reproducer:

    WITH t(y) AS (
        SELECT number + 10 AS x FROM numbers(2)
        ORDER BY number WITH FILL TO 4 INTERPOLATE (x AS x + 1)
    )
    SELECT number, number IN t FROM numbers(12, 2)
    ORDER BY number SETTINGS rewrite_in_to_join = 1;

    Returns (12, 0), (13, 0); both membership results must be 1. Disabling the rewrite or removing the CTE column alias produces the correct results. Preserve the earliest names across successive overrides and pruning. Inline finding.

Tests
  • ⚠️ Add focused stateless regressions for the remote interpolation path and the CTE membership query above. All 15 added SQL reference tests pass on the PR fast-test binary, but do not cover these paths. Additional parser probes at nesting depths 20 and 30 pass.
Final Verdict

❌ Block — preserve interpolation through repeated projection overrides and conversion to shard SQL, with regression coverage for both.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 18, 2026
@ai-mountain

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Please review my PR again. Thanks.

@amosbird

Copy link
Copy Markdown
Collaborator

The current rewrite SELECT count() = uniqExact(*) FROM (subquery) is heavier than necessary — it must scan all data even if a duplicate is found on the 2nd row, and runs two aggregate functions simultaneously.

The key property of UNIQUE is that non-unique can terminate immediately. We should exploit this.

Proposed approach

Create an internal aggregate function __hasNoDuplicates(*) that maintains a hash set. On each add, it inserts the row hash — if the key already exists (duplicate), it sets a flag and short-circuits.

The critical part: reuse the existing Aggregator::executeOnBlock BREAK path to cancel I/O.

Today, max_rows_to_group_by with group_by_overflow_mode = 'break' causes Aggregator::executeOnBlock to return false. AggregatingTransform then sets is_consume_finished = true and closes its input port, cascading upstream through the pipeline to stop storage reads. This path is stable and well-tested.

Add two virtual methods to IAggregateFunction:

virtual bool isEarlyTerminable() const { return false; }
virtual bool shouldTerminateEarly(AggregateDataPtr place) const { return false; }

After Aggregator::executeOnBlock processes a block, check whether any aggregate requests early termination — if so, return false, taking the exact same code path as BREAK. No new processors or transforms needed.

Analyzer rewrite becomes simply:

UNIQUE(subquery) → SELECT __hasNoDuplicates(*) FROM (subquery) WHERE <null filter>

Benefits

Current (count() = uniqExact(*)) Proposed (__hasNoDuplicates)
Best case (dup on row 2) O(n) time + full I/O O(1), stops after 1 block
Worst case (all unique) O(n), 2 aggregates O(n), 1 aggregate
I/O cancellation None Block-level via existing BREAK path
New processors None None
IAggregateFunction changes None 2 virtual methods (default false, backward-compatible)

Implementation scope

  • IAggregateFunction: 2 new virtual methods
  • Aggregator::executeOnBlock: ~5 lines to check early termination after block processing
  • AggregateFunctionHasNoDuplicates: ~80 lines (hash set + early termination interface)
  • resolveFunction.cpp: simpler rewrite than current (1 aggregate instead of 2)

The early termination interface is generic and reusable by future aggregate functions.

@ai-mountain

Copy link
Copy Markdown
Contributor Author

@amosbird Thanks very much. I'll fix based on your suggestions.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch 2 times, most recently from 88ad14c to d80e1de Compare March 19, 2026 14:26
Comment thread src/Core/Settings.cpp Resolved
@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch 3 times, most recently from 574ed12 to ef343a9 Compare March 19, 2026 20:07
Comment thread src/Interpreters/Aggregator.cpp Resolved
@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch from ef343a9 to b275828 Compare March 19, 2026 20:58
@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch from b275828 to b00ff36 Compare March 19, 2026 21:34
@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch from b00ff36 to 9e0dd1f Compare March 23, 2026 15:46
@ai-mountain ai-mountain reopened this Mar 23, 2026
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Mar 23, 2026
@ai-mountain

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Can you take another look on my PR please? Thanks.

@alexey-milovidov

Copy link
Copy Markdown
Member

I would like to find a better name for this aggregate function, so it will be usable in normal scenarios.

For example, allUnique

@ai-mountain
ai-mountain force-pushed the feat-unique-subquery-predicate branch 2 times, most recently from 40b1587 to 1e94863 Compare March 23, 2026 19:32
Comment thread contrib/SimSIMD Resolved
The projection name of `UNIQUE(subquery)` was the internal function name
`__unique`, which leaked into `DESCRIBE` and `TSVWithNames` headers. Worse, all
predicates of one query shared that name, so
`SELECT UNIQUE(<unique>), UNIQUE(<duplicates>)` failed with "Block structure
mismatch ... different values of constants in column". Name each predicate
`UNIQUE(__subquery_<hash>)` from the tree hash of its original subquery AST (the
`ASTSubquery::getColumnName` scheme): stable across query tree cloning and
between `only_analyze` and execution, distinct for different predicates.

`04545_unique_predicate_projection_name` now asserts the exact header (with the
hash masked) and the two-predicate query.

Addresses review: ClickHouse#99877 (comment)

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits October 8, 2026 13:10
…a subquery

Address review: `getFunctionLayer` chose `UniqueLayer` as soon as the argument
started like a subquery, so calls such as `unique((SELECT 1), 2)` or
`unique((SELECT 1) + 1)` became syntax errors instead of ordinary function calls
with a scalar subquery. The lookahead now finds the bracket closing a
parenthesized subquery and accepts the predicate form only when it is followed
by the closing bracket of the call or by a set operation (`UNION`, `EXCEPT`,
`INTERSECT`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review: in only-analyze mode `UNIQUE` resolves to a `materialize`
placeholder, which is rejected by functions requiring a constant argument
(`getArgumentsThatAreAlwaysConstant`), e.g. the index of `tupleElement`. So
`CREATE VIEW v AS SELECT tupleElement((1, 2), UNIQUE(SELECT ...))` failed
although the query executes successfully. Such placeholders are now replaced
by the real value of the predicate after the arguments are resolved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 2 commits October 23, 2026 10:10
# Conflicts:
#	src/Analyzer/Resolve/QueryAnalyzer.cpp
`UNIQUE(subquery)` is now rewritten into
`ifNull((SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)), 1)`
and resolved through the regular scalar subquery path, as requested in the review:

- Correlated subqueries are supported: the rewritten subquery is left to the planner for
  decorrelation, like any correlated scalar subquery. A missing correlated group (an empty
  inner relation) is decorrelated to NULL, and an empty input is vacuously unique, hence `ifNull`.
- The projections of the subquery are not renamed anymore: the `NULL` filter uses an `APPLY`
  matcher instead of referring to the columns by name.
- The projection name is built like for a correlated `EXISTS`, from the projection name of the
  subquery: `UNIQUE(_subquery_N)`.
- The `only_analyze` placeholder (the `materialize` wrapper), the
  `constant_expression_in_resolve_process` flag in `LIMIT`/`OFFSET`/`LIMIT BY`/window frame/
  `WITH FILL`/function parameter contexts, and the evaluation of placeholders in always-constant
  arguments are removed. In `only_analyze` mode `UNIQUE` now behaves exactly like any other
  scalar subquery; the tests that pinned the placeholder behaviour are removed.

Document that rows are compared like `DISTINCT` does (floating-point values by their binary
representation), and that correlated subqueries are supported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit ff0cbf5.

Approve preview

alexey-milovidov and others added 3 commits October 30, 2026 14:58
…lt-ins

The rewrite of `UNIQUE(subquery)` creates `count`, `uniqExact`, `equals`,
`and`, `isNotNull` and `ifNull` nodes that are resolved in the scope of the
query, so a lambda with the same name, e.g. `WITH (x -> 0) AS isNotNull`,
replaced them and changed the result of the predicate. Such nodes are now
marked with `FunctionNode::markAsBuiltin`, and their names are not looked up
as lambdas or user defined functions.

The parser-marked `__unique` operator is now recognized before the lambda
lookup, so `WITH (x -> 42) AS __unique` cannot replace the predicate either,
while an ordinary call `__unique(...)` is an ordinary function.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The token lookahead accepted an unparenthesized `SELECT`/`WITH`/`FROM` as the
start of a subquery, so `unique(from + 1)` with a column named `from` became a
syntax error instead of an ordinary function call. Now the argument is parsed
with `ParserSelectWithUnionQuery` and must be followed by the closing bracket
of the call; otherwise `unique` is a regular function name. The parsed subquery
is handed over to `UniqueLayer`, so it is parsed only once and nested
predicates stay linear.

Formatting prints `__unique` as the `UNIQUE` keyword only for the operator
produced by the parser, so an ordinary call `__unique((SELECT 1))` is printed
as itself and keeps its meaning after a round trip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
For an ordinary call such as `unique((SELECT ...), 2)`, the argument was first
parsed speculatively as the subquery of the `UNIQUE` predicate. That parse
failed only at the comma, and then the function call parsed the same argument
again, so the work doubled at every nesting level.

Now a linear token scan checks first whether a bracketed argument can be a
whole subquery: after its first bracketed group, only the closing bracket
of the call, a set operation, or `|>` can follow. The speculative parse also
runs on the caller's `Pos`, so its backtracking counts against
`max_parser_backtracks`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/TreeRewriter.cpp Resolved
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 2 commits November 8, 2026 04:26
…on the legacy path

The `TreeRewriter` gate rejected every AST function named `__unique`, so an
ordinary call with that name (e.g. an executable UDF) failed with
`NOT_IMPLEMENTED` on the legacy expression analysis (constraints, indexes),
while the analyzer only dispatches the parser-marked operator. Gate it on
`isOperator`, like `resolveFunction` and the formatter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 8, 2026 06:25
The rewrite `SELECT count() = uniqExact(*) FROM (subquery) WHERE and(1, * APPLY isNotNull)`
reads the columns of the subquery with matchers, which refer to the columns by name.
A `UNION` whose first query has several columns with the same name, e.g.
`SELECT toNullable(1) AS x, toNullable(1) AS x UNION ALL SELECT NULL, 2`, made both the
`NULL` filter and `uniqExact` read the first of them several times, giving a wrong result.

Resolve the subquery before the rewrite, in a scope nested in the scope of the rewritten
subquery (so that correlation still propagates), and give its columns the unique names
`__unique_predicate_column_N` by position, in every query of a `UNION`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…IQUE` predicate

`UserDefinedSQLFunctionVisitor`, which runs on the AST in `CREATE VIEW`, `ALTER TABLE ... DELETE`,
`DELETE FROM` and similar statements, replaced the operator `__unique` produced by the parser
for `UNIQUE(subquery)` with a SQL user defined function of the same name. Skip the operator form;
an ordinary call `__unique(...)` is still expanded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +1385 to +1386
query_node->setProjectionAliasesToOverride(std::move(unique_names));
query_node->resolveProjectionColumns(std::move(projection_columns));

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.

[Blocker] Preserve INTERPOLATE when renaming the subquery projection

Renaming the resolved projection leaves InterpolateNode::getExpressionName holding the original name. QueryNode::removeUnusedProjectionColumns subsequently compares that name with the renamed projection and removes the explicit interpolation item, changing the rows whose uniqueness is tested.

Reproduced on the CI binary for 2680b43172f6:

SELECT UNIQUE(
    SELECT number + 10 AS x
    FROM numbers(2)
    ORDER BY number WITH FILL TO 4
    INTERPOLATE (x AS x + 1)
); -- 0; expected 1

The standalone subquery produces [10,11,12,13], and adding SELECT x FROM (...) around that same subquery makes the predicate correctly return 1. Please preserve the dependent interpolation metadata when applying positional names, and add this case as a regression test.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Fixed in ff0cbf5. This was a general bug, not specific to UNIQUE: the column aliases of a CTE WITH t(y) AS (... INTERPOLATE (x AS x + 1)) SELECT * FROM t and of FROM (...) AS t(y) lost the interpolation the same way on master. QueryNode now keeps the projection column names before the override (getProjectionColumnNamesBeforeOverride); removeUnusedProjectionColumns matches the INTERPOLATE targets by them, and so does the planner when it routes the interpolated values to the result columns (it also matched by the overridden display alias). 05816_unique_predicate_interpolate covers your reproducer and the CTE / table alias cases.

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.

[Blocker] The local reproducer is fixed, but the same projection/INTERPOLATE mismatch remains when the subquery reads a remote source on ff0cbf575c7:

SELECT UNIQUE(
    SELECT number + 10 AS x
    FROM remote('127.0.0.1:9000', numbers(2))
    ORDER BY number WITH FILL TO 4
    INTERPOLATE (x AS x + 1)
);

With the PR fast-test binary on both ends (tested on port 19000), this throws UNKNOWN_IDENTIFIER for x instead of returning 1. QueryNode::toASTImpl still writes the overridden projection name at src/Analyzer/QueryNode.cpp:605 and emits the original interpolation target at :636-637: the shard receives SELECT number + 10 AS __unique_predicate_column_0 ... INTERPOLATE (x AS x + 1). The new name mapping is consumed by pruning and the local planner, but is lost during conversion to shard SQL. Please preserve it through that conversion too; the CTE column-alias form over remote fails the same way.

Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
alexey-milovidov and others added 5 commits November 17, 2026 10:24
An ordinary call whose argument starts with an identifier that can start a
subquery, e.g. `unique(with + 1)` with a column named `with`, was first
parsed as a subquery, which read the nested expression before failing, and
then parsed again as an ordinary call. Nesting such calls doubled the work
at every level, and `max_parser_backtracks` was exhausted at depth 18.

The outcome of the speculative parse depends only on the tokens, so a failure
is now remembered in `Tokens` by the index of the first token of the argument,
and is not repeated when an enclosing expression is parsed again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `UNIQUE` predicate (the operator `__unique`) and an ordinary call
`__unique(...)` had the same AST hash, so the query cache served the result
of one for the other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ion check

While expanding a SQL UDF named `__unique`, the predicate in its body was
mistaken for a recursive call, so `CREATE VIEW` rejected it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…named from outside

`INTERPOLATE` items name their targets by the names the columns have in the
query. When the projection columns got other names from outside (by the
positional renaming of the `UNIQUE` subquery, or by the column aliases of a
CTE `t(y)` or of a subquery in `FROM ... AS t(y)`),
`QueryNode::removeUnusedProjectionColumns` dropped the items, and the planner
did not route the interpolated values to the result columns, so the filled
rows had default values.

`QueryNode` now keeps the names of the projection columns before the override,
and both places use them to match the `INTERPOLATE` targets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

void QueryNode::resolveProjectionColumns(NamesAndTypes projection_columns_value)
{
projection_column_names_before_override.clear();

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.

[Blocker] Preserve the original names across a second projection override

This clears the saved names on every call and then records the already overridden projection names. The IN-to-join rewrite calls resolveProjectionColumns again for a resolved CTE, so a CTE column alias replaces the original INTERPOLATE target in this mapping. removeUnusedProjectionColumns then silently removes the interpolation item.

Reproduced on ff0cbf575c7:

WITH t(y) AS (
    SELECT number + 10 AS x
    FROM numbers(2)
    ORDER BY number WITH FILL TO 4
    INTERPOLATE (x AS x + 1)
)
SELECT number, number IN t
FROM numbers(12, 2)
ORDER BY number
SETTINGS rewrite_in_to_join = 1;

This returns (12, 0), (13, 0), although t contains 10, 11, 12, 13. With the rewrite disabled, or with the CTE column alias removed, both membership results are 1. Preserve the earliest projection names through subsequent renames (and pruning), and add this case to the regression test.

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support UNIQUE(subquery) predicate that tests for no duplicate rows

8 participants