Repository navigation
Pipe operators in SQL queries - #111151
Conversation
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [5d70225] Summary: ✅
AI ReviewSummaryThis PR adds Final Verdict✅ No new review findings on the current head. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 424/486 (87.24%) · Uncovered code |
…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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
This particular example does not matter. Please don't complicate the code for that.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
| /// 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 |
There was a problem hiding this comment.
Why do we care about enable_global_with_statement = 0? I think it worked perfectly without this logic.
There was a problem hiding this comment.
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.
- 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]>
…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]>
… 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]>
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.
|
🕵 The two CI reds on The new overload does exactly what the local helper did, so Also addressed the remaining AI-review Major by its alternative action (documented + pinned by a test); see the thread on |
… 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.
|
🕵 CI status on
@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 |
|
Fix already in progress: #110326. That PR owns this exact signature, not just the same family. The report's stack goes 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 ( One correction to the diagnosis: the direction is the reverse. The failing shape is a Merge header declaring #110326 is 1230 commits behind master, so I checked that its green arm is the fix and not its base: 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. |
|
🕵 Both CI failures on
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. |
There was a problem hiding this comment.
Can we write REPLACE instead of EXCEPT?
alexey-milovidov
left a comment
There was a problem hiding this comment.
LGTM. The code is well structured and well-contained. The implementation is even somewhat elegant.
Closes: #69364
Related: #73394
Changelog category (leave one):
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. AnySELECTquery 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 theFROMclause, theSELECTclause is now optional and defaults toSELECT *.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:is parsed into the same AST as
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 ofJOIN, includingARRAY JOIN. Pipe operators work everywhere aSELECTquery is expected: in subqueries,INSERT ... SELECT(including the formINSERT INTO t2 FROM t1 |> ...),CREATE VIEW, theviewtable function,EXPLAIN, and so on. Since every operator is a subquery scope, table aliases are visible only within the same operator (e.g. in theONcondition of a join) - this is a difference from GoogleSQL, which keeps table aliases visible across operators.The implementation is a new
TokenType::PipeOperatorfor|>in the lexer and theparsePipeOperatorsfunction invoked fromParserSelectWithUnionQueryafter the union list; each operator parses its clauses with the existing expression parsers and constructs the wrappingASTSelectQuery. 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
Version info
26.8.1.1189(included in26.8and later)