Repository navigation
LINQ: Count()/LongCount() after Take()/Skip() count the paged rows (Fixes #5920) - #5925
Merged
Merged
Conversation
…5920) Count()/LongCount() over a paged statement put the LIMIT/OFFSET on the count(*) itself, so Take(n).Count() returned the full count and Skip(k).Count() / Skip(k).Take(n).Count() returned 0. A paged counted statement is now wrapped in a CTE (keeping its ORDER BY, which decides the page) and the CTE is counted. Covers documents, Where, OrderBy, Select projections, SelectMany(...).Take/Skip, Take/Skip before SelectMany (the SUM(jsonb_array_length) shortcut now sums the page) and compiled queries. Take(0).Any() no longer widens LIMIT 0 to LIMIT 1. Unpaged counts send byte-identical SQL; Distinct()/GroupBy() counts already counted a CTE that carried the paging and are unchanged. Fixes #5920 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jeremydmiller
added a commit
that referenced
this pull request
Nov 15, 2026
[9.0] LINQ: Count()/LongCount() after Take()/Skip() count the paged rows (backport of #5925)
This was referenced Nov 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #5920.
Root cause
ProcessSingleValueModeIfAnyturns a counted statement intoselect count(*) ...by swapping its select clause for aCountClause, and it left the statement'sLimit/Offsetin place. The paging was therefore applied to the single row the aggregate returns:Take(n).Count():select count(*) ... LIMIT nreturns the full countSkip(k).Count()andSkip(k).Take(n).Count():OFFSET kskips the only row, so the count is 0SelectMany(x => x.Children).Take(n).Count(): the same, over the exploded CTEOrderBy(...).Take(n).SelectMany(x => x.Children).Count(): theSUM(jsonb_array_length(...))shortcut summed every document and then paged the SUM rowFix
In
CollectionUsage.Compilation.cs:tryCountPagedStatement<T>(): when the counted statement has aLimitorOffset, convert it to a CTE, keeping its ORDER BY because that decides which rows are on the page, and count the CTE. This is the same shape the join path already uses. Unpaged statements,Distinct()andGroupBy()are untouched: the last two already counted a CTE that carried the paging.sumCollectionLengths<T>(): the SelectMany SUM shortcut wraps paged parent rows in a CTE and sums over it.Any():Take(0).Any()keptLIMIT 0instead of widening it toLIMIT 1. It used to returntrue.SQL before / after (executed; CTE names normalized to
cte1/cte2)Take(3)select count(*) ... from mt_doc_x as d LIMIT $1WITH cte1 as (select d.data from mt_doc_x as d LIMIT $1) select count(*) as number from cte1 as dSkip(4)select count(*) ... OFFSET $1WITH cte1 as (select d.data from mt_doc_x as d OFFSET $1) select count(*) ... from cte1 as dSkip(4).Take(3)select count(*) ... OFFSET $1 LIMIT $2WITH cte1 as (select d.data ... OFFSET $1 LIMIT $2) select count(*) ... from cte1 as dOrderBy(Number).Skip(4).Take(3)select count(*) ... OFFSET $1 LIMIT $2(ORDER BY dropped)WITH cte1 as (select d.data ... order by CAST(d.data ->> 'Number' as integer) OFFSET $1 LIMIT $2) select count(*) ... from cte1 as dWhere(Number > 3).Take(3)select count(*) ... where ... > $1 LIMIT $2WITH cte1 as (select d.data ... where ... > $1 LIMIT $2) select count(*) ... from cte1 as dSelect(x => x.Number).Take(3)select count(*) ... LIMIT $1WITH cte1 as (select CAST(d.data ->> 'Number' as integer) ... LIMIT $1) select count(*) ... from cte1 as dSelectMany(Children).Take(3)WITH cte1 as (select jsonb_array_elements(...) as data ...) select count(*) from cte1 as d LIMIT $1WITH cte1 as (select jsonb_array_elements(...) ...), cte2 as (select d.data as data from cte1 as d LIMIT $1) select count(*) from cte2 as dSelectMany(Children).Where(Value > 1).Take(3)... select count(*) from cte1 as d where ... > $1 LIMIT $2... cte2 as (select d.data as data from cte1 as d where ... > $1 LIMIT $2) select count(*) from cte2 as dSelectMany(Tags).Take(3)(scalar)... select count(*) from cte1 as d LIMIT $1... cte2 as (select CAST(data as integer) as data from cte1 as d LIMIT $1) select count(*) from cte2 as dOrderBy(Number).Take(3).SelectMany(Children)select SUM(jsonb_array_length(d.data -> 'Children')) from mt_doc_x as d LIMIT $1WITH cte1 as (select d.data from mt_doc_x as d order by ... LIMIT $1) select SUM(jsonb_array_length(d.data -> 'Children')) from cte1 as dSelect(Color).Distinct().Take(2)WITH cte1 as (select DISTINCT(...) ... LIMIT $1) select count(*) ...GroupBy(...).Select(...).Take(2)WITH cte1 as (... GROUP BY ... LIMIT $1) select count(*) ...Take(0)withAny()select TRUE ... LIMIT 1select TRUE ... LIMIT 0Unpaged counts are byte-identical.
unpaged_count_sql_is_unchangedrecords the SQL each query actually executes and compares it with strings captured from master at1d13d0f3a. It covers 11 shapes: plain, Where, OrderBy, Where+OrderBy, Select, Distinct, SelectMany, SelectMany+Where, SelectMany scalar, SelectMany+Distinct and GroupBy. All 11 pass on master and with the fix.Skip(k).Any()withkpast the end was already correct (OFFSET k LIMIT 1).Tests
LinqTests/Bugs/Bug_5920_count_over_paged_queries.cs, 140 cases. Each shape'sCountAsync()andLongCountAsync()are compared against LINQ to Objects over the same 10 seeded documents. The shapes are Take, Skip, Skip+Take, OrderBy(+Descending)+Skip+Take, Where+Take, Where+OrderBy+Skip+Take, Select+Take, Select+Skip+Take, Distinct+Take, Distinct+Skip+Take, SelectMany+Take, SelectMany+Skip, SelectMany+Skip+Take, SelectMany+Where+Take, SelectMany scalar+Take, SelectMany+Distinct+Take, GroupBy+Take, Skip+Take+SelectMany and Skip+SelectMany. They run withnin {0, 1, 3, 10, 25} (25 > total) andkin {0, 1, 4, 10, 15} (past the end).Any()after Skip and after Skip+Take is covered too, as are the executed-SQL assertions above. The document type is declared inClearedBeforeEachTest.CompiledQueryTests/compiled_count_over_paged_queries.cs, 13 cases. A compiledWhere+OrderBy+Skip+Take+Count()and a compiledTake+LongCount(), each with several paging values, against LINQ to Objects. A test also asserts that both are served by the source-generated path.Red on master (fix reverted, same tests)
Bug_5920_count_over_paged_queries: 51 of 140 fail. Take, Skip, Skip+Take, OrderBy+Skip+Take, Where+Take, Select+Take, all four SelectMany-then-page shapes, both page-then-SelectMany shapes,Take(0).Any()and the paged-SQL assertion. Distinct+Take and GroupBy+Take pass on master, and so do all 11 unpaged-SQL cases.compiled_count_over_paged_queries: 5 of 13 fail.Full runs with the fix (Release, database
marten_10_m)The new LinqTests class was re-run after its SQL assertions moved from
ToCommand()to executed SQL: 140/140 on net10.0 and on net11.0.9.x
9.0 has the same bug. On a worktree from
origin/9.0(d824a8dcc), the same test class fails the same 51 behavioural cases. The fix cherry-picks cleanly onto branchfix/5920-take-skip-count-9.0(0e549e50b). That branch is red without the fix (51/140 LinqTests, 5/13 CompiledQueryTests) and green with it (full LinqTests on net10.0: 1809 run, 0 failed). Its CI run: https://github.com/JasperFx/marten/actions/runs/43732699500Not fixed here (separate, pre-existing)
OrderBy(...).Take(n).SelectMany(x => x.Children).ToList()(a fetch, not a count) applies theLIMITto the exploded child rows, so it returnsnchildren rather than the children of the firstndocuments. After this PR, the count of that shape follows LINQ semantics (the children of the firstndocuments), so it can differ from the fetch's row count until the fetch is fixed too.Migration guide: a "LINQ
Count()afterTake()orSkip()counts the page" note under Key Changes in 10.0.0. markdownlint and cspell are clean.🤖 Generated with Claude Code