Skip to content

Add minimal INSERT ... RETURNING (SELECT ...) - #126476

Merged
alexey-milovidov merged 8 commits into
masterfrom
insert-returning-minimal
Oct 24, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
insert-returning-minimal

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Closes: #21697 Closes #5912
Related: #105714

A minimal implementation of INSERT ... RETURNING, a much simpler replacement for #105714.

INSERT INTO t (x) RETURNING (SELECT id, x) VALUES (1), (2);
INSERT INTO t RETURNING (SELECT count(), max(x) FROM t) SELECT ... FROM src;
INSERT INTO FUNCTION s3(...) RETURNING (SELECT count()) SELECT ...;

The RETURNING (SELECT ...) clause goes right after the list of columns (before the data, because everything after VALUES/FORMAT is data). It runs the SELECT on top of the inserted blocks: inside it, the destination table refers to the stream of data being written into the table, after the omitted columns are filled with defaults. So it returns, for example, generated values such as DEFAULT generateUUIDv4() exactly as they were written. Without FROM, the SELECT reads the inserted data too (via implicit_table_at_top_level), which is also the way to refer to the data inserted into a table function. Deduplication and other transformations inside the table engine are not taken into account.

Implementation:

  • InsertDependenciesBuilder optionally puts a ForkProcessor into the chain of every insert stream, right before the sink of the destination table. The copies are merged by a ResizeProcessor.
  • The whole insert pipeline, with this extra output, becomes a Pipe. The RETURNING query reads it through a StorageValues set as the view source, the same way a materialized view reads the inserted blocks. The data is streamed and not accumulated in memory. If the RETURNING query doesn't read the table (e.g. SELECT 1 FROM system.one), the insert still runs as a completed pipeline. If it reads the table twice, it throws NOT_IMPLEMENTED.
  • Data inside the query or in the HTTP request body is read by the server as usual.
  • Data sent separately by the client over the native protocol (VALUES parsed by clickhouse-client, stdin, FROM INFILE, input) is read inside the pipeline with the existing input callbacks, and the result is streamed to the client while it is still sending the data. clickhouse-client reads the result packets between sending the blocks and before EndOfStream. To avoid a deadlock when both sides block on writing to full socket buffers, TCPHandler sends the result without callback_mutex (held by the thread reading the data) until all the data is received, and doesn't accept Ping in this phase.
  • This is gated by a new protocol revision 54495 (DBMS_MIN_REVISION_WITH_INSERT_RETURNING): older clients get NOT_IMPLEMENTED instead of unexpected packets. The spec of the native protocol is updated. clickhouse-local works as well.
  • The input initializer callback now takes the columns description and the header instead of a storage, so the insert sends the full table columns (for defaults) with the insert sample block, as an ordinary INSERT does.
  • The async_insert setting is ignored for such queries, and parallel distributed INSERT SELECT is not used.
  • The RETURNING query can't read the inserted data during the analysis (in a scalar subquery or EXISTS), because that would run the insert before the query is built: this throws NOT_IMPLEMENTED. For EXPLAIN PIPELINE, the RETURNING query reads an empty block, and the insert is not executed.
  • Destinations which read from other tables (Alias, Distributed, Buffer with a destination) are rejected with NOT_IMPLEMENTED, because the access checks and row policies of the underlying tables would not apply to the substituted data stream.

RETURNING is not added to the list of reserved keywords.

Changelog category (leave one):

  • New Feature

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

Add INSERT INTO t ... RETURNING (SELECT ...), which runs a SELECT on top of the inserted data and streams its result while the data is being inserted, e.g. to get the values of columns generated on insertion. Inside the SELECT, the destination table (or the absence of FROM) refers to the inserted data.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.707-master (included in 26.11 and later)

The `RETURNING` clause specifies a `SELECT` query, which runs on top of the
inserted blocks: inside it, the destination table refers to the stream of
the data written into the table (after the defaults are filled). The INSERT
pipeline is forked right before the sink of the destination table, and the
copy of the data is the source of the `RETURNING` query, the same way as a
materialized view reads the inserted blocks. Deduplication and other
transformations inside the table engine are not taken into account.

It is supported for `INSERT SELECT` and for `INSERT` with the data inlined
into the query or in the HTTP request body. `clickhouse-client` sends the
data inline with the query when there is `RETURNING`.

This is a simpler replacement for #105714

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

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3891de3]

Summary: ✅


AI Review

Summary

Adds INSERT ... RETURNING (SELECT ...) to stream results computed from inserted blocks, including generated defaults, with native-client and clickhouse-local support. Reviewed commit 3891de3d9d43eee4d87f743a8aa1909c2a996b8e. Previously reported issues are addressed in the current code; no additional actionable findings remain.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Oct 17, 2026
Comment thread src/Storages/StorageValues.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3891de3d9 with master bb0fc9fd4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 7fc386e15; 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

425 object files changed (+166.33 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InterpreterInsertQuery.cpp.o 578.53 KiB 615.50 KiB +36.97 KiB (+6.39%)
src/CMakeFiles/dbms.dir/Storages/StorageValues.cpp.o 269.65 KiB 305.82 KiB +36.18 KiB (+13.42%)
src/CMakeFiles/dbms.dir/Client/LocalConnection.cpp.o 361.50 KiB 393.59 KiB +32.09 KiB (+8.88%)
src/CMakeFiles/dbms.dir/Analyzer/Utils.cpp.o 545.21 KiB 568.59 KiB +23.38 KiB (+4.29%)

719 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

1956 translation units recompiled, 11641 s compile time in total, 1955 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.3 s

Job report

…ately

When `clickhouse-client` sends the data of an INSERT separately from the
query (from stdin, `FROM INFILE`, or `VALUES` parsed by the client), the
server reads it inside the pipeline with the `input` callbacks, and sends
the result of the `RETURNING` query while the client is still sending the
data. The client reads the result between sending the blocks, and before
`EndOfStream`.

To avoid a deadlock when both sides block on writing to a full socket, the
server sends the result without `callback_mutex` (which is held by the
thread reading the data) until all the data is received.

This is gated by the new protocol revision 54495
(`DBMS_MIN_REVISION_WITH_INSERT_RETURNING`); older clients get
`NOT_IMPLEMENTED` instead of unexpected packets. The input initializer now
takes the columns description and the header instead of a storage, so the
insert can send the full table columns (for defaults) with the insert
sample block, as for an ordinary INSERT.

The `RETURNING` query is run with `implicit_table_at_top_level` set to the
destination, so it can be written without `FROM`, which is also the way to
read the data inserted into a table function (`INSERT INTO FUNCTION`).

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

mintlify Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 21, 2026, 5:23 AM

alexey-milovidov and others added 3 commits October 18, 2026 17:32
In the flaky check, `05401_insert_returning` (debug) and `05402_insert_returning_client` (ASan)
took more than 180 seconds. The queries did not hang: the inserts with hundreds of tiny blocks
created hundreds of parts each, and the insert of 3 million rows from stdin was starved of CPU
on the loaded machine (`OSCPUWaitMicroseconds` was 93 seconds of 182). Insert ten times less data,
and write the large insert into the `null` table function. It still sends many blocks while
receiving a result much larger than the socket buffers.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126476&sha=86ab9be4ed2881ec7682cda20b1c0565cfa38b22&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126476&sha=86ab9be4ed2881ec7682cda20b1c0565cfa38b22&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#126476

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…other tables in `INSERT ... RETURNING`

- `EXPLAIN PIPELINE` of `INSERT ... RETURNING` could run the insert while building the `RETURNING`
  query, e.g. to evaluate a scalar subquery. Now the `RETURNING` query reads an empty block for
  `EXPLAIN`, and the insert is added as a separate pipeline, which is not executed.
- A scalar subquery or `EXISTS` reading the inserted data ran the whole insert during the analysis,
  and the query then failed after the data was written. Reading the inserted data during the
  analysis now throws `NOT_IMPLEMENTED` before anything is executed.
- Subcolumns (`JSON` paths, tuple elements, `size0`, `null`) of the inserted data threw
  `NOT_FOUND_COLUMN_IN_BLOCK`, because the pipe has only the physical columns. They are extracted
  with `getSubcolumn` now.
- For a destination which reads from other tables (`Alias`, `Distributed`, `Buffer`), the
  `RETURNING` query skipped the access checks and the row policies of those tables. Such
  destinations are rejected with `NOT_IMPLEMENTED`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit to scanhex12/ClickHouse that referenced this pull request Oct 20, 2026
Since ClickHouse#124907 the test runner randomizes `max_bytes_before_external_set`
and `max_bytes_ratio_before_external_set`. When the threshold is below
what the set collects before the test's 0.1 s limit, the set goes to
disk, and the disk set builder throws `QUERY_WAS_CANCELLED` in the
`break` mode by design (`05401_external_set_cancellation`). The test
checks the quiet stop of the in-memory set, so clamp both thresholds to
0 for it with `Random settings limits`; every other setting stays
random.

Failed in "Stateless tests (arm_binary, AsyncInsert, s3 storage,
parallel)" on PR ClickHouse#126476 with `--max_bytes_before_external_set 8556090`
(127/128 reruns with the same settings failed).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 21, 2026 03:15
…RNING`

- Reject materialized-view destinations too: the `RETURNING` query reads the inserted
  stream instead of the view, so the read authorization of its target would not apply.
- Do this check after the `INSERT` access check of the destination, so the engine is not
  reported to a user without access to the table.
- Do not require `SELECT` on the synthetic `_table_function.*` name for the data inserted
  into a table function; the access to the table function is checked when it is executed,
  and the tables read by the `RETURNING` query are still checked.
- Keep the combined pipeline single-threaded when the insert pushes to dependent
  materialized views sequentially (`parallel_view_processing = 0`).

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

The `input` initializer of `LocalConnection` always read the data from stdin,
and the client skipped its own reader of the file, so the file was silently
ignored. Read the file in the initializer with `StorageFile`, the same way as
`ClientBase::sendData` does (globs, compression, the format from the file name).

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

@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.

All good.

@alexey-milovidov alexey-milovidov self-assigned this Oct 24, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 24, 2026
Merged via the queue into master with commit 1d30ce2 Oct 24, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the insert-returning-minimal branch October 24, 2026 02:32
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 27, 2026
…el-replicas

Resolve the conflict in the input() blocks reader callback of TCPHandler.cpp:
keep master's received_all_data_for_input writes (INSERT ... RETURNING, ClickHouse#126476)
and this PR's killQueryIfStoppedByClient call after callback_mutex is released.

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

Copy link
Copy Markdown
Member

@alexey-milovidov should this be experimental and be disabled with a setting at the moment?

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

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. 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.

INSERT ... RETURNING clause INSERT AND SELECT query (RFC)

3 participants