Repository navigation
Description
Spurious TOTALS block in the result of a non-aggregate SELECT when WHERE contains a correlated scalar subquery with GROUP BY ... WITH TOTALS
Summary
A top-level SELECT with no aggregation at all returns a totals block to
the client when its WHERE clause contains a correlated scalar subquery that
uses GROUP BY ... WITH TOTALS HAVING <expr over an outer column>.
The correlated-subquery decorrelation rewrites the scalar subquery into a
JOIN FillRightFirst whose left side contains a TotalsHaving step; the
totals block produced by that step propagates through the join into the
top-level pipeline and reaches the client as a totals row of the outer query.
The EXISTS decorrelation path already refuses this exact situation with
Code: 48. DB::Exception: Cannot decorrelate query, because 'TotalsHaving' step is not supported. (NOT_IMPLEMENTED) — the scalar-subquery path performs
the decorrelation anyway and produces the wrong output. Expected behaviour:
either reject like the EXISTS path, or decorrelate correctly without
leaking the subquery's totals into the outer result.
Found by the AST-fuzzer correctness oracle from PR
#99980 (TLP WHERE and
TLP DISTINCT oracles both trip on it: the partitioned query gains 2 extra
"rows" — the empty separator + totals row — versus the reference).
Minimal repro
CREATE TABLE t (id UInt32, val Int64) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, number * 7 FROM numbers(3);
SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0);$ clickhouse local --queries-file repro.sql
0
1
2
0 <-- spurious totals block; the outer query has no aggregation
In FORMAT JSONCompact the result object likewise contains a "totals"
field. Reproduced on 26.6.1.1 (master 76c2edca2fd, release build) via
both clickhouse local and server.
Notes on the shape:
HAVING isNull(val) = 0is load-bearing: it references the outer
columnval, making the subquery correlated. Without theHAVING, the
uncorrelated scalar is evaluated separately and nothing leaks.- A bare outer-column reference (
HAVING val >= 0) is rejected with
NOT_AN_AGGREGATE, which looks inconsistent —isNull(val)is accepted
wherevalis not — but that is a separate, minor concern. - The same shape inside
EXISTSerrors out instead of leaking:
SELECT id FROM t WHERE exists((SELECT 1 FROM t AS u WHERE u.id = t.id GROUP BY 1 WITH TOTALS))→NOT_IMPLEMENTED: Cannot decorrelate query, because 'TotalsHaving' step is not supported.
Plan (where the totals come from)
EXPLAIN PLAN SELECT id FROM t WHERE id >= (SELECT 0 GROUP BY 1 WITH TOTALS HAVING isNull(val) = 0);
Expression ((Project names + Projection))
Filter
Join (JOIN FillRightFirst)
Expression (Left Pre Join Actions)
Expression
Join (JOIN FillRightFirst)
Expression
TotalsHaving <-- subquery's totals step
Aggregating
Expression ((Before GROUP BY + Change column names to column identifiers))
ReadFromSystemOne
Filter
ReadFromCommonBuffer
Expression (Right Pre Join Actions)
BuildRuntimeFilter (Build runtime join filter on __table1.val)
SaveSubqueryResultToBuffer
Expression (Change column names to column identifiers)
ReadFromMergeTree (default.t)
Fix area
The correlated scalar-subquery decorrelation (planner, same place that emits
Cannot decorrelate query, because '...' step is not supported for the
EXISTS path — src/Planner/ correlated-subquery handling). Either add
TotalsHaving to the unsupported-step check for scalar subqueries as well,
or make the decorrelated join drop/contain the subquery's totals block so it
never reaches the outer query's output.
Original fuzzer hits (for reference)
- 2026-06-09 11:52:53, cycle 7 instance 03 (
TLP WHEREoracle), run dir
tmp/fuzz_lab/runs/20260602-1228-0979ce58972/inst/03/:
SELECT toString('...') FROM _s1 WHERE (d > (SELECT toLowCardinality(10) GROUP BY '\'', toInt256(-9223372036854775807), toNullable(-2147483649) WITH TOTALS HAVING isNull(g))) AND (toNullable(toLowCardinality(100)) <= d)
— reference 500 rows, partitioned 502. - 2026-06-09 21:07:02, cycle 8 instance 01 (
TLP DISTINCToracle), run dir
tmp/fuzz_lab/runs/20260609-1152-76c2edca2fd/inst/01/(run_284.log):
correlatedEXISTS+GROUP BY ... WITH TOTALSinsideor(...)—
reference 500 rows, partitioned 502.
Activity
qoega commentedon Jun 10, 2026
@groeneai could you please reproduce and fix this one? Repro is in the issue body — deterministic on master
76c2edca2fd, default settings.groeneai commentedon Jun 10, 2026
@qoega reproduced and fixed in #107075.
Root cause: correlated-subquery decorrelation rewrites the subquery into a JOIN, and
JoinSteppropagates totals from either input. When the correlated subquery's plan produces a totals stream (aTotalsHavingStepthat isn't consumed by an enclosingAggregatingStep, which would drop it), that totals stream leaked through the decorrelation join into the outer non-aggregate pipeline and reached the client as a spurious totals row.The existing
decorrelateQueryPlan"step not supported" throw only fires when theTotalsHavingstep is itself correlated. In your reproHAVING isNull(val) = 0puts thevalcorrelation into a separate Filter step, leavingTotalsHavingin a non-correlated subplan that gets wrapped wholesale, so it was never rejected. On current master theEXISTSvariant of your repro leaks the same way (it does not reject) — the rejection you observed happens only for the shape where the totals step itself is correlated.Fix: before decorrelating, walk the subquery plan and detect a
TotalsHavingStepreachable from the result without crossing anAggregatingStep; if found, reject withNOT_IMPLEMENTED, for both the scalar andEXISTSpaths (the option you suggested). A nestedWITH TOTALSconsumed by an enclosing aggregation, andWITH ROLLUP/WITH CUBE, are unaffected and keep working. Regression test04327_correlated_subquery_with_totalsadded.clickgapai commentedon Oct 8, 2026
Same defect reproduced during automated review of PR #124096 (ClickGap), current master.
Finding:
rewrite_in_to_jointotals fix skips views: leaked row andLOGICAL_ERRORReproducer
Expected:
Actual: