Skip to content

LIMIT ... AFTER/UNTIL to return rows between boundary conditions - #99508

Merged
nihalzp merged 99 commits into
ClickHouse:masterfrom
zakr600:limit_after
Sep 8, 2026
Merged

nihalzp merged 99 commits into
ClickHouse:masterfrom
zakr600:limit_after

Conversation

@zakr600

@zakr600 zakr600 commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #15341

Adds a range form of LIMIT that selects rows by boundary conditions instead of by position:

LIMIT [n] AFTER start_expr [UNTIL end_expr]
LIMIT [n] AFTER start_expr ALL [UNTIL end_expr]
LIMIT [n] UNTIL end_expr

AFTER start_expr starts the output at the first row where start_expr is true (inclusive); UNTIL end_expr stops before the first row where end_expr is true (exclusive); the optional n caps the length of the opened range. AFTER ... ALL opens a new range at every matching row and returns their union without duplicating overlapping rows, so n is the length of each range. "First" is defined by stream order, so ORDER BY controls it; without ALL, an UNTIL match before the first AFTER match yields an empty result. Boundary expressions may reference columns that are not selected.

This answers questions like "give me the rows from the first error until the next checkpoint" or "N rows after every marker" in one pass over an ordered stream, where today users either post-filter with window functions or fetch everything and cut client-side.

Changelog category (leave one):

  • New Feature

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

New LIMIT forms that select rows by boundary conditions instead of by position, following the stream order (use ORDER BY to define it): LIMIT n AFTER cond returns up to n rows starting at the first row where cond is true (SELECT number FROM numbers(10) ORDER BY number LIMIT 3 AFTER number >= 5 returns 5, 6, 7); LIMIT UNTIL cond returns the rows before the first row where cond is true (LIMIT UNTIL number >= 3 returns 0, 1, 2); LIMIT AFTER cond1 UNTIL cond2 returns the rows between the two (LIMIT AFTER number >= 2 UNTIL number >= 6 returns 2, 3, 4, 5); LIMIT n AFTER cond ALL opens a range of n rows at every matching row and returns their union without duplicates (LIMIT 2 AFTER number IN (2, 6) ALL returns 2, 3, 6, 7).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@zakr600

zakr600 commented Mar 14, 2026

Copy link
Copy Markdown
Contributor Author

implements this #15341 (comment)

@EmeraldShift

Copy link
Copy Markdown
Contributor

Does this return N rows after every occurrence of the condition, or only the first? It would be cool to have a variant LIMIT N AFTER ... ALL that included all of them, similar to grep -A

@zakr600

zakr600 commented Mar 14, 2026

Copy link
Copy Markdown
Contributor Author

Does this return N rows after every occurrence of the condition, or only the first? It would be cool to have a variant LIMIT N AFTER ... ALL that included all of them, similar to grep -A

Only after the first.
I'll try to add support for [ALL] in the future.

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

clickhouse-gh Bot commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8397fda]

Summary: ✅


AI Review

Summary

This PR adds LIMIT ... AFTER/UNTIL range selection and closes most of the earlier correctness gaps, but the current head still has one new blocker in the boundary-expression arrayJoin rejection and one author-dismissed StorageMerge rewrite bug that remains user-visible in the branch.

Findings

❌ Blockers

  • [src/Planner/PlannerExpressionAnalysis.cpp:669] The new LIMIT AFTER/UNTIL arrayJoin guard still does exact-name matching, so the official alias unnest bypasses it on the analyzer path; the sibling legacy AST check at src/Interpreters/ExpressionAnalyzer.cpp:1870 has the same alias hole, and the AST path also still misses SQL UDF wrappers. That lets a row-multiplying boundary expression reach LimitRangeStep, breaking the 1:1 row correspondence the feature relies on and potentially returning wrong rows. Suggested fix: canonicalize function names for the query-tree check, switch the AST check to expressionContainsArrayJoin, and add unnest regressions for both analyzers.
  • [src/Storages/StorageMerge.cpp:1495-1518] [dismissed by author -- https://github.com/LIMIT ... AFTER/UNTIL to return rows between boundary conditions #99508#discussion_r3950646764] replaceTableExpressionAndRemoveJoin still clears GROUP BY / LIMIT BY / ORDER BY clauses without clearing the remaining analyzer-side modifier flags (WITH TOTALS / ROLLUP / CUBE / multi-set GROUPING SETS / LIMIT BY ALL). That is still user-visible on the current head as the exception reproduced in Fix NOT_IMPLEMENTED for Merge over Distributed with a JOIN and a GROUP BY modifier #118658. Being pre-existing on master does not make the bug disappear for this PR head; the branch still ships it unless the fix is merged first or included here.
Tests
  • ⚠️ Add a focused stateless regression that rejects unnest in LIMIT AFTER / LIMIT UNTIL under both analyzers. The current suite only covers literal arrayJoin in tests/queries/0_stateless/04354_limit_after_reject_array_join.sql.
Final Verdict

❌ Not ready to merge: the new boundary-expression validation still lets unnest bypass the arrayJoin ban, and the branch still contains the unresolved StorageMerge rewrite bug tracked in #118658.

LLVM Coverage Report

Measured on commit 8397fda.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 1251/1323 (94.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 15, 2026
Comment thread src/Processors/LimitRangeTransform.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
@nihalzp nihalzp self-assigned this May 22, 2026
Comment thread src/Processors/LimitRangeTransform.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8397fda69 with master 55c256363 (stripped binary size, per-symbol sizes and ThinLTO time; 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

123 object files changed (+353.89 KiB total), 3 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/LimitRangeStep.cpp.o new 133.48 KiB +133.48 KiB
src/CMakeFiles/dbms.dir/Processors/LimitRangeTransform.cpp.o new 113.07 KiB +113.07 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/ChunkRowRange.cpp.o new 23.45 KiB +23.45 KiB
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o 765.71 KiB 787.97 KiB +22.26 KiB (+2.91%)

716 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

1051 translation units recompiled, 6645 s compile time in total, 1048 of them have a recent master baseline.

Job report

Comment thread src/Storages/StorageMerge.cpp Resolved
@nihalzp
nihalzp added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit f820a49 Sep 8, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 19, 2026
Reading a Merge table that matches a Distributed table with a JOIN and a
GROUP BY ... WITH TOTALS/ROLLUP/CUBE/GROUPING SETS failed outright:

  Code: 48. DB::Exception: WITH TOTALS, ROLLUP, CUBE or GROUPING SETS are not
  supported without aggregation: Child table: default.d. (NOT_IMPLEMENTED)

replaceTableExpressionAndRemoveJoin builds a separate query for each matched
child table. It clears the GROUP BY, ORDER BY and LIMIT BY node lists, because
they may reference the JOIN it removes, and it replaces the projection with
plain column identifiers, which drops the aggregate functions. It did not reset
the modifier flags belonging to those clauses, so the child query was left with
no GROUP BY keys and no aggregates while still carrying WITH TOTALS. When the
child is a Distributed table that tree is re-analyzed and validateAggregates
rejects it. The child query the rewrite produced is visible in the server log as:

  SELECT `__table1`.`a` AS `a` FROM `t_99508` AS `__table1` WITH TOTALS

The old-analyzer twin of this rewrite, removeJoin in
getHeaderForProcessingStage.cpp, already resets all seven of these flags, which
is why enable_analyzer = 0 was unaffected. This mirrors it, in the same spirit
as the is_limit_with_ties reset the function already performs for the same
reason: a clause modifier flag must not outlive the clause it modifies.

WITH TOTALS, WITH ROLLUP, WITH CUBE, and GROUPING SETS with more than one
grouping set are the independently observable cases, reachable through JOIN,
ARRAY JOIN, GLOBAL JOIN and the merge() table function. A single-set
GROUPING SETS list is collapsed during resolution by
GroupingFunctionsResolvePass, which clears the flag with it, so only a multi-set
list survives to reach this rewrite. is_group_by_all, is_order_by_all and
is_limit_by_all are cleared during resolution, so they cannot be witnessed on
their own today; they are reset as well so that the two rewrites agree, and
because a surviving order_by_all with no ORDER BY list later dereferences a null
orderBy() in ASTSelectQuery. The AST side of that pair was fixed in ClickHouse#109139
and ClickHouse#113759.

Reported by Nihal Z. Miaji on ClickHouse#99508 as a pre-existing master bug.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-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.

LIMIT clause for matching a range of records based on boundary conditions.

7 participants