Skip to content

Pipe operators in SQL queries - #111151

Merged
alexey-milovidov merged 35 commits into
masterfrom
pipe-syntax
Aug 11, 2026
Merged

alexey-milovidov merged 35 commits into
masterfrom
pipe-syntax

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Closes: #69364
Related: #73394

Changelog category (leave one):

  • New Feature

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

Support pipe operators in SQL queries: FROM t |> WHERE x > 1 |> AGGREGATE count() AS c GROUP BY y |> ORDER BY c DESC |> LIMIT 10, similar to the pipe syntax of GoogleSQL. Any SELECT query can be followed by a chain of |> operators, and each operator wraps the query before it into a subquery, so the resulting AST is the same as for the equivalent query with nested subqueries. In a query that starts with the FROM clause, the SELECT clause is now optional and defaults to SELECT *.

This is a reimplementation of #73394 following the review discussion: instead of a separate dialect with its own syntax tree and translator, the pipe operators are a syntax extension of the regular ClickHouse dialect. The |> token was previously a syntax error, so no existing queries change behavior. Inside every operator, the regular ClickHouse syntax is used, and any type of query can be pipelined:

FROM orders
|> WHERE cancelled = 0
|> AGGREGATE sum(amount) AS total GROUP BY customer
|> ORDER BY total DESC
|> LIMIT 3

is parsed into the same AST as

SELECT * FROM
(
    SELECT customer, sum(amount) AS total FROM
    (
        SELECT * FROM
        (
            SELECT * FROM orders
        )
        WHERE cancelled = 0
    )
    GROUP BY customer
)
ORDER BY total DESC
LIMIT 3

Supported operators: WHERE, SELECT [DISTINCT], EXTEND, SET (via * REPLACE), DROP (via * EXCEPT), AS, AGGREGATE ... [GROUP BY ...], DISTINCT, ORDER BY, LIMIT [OFFSET], OFFSET, UNION/INTERSECT/EXCEPT, and all kinds of JOIN, including ARRAY JOIN. Pipe operators work everywhere a SELECT query is expected: in subqueries, INSERT ... SELECT (including the form INSERT INTO t2 FROM t1 |> ...), CREATE VIEW, the view table function, EXPLAIN, and so on. Since every operator is a subquery scope, table aliases are visible only within the same operator (e.g. in the ON condition of a join) - this is a difference from GoogleSQL, which keeps table aliases visible across operators.

The implementation is a new TokenType::PipeOperator for |> in the lexer and the parsePipeOperators function invoked from ParserSelectWithUnionQuery after the union list; each operator parses its clauses with the existing expression parsers and constructs the wrapping ASTSelectQuery. The depth of the chain is limited by the parser depth check and by the AST depth check after parsing.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1189 (included in 26.8 and later)

alexey-milovidov and others added 2 commits July 20, 2026 21:47
A query can be followed by a chain of pipe operators, similar to the pipe
syntax of GoogleSQL:

    FROM orders
    |> WHERE cancelled = 0
    |> AGGREGATE sum(amount) AS total GROUP BY customer
    |> ORDER BY total DESC
    |> LIMIT 3

The `|>` token is a syntax extension of the regular ClickHouse dialect:
each operator wraps the query before it into a subquery, so the resulting
AST is the same as the AST of the equivalent query written with nested
subqueries, and inside every operator the regular ClickHouse syntax is used.

Supported operators: `WHERE`, `SELECT [DISTINCT]`, `EXTEND`, `SET`, `DROP`,
`AS`, `AGGREGATE ... [GROUP BY ...]`, `DISTINCT`, `ORDER BY`,
`LIMIT [OFFSET]`, `OFFSET`, `UNION`/`INTERSECT`/`EXCEPT`, all kinds of
`JOIN` and `ARRAY JOIN`.

Also, in a query that starts with the `FROM` clause, the `SELECT` clause
is now optional: `FROM t` works as `FROM t SELECT *`. `INSERT` queries can
use the form `INSERT INTO t2 FROM t1 |> ...`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The generated test reference is verified against the built server:
the stateless test `04613_pipe_operators` passes, and `EXPLAIN SYNTAX`
shows that pipe queries produce the same AST as nested subqueries.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 20, 2026, 11:09 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d70225]

Summary: ✅


AI Review

Summary

This PR adds FROM-first SELECT syntax and |> pipe operators by lowering each stage to ordinary nested subqueries, along with the corresponding documentation and stateless coverage. After reviewing the current diff and re-checking all prior inline discussion against the current head, I did not find a new blocker or major correctness issue that still holds.

Final Verdict

✅ No new review findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 424/486 (87.24%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 20, 2026
Comment thread src/Parsers/ParserPipeOperators.cpp Resolved
…pipe operators

Two fixes for the pipe operators:

1. The `|> LIMIT length OFFSET offset` operator set `LIMIT_LENGTH` before
   `LIMIT_OFFSET`, while `ParserSelectQuery` inserts them in the opposite
   order. The AST consistency check in debug builds compares the tree of the
   original AST with the result of parsing back the formatted AST, so the
   query `FROM orders |> ORDER BY amount DESC |> LIMIT 2 OFFSET 1` failed
   with a logical error `Inconsistent AST formatting` (an exception in
   `executeQuery`), which showed up in the CI report:
   https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111151&sha=fe252592074e771e8964282d9ead984ecb0475fc&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29

2. Address review: `wrapQueryIntoSelect` did not carry over the `WITH`
   clause of the query, so query-scoped aliases and CTEs went out of scope
   after the first operator, e.g. in
   `WITH 10 AS threshold FROM t |> WHERE x < threshold`. Now the effective
   `WITH` clause (the one of the first `SELECT`, together with the
   `recursive_with` flag) is cloned onto every wrapping `SELECT`, and the
   children are added in the same order as in `ParserSelectQuery` to keep
   the formatting round-trip consistent.

Tests cover a scalar `WITH` alias, a CTE, a CTE referenced in a `JOIN`
operator, `WITH RECURSIVE`, and the formatting of `LIMIT ... OFFSET ...`.

#111151

Co-Authored-By: Claude Fable 5 <[email protected]>
{
/// If SELECT is defined (possibly in parentheses), return to position before select and parse
/// rest of query as SELECT query. Parentheses are handled by ParserSelectWithUnionQuery.
/// The query can also start with the FROM clause: INSERT INTO t2 FROM t1 |> WHERE x.

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.

The new FROM-started INSERT ... SELECT entrypoint still attaches an INSERT-scoped WITH only after ParserSelectWithUnionQuery has already built the pipe wrappers below. That means wrapQueryIntoSelect never sees those aliases/CTEs while it is constructing |> stages, so under enable_global_with_statement = 0 a query like WITH 10 AS threshold INSERT INTO dst FROM src |> WHERE x < threshold still loses threshold in the first wrapped WHERE and throws UNKNOWN_IDENTIFIER.

The plain WITH ... FROM ... |> ... case was fixed by cloning the effective WITH during wrapping, but this new INSERT ... FROM ... |> ... path reintroduces the same bug for INSERT-scoped WITH. We need to push the WITH onto the initial SELECT before piping, or recursively clone it into the generated wrappers here, so the feature does not depend on enable_global_with_statement.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d4065af (via b2c05c6). spreadWithOntoPipeStages now clones the INSERT-scoped WITH down the whole chain of generated pipe wrappers, not just the outermost SELECT, so query-scoped aliases/CTEs stay visible in every |> stage regardless of enable_global_with_statement. Added a regression test in 04613_pipe_operators covering WITH ... INSERT INTO ... FROM ... |> WHERE ... |> WHERE ... |> SELECT ... with enable_global_with_statement = 0.

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.

The original regression is back in the current head. src/Parsers/ParserInsertQuery.cpp:221-237 still attaches the INSERT-scoped WITH only after ParserSelectWithUnionQuery has already built the pipe wrappers, and only to the direct list_of_selects children. Then src/Interpreters/InterpreterInsertQuery.cpp:883-885 propagates that outer WITH into nested stages only when enable_global_with_statement is enabled.

So under enable_global_with_statement = 0, WITH 10 AS threshold INSERT INTO dst FROM src |> WHERE x < threshold still loses threshold inside the first wrapped WHERE. The d4065af fix no longer matches the current code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 This is intentional: spreadWithOntoPipeStages was deliberately reverted at the author's request (see the other thread on this file — "Why do we care about enable_global_with_statement = 0? I think it worked perfectly without this logic."). Per the review verdict's alternative action, the behavior is now documented and pinned by a test in 13d2b02: pipe-operators.md notes that an INSERT-scoped WITH reaches the inner pipe stages via enable_global_with_statement (enabled by default) — exactly the way it reaches a hand-written nested subquery — and 04613_pipe_operators asserts that with the setting disabled both the piped form and the equivalent hand-written nested-subquery form fail identically with UNKNOWN_IDENTIFIER (verified under both analyzers). So the INSERT ... FROM ... |> ... form is not narrower than what the same query written with explicit nested subqueries provides.

Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
alexey-milovidov and others added 3 commits July 21, 2026 17:32
Address two parser-ordering gaps found in review of the `|>` pipe operators
feature (#111151):

- An `INSERT`-scoped `WITH` (written before `INSERT`) was attached only to the
  outermost generated `SELECT`, so query-scoped aliases and CTEs became invisible
  in the inner pipe stages when `enable_global_with_statement = 0`, e.g.
  `WITH 100 AS lo, 300 AS hi INSERT INTO t FROM src |> WHERE x >= lo |> WHERE x < hi`
  threw `UNKNOWN_IDENTIFIER`. `spreadWithOntoPipeStages` now clones the `WITH`
  down the whole chain of pipe wrappers, matching the plain
  `WITH ... FROM ... |> ...` behavior and no longer depending on the setting.

- In the `FROM`-first form, the parser decided that `SELECT` was omitted before
  parsing the post-`FROM` column alias list (`ASTSelectQuery::ALIASES`), so
  `FROM t (a, b) SELECT ...` was misclassified as implicit `SELECT *` and failed
  on the later explicit `SELECT`. The alias list is now parsed right after the
  tables, before deciding whether the `SELECT` clause was omitted.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- `WITH RECURSIVE` requires the analyzer, so it failed on the old-analyzer
  stateless-test shard (`enable_analyzer = 0`). Moved that one query to its own
  section guarded by `SET enable_analyzer = 1`, keeping dual-analyzer coverage
  for the rest of the test. This was the reproducible CI failure:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111151&sha=c80cbfdc6f5f07baff40fd25d1302b3f2fe1de99&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29

- Added a regression test for an `INSERT`-scoped `WITH` staying visible across
  pipe stages with `enable_global_with_statement = 0`.

- Added a regression test for a post-`FROM` column alias list in the FROM-first
  form, before and instead of an explicit `SELECT` clause.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
auto select = make_intrusive<ASTSelectQuery>();
/// The children are added in the same order as in ParserSelectQuery,
/// because it is checked when the formatted AST is parsed back.
if (with_clause)

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.

This wrapper now preserves WITH, but it still leaves any SELECT ... SETTINGS ... on the query that just became a subquery. That breaks piped queries which set enable_analyzer or allow_experimental_analyzer before the first |>: InterpreterSetQuery::applySettingsFromQuery only applies settings from the outermost / last first-order SELECT, while validateAnalyzerSettings rejects the nested setting as a subquery override.

For example, SELECT number FROM numbers(1) SETTINGS enable_analyzer = 0 |> LIMIT 1 will now throw INCORRECT_QUERY (Setting 'enable_analyzer' is changed in the subquery) instead of behaving like the original top-level query with one extra pipe stage. The first pipe wrapper needs to preserve the effective query settings at the top level as well, or at least hoist the analyzer-setting pair out of the subquery before validation runs. A focused regression test for ... SETTINGS enable_analyzer = 0 |> ... would pin this down.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This particular example does not matter. Please don't complicate the code for that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

On the broadened form of this finding ("ordinary query settings such as max_threads are silently dropped after the first pipe stage") — that part is not the case. The SETTINGS clause stays on the query that becomes a subquery, and settings of a subquery are applied when that subquery is interpreted, exactly as for a hand-written nested query. Checked on this branch:

SELECT count() FROM numbers(10) SETTINGS max_rows_to_read = 5 |> LIMIT 1
Code: 158. Limit for rows (controlled by 'max_rows_to_read' setting) exceeded, max rows: 5.00, current rows: 10.00. (TOO_MANY_ROWS)

which is the same behavior as SELECT count() FROM (SELECT * FROM numbers(10) SETTINGS max_rows_to_read = 5). The only settings that behave differently are the analyzer toggles, which validateAnalyzerSettings rejects in a subquery — that is exactly the example the author dismissed above, so no change here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Taken the verdict's alternative action: the limitation is now documented and pinned by tests in e1a3784.

pipe-operators.md notes that a SETTINGS clause before the first pipe operator stays on the query that becomes a subquery; ordinary settings keep working (they are applied when that subquery is interpreted), and only enable_analyzer / allow_experimental_analyzer cannot be changed in a subquery, so those two must be written after the last pipe operator or passed outside the query.

04613_pipe_operators now asserts the exact parity with the hand-written nested form — both throw INCORRECT_QUERY:

SELECT number FROM numbers(1) SETTINGS enable_analyzer = 0 |> LIMIT 1;
SELECT * FROM (SELECT number FROM numbers(1) SETTINGS enable_analyzer = 0) LIMIT 1;
SELECT number FROM numbers(1) SETTINGS allow_experimental_analyzer = 0 |> LIMIT 1;

plus the positive side, that ordinary settings still take effect after piping (SETTINGS max_rows_to_read = 5 |> LIMIT 1 still throws TOO_MANY_ROWS). So piping does not change the meaning of a SETTINGS clause relative to writing the same nesting by hand — which is the contract this parser transformation is defined by. Verified under both analyzers.

Comment thread src/Parsers/ParserPipeOperators.cpp Resolved
Comment thread src/Parsers/ParserInsertQuery.cpp Outdated
/// Clone the query-scoped WITH (written before INSERT) onto a SELECT generated for a FROM-first or pipe
/// query, and onto every pipe wrapper it nests. Pipe operators wrap the query into `SELECT ... FROM (inner)`,
/// so a WITH attached only to the outermost SELECT is not visible in the inner stages when
/// `enable_global_with_statement = 0`. Spreading it down the chain keeps the aliases and CTEs visible in

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Why do we care about enable_global_with_statement = 0? I think it worked perfectly without this logic.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right — with the default enable_global_with_statement = 1 the WITH propagates to the inner stages during interpretation anyway. Reverted to the same logic as on master (the WITH is attached only to the outermost generated SELECT) in e2eab03 and removed the enable_global_with_statement = 0 case from the test.

alexey-milovidov and others added 2 commits July 22, 2026 12:24
- Revert `spreadWithOntoPipeStages` and keep the `INSERT`-scoped `WITH`
  only on the outermost generated `SELECT`, as on master. Per review,
  making the inner pipe stages independent of
  `enable_global_with_statement` is not worth the extra code.

- Clone the `CTE_ALIASES` sidecar together with the `WITH` clause in
  `wrapQueryIntoSelect`. `ParserSelectQuery` keeps CTE column alias
  lists (`WITH t(a) AS ...`) in that separate child, so without it the
  reparsed formatted query had a different tree hash and threw the
  debug-only `Inconsistent AST formatting` exception.

- The old analyzer does not support column alias lists on subqueries
  (`AS o (name, total)` threw `UNKNOWN_IDENTIFIER`) and expands
  asterisks in `EXPLAIN SYNTAX` output, which made the test fail on the
  old-analyzer shard:
  https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111151&sha=dda2fe845b20b51d4f78fc8c9cf1d5c30767629e&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29
  Move those sections under `SET enable_analyzer = 1`.

#111151

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
Comment thread src/Parsers/ParserPipeOperators.cpp Resolved
alexey-milovidov and others added 2 commits July 23, 2026 02:24
…fore a pipe operator

The `|> UNION`/`INTERSECT`/`EXCEPT` branch parses each operand with
`ParserUnionQueryElement`, which stops an unparenthesized operand before
a following `|>`, so the next pipe operator was silently applied to the
whole set operation instead of the last operand. Now a pipe operator
after an unparenthesized operand is a syntax error, and the user has to
write parentheses to disambiguate.

Co-Authored-By: Claude Fable 5 <[email protected]>
… explicitly in the FROM-first form

The FROM-first entrypoint disabled aliases without the `AS` keyword
for the whole `FROM` clause, so forms like `FROM orders o SELECT o.customer`
failed even though the same aliases are accepted in an ordinary
`SELECT ... FROM ...`. The restriction is needed only when the `SELECT`
clause is omitted: otherwise a following clause keyword that is a valid
alias (e.g. `SELECT` itself) would be mistaken for an alias. Now the
tables are first parsed with the normal alias rules, and that parse is
kept when an explicit `SELECT` follows.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
Comment thread src/Parsers/ParserPipeOperators.cpp Resolved
alexey-milovidov and others added 3 commits July 23, 2026 09:37
… table is sampled with an offset

In `FROM t SAMPLE 1/10 OFFSET 5` the `OFFSET` has already been consumed
as the `SAMPLE` offset by `ParserTablesInSelectQuery`, while in the
explicit form `FROM t SAMPLE 1/10 SELECT * OFFSET 5` it is a query-level
`OFFSET` (the formatter of `ASTSelectQuery` relies on the explicit form
to disambiguate exactly this shape). Require an explicit `SELECT` for it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…BY pipe operator

The `|> ORDER BY` operator parsed only `ParserOrderByExpressionList`, so
`ORDER BY ALL` and a trailing `INTERPOLATE` after `WITH FILL` did not
work like in the ordinary `ORDER BY` clause. The clause body parsing is
extracted from `ParserSelectQuery` into a shared `parseOrderByClauseBody`
and reused by the pipe operator.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only CI failure on 5f69b56 — AST fuzzer (amd_debug), signal 6 in printPipeline/getUniqID during dumpPipeline for a STREAM query — is unrelated to this PR (the crashing query contains no pipe operators). It is tracked in #110834, and a fix is already in progress: #110955.

Master gained `equalsCaseInsensitive(std::string_view, std::string_view)`
in `Common/StringUtils.h`, so the name is now overloaded and can no longer
be passed as a predicate to `std::equal`, which broke the `Fast test` and
`Build (arm_tidy)` builds:

    src/Parsers/ParserSelectQuery.cpp:158:12: error: no matching function for call to 'equal'

The new overload does exactly what the local helper did, so `isSelectKeyword`
now calls it directly instead of open-coding the comparison.
…TTINGS` clause before the first pipe operator

The `SETTINGS` clause of the query before the first pipe operator stays on
that query, which becomes a subquery of the generated wrapper. Ordinary
settings keep working, because settings of a subquery are applied when that
subquery is interpreted; only `enable_analyzer` and its alias
`allow_experimental_analyzer` cannot be changed in a subquery.

Per the review verdict's alternative action, the limitation is now documented
in `pipe-operators.md` and pinned by tests in `04613_pipe_operators`, which
also assert that the piped form and the equivalent hand-written nested form
fail identically, and that ordinary settings such as `max_rows_to_read` still
take effect after piping.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The two CI reds on 13d2b02aaf2 (Fast test and Build (arm_tidy)) were the same build break, caused by master rather than by this branch: master gained a equalsCaseInsensitive(std::string_view, std::string_view) overload in Common/StringUtils.h (#e92862a3536), so the name became overloaded and could no longer be passed as a predicate to std::equal:

src/Parsers/ParserSelectQuery.cpp:158:12: error: no matching function for call to 'equal'

The new overload does exactly what the local helper did, so isSelectKeyword now calls it directly. Merged master (2869 commits behind, zero conflicts), rebuilt clickhouse clean, and re-ran 04613_pipe_operators — identical output under both analyzers.

Also addressed the remaining AI-review Major by its alternative action (documented + pinned by a test); see the thread on ParserPipeOperators.cpp.

Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
Comment thread src/Parsers/ParserPipeOperators.cpp Resolved
… in the pipe-side FROM operator

Two findings of the AI review on `e1a3784d23f`:

- `ParserSelectQuery`: the guard that requires an explicit `SELECT` for a
  sampled table with an offset rejected every omitted-`SELECT` query with any
  sampled table expression, including unambiguous ones such as
  `FROM sampled SAMPLE 1 OFFSET 0 WHERE id > 8` or
  `FROM sampled SAMPLE 1 OFFSET 0 JOIN dim USING (id)`. The ambiguity exists
  only for the sample offset that ends the tables parse, and only when the
  query does not continue with a clause that a query-level `OFFSET` cannot
  precede, so the check now keys off the last top-level table expression and
  the token that follows the tables.

- `ParserPipeOperators`: the `FROM`-clause operator returned a syntax error for
  a leading comma before `ParserTablesInSelectQueryElement` could parse it, so
  the comma spelling of a cross join was unavailable in the first join
  position, even though `SELECT * FROM (SELECT * FROM lhs), rhs` is valid. The
  early return is removed; the existing `ARRAY JOIN` guard still rejects the
  genuinely ambiguous case.

Tests and documentation are updated accordingly.
Master removed the legacy Docusaurus docs tree (docs/en/). Resolved by
accepting the deletion and porting the pipe operators documentation to the
live Mintlify tree: docs/reference/statements/select/pipe-operators.mdx
(registered in docs/reference/navigation.json), with the corresponding
notes in from.mdx and index.mdx.
A query generated by a pipe operator can now end with a SETTINGS clause,
attached to the generated wrapper SELECT, the same as in the equivalent
hand-written nested form. Previously the trailing SETTINGS token was left
for the caller, which only worked on the top-level ParserQueryWithOutput
path, so a trailing SETTINGS was a syntax error in a subquery, CREATE VIEW,
or the view table function, and in INSERT ... SELECT it could be
reinterpreted as INSERT-level settings.

SETTINGS is inserted before INTERPOLATE in the order of children of the
generated ASTSelectQuery, matching ParserSelectQuery, because the order is
checked when the formatted AST is parsed back.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status on d1e4522ac1e: both reds are AST fuzzer findings on queries without any pipe operators, unrelated to this parser-only PR:

  • AST fuzzer (arm_asan_ubsan): Logical error: Can't determine table for parallel replicas on an ANY RIGHT JOIN with clusterAllReplicas on the right side — tracked open issue Logical error 'Can't determine table for parallel replicas' for RIGHT JOIN whose right side has no eligible table #113292 (findParallelReplicasQuery.cpp:630, decision path vs build path disagree for RIGHT JOIN).
  • AST fuzzer (amd_debug, targeted, old_compatibility): Logical error: Bad cast from type DB::ColumnString to DB::ColumnLowCardinality in MergeTreeDataSelectExecutor::markRangesFromPKRange during PK index analysis, on SELECT count() FROM (SELECT customer FROM remoteSecure(..., view(SELECT * FROM merge(...))) UNION ALL SELECT 'bob') WHERE 'bob' = customer — the header declares the column as String while the underlying table's PK column is LowCardinality(String), same family as the KeyCondition-over-Merge issues, but I found no exact tracked issue for this signature.

@groeneai, investigate the second failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111151&sha=d1e4522ac1e6be2b99c2e1c64306c2a6db04a2f9&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29 and provide a fix in a separate PR. If a fix is already in progress, link it here.

Meanwhile this PR was updated: merged master (resolving the docs conflict from the legacy docs/en tree removal by porting the pipe operators documentation to docs/reference/statements/select/pipe-operators.mdx + navigation.json), and the AI-review Major about trailing SETTINGS after a pipe chain in embedded contexts is fixed in 01eb67e52fb.

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator

Fix already in progress: #110326.

That PR owns this exact signature, not just the same family. The report's stack goes typeid_cast.h:22 -> FunctionsConversion.cpp:2821 (the prepareUnpackDictionaries lambda) -> KeyCondition.cpp:1593, which is the func->execute call in applyFunction's cache-miss branch, and that is precisely the code #110326 rewrites.

Minimal reproducer, no fuzzer and default settings:

CREATE TABLE t_lc (customer LowCardinality(String)) ENGINE = MergeTree ORDER BY customer;
CREATE TABLE t_s  (customer String)                 ENGINE = MergeTree ORDER BY customer;
INSERT INTO t_lc SELECT toString(number % 97) FROM numbers(1000);
INSERT INTO t_s  SELECT toString(number % 97) FROM numbers(1000);
CREATE TABLE m_lc (customer LowCardinality(String)) ENGINE = Merge(currentDatabase(), '^t_(lc|s)$');
SELECT count() FROM (SELECT customer FROM m_lc UNION ALL SELECT 'bob') WHERE 'bob' = customer;

On master (91687a7d610e, amd_debug) this hits the logical error at the frames above, on a real server as well as in clickhouse local. With the build_amd_debug artifact from #110326 it returns 1. Both index-analysis paths reproduce and both are fixed: use_lightweight_primary_key_index_analysis = 0 gives checkInHyperrectangle at :5529, the frame in the report, and = 1 gives :5970.

One correction to the diagnosis: the direction is the reverse. The failing shape is a Merge header declaring LowCardinality(String) over a plain String source part, which is what the error text says, since the cast wrapper is built for LowCardinality from the header and then handed a full ColumnString from the plain part. The inverse (header String, source LowCardinality(String)) returns 1 on master. remoteSecure, view and merge(REGEXP(...)) are not needed; they only supplied the supertype cast that the UNION ALL produces on its own.

#110326 is 1230 commits behind master, so I checked that its green arm is the fix and not its base: applyFunctionForField, applyFunction and applyMonotonicFunctionsChainToRange are byte-identical between its merge base and master, so neither carrier changed in between.

It is mergeable and still unreviewed. Note that #111050 rewrites the same cache branch a different way for a nested-CAST variant, so whichever is reviewed first will need a rebase of the other.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both CI failures on 01eb67e52fb are unrelated to this PR (neither failing query contains pipe operators):

The AI Review verdict on the current head is ✅ with no remaining findings; the three unresolved threads are the settled/documented ones.

- A `SETTINGS` clause of the query before the first pipe operator stays on that query, which becomes a subquery of the generated wrapper. Ordinary settings keep working, because settings of a subquery are applied when that subquery is interpreted. The only exception is the pair of settings that select the query analyzer, `enable_analyzer` and its alias `allow_experimental_analyzer`: changing them in a subquery is not allowed, so `SELECT number FROM numbers(1) SETTINGS enable_analyzer = 0 |> LIMIT 1` throws `INCORRECT_QUERY` — exactly as the equivalent hand-written `SELECT * FROM (SELECT number FROM numbers(1) SETTINGS enable_analyzer = 0) LIMIT 1` does. Write these two settings after the last pipe operator, or pass them outside of the query.
- Pipe operators bind to the whole query before them, including set operations: in `SELECT 1 UNION ALL SELECT 2 |> AGGREGATE count()`, the aggregation is applied to the result of the `UNION ALL`. To continue a query with `UNION` after a pipe operator, use the `|> UNION` operator or parentheses.
- Pipe operators can be used everywhere a `SELECT` query is expected: in subqueries, in `INSERT ... SELECT` (including the form `INSERT INTO t FROM src |> ...`), in `CREATE VIEW`, in the `view` table function, and so on.
- The renaming of columns in place is not provided as a separate operator; use `|> SELECT * EXCEPT (old_name), old_name AS new_name` or the `SET` and `DROP` operators.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Can we write REPLACE instead of EXCEPT?

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM. The code is well structured and well-contained. The implementation is even somewhat elegant.

@alexey-milovidov alexey-milovidov self-assigned this Aug 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 11, 2026
Merged via the queue into master with commit 529df9d Aug 11, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the pipe-syntax branch August 11, 2026 23:18
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 12, 2026

This branch was successfully deployed

1 active deployment
staging - docs — 5d70225a Deployed Aug 5, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature 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.

SQL with pipes

3 participants