Skip to content

Count NULL as a value in Distinct().Count() over a grouping - #39766

Open
seragAhmed wants to merge 2 commits into
dotnet:mainfrom
seragAhmed:fix/39759-distinct-count-null
Open

seragAhmed wants to merge 2 commits into
dotnet:mainfrom
seragAhmed:fix/39759-distinct-count-null

Conversation

@seragAhmed

Copy link
Copy Markdown
Contributor
  • I've read the guidelines for contributing and seen the walkthrough
  • I've posted a comment on an issue with a detailed description of how I am planning to contribute and got approval from a member of the team
  • The code builds and tests pass locally (also verified by our automated build checks)
  • Commit messages follow this format
  • Tests for the changes have been added (for bug fixes / features)
  • Code follows the same patterns and style as existing code in this repo

Fixes #39759

Inside a GroupBy, g.Select(x => x.Nullable).Distinct().Count() / LongCount() translated to COUNT(DISTINCT x), which skips NULL, while LINQ counts null as one distinct value.

When the counted operand can be NULL, the translation now adds a distinct count of CASE WHEN x IS NULL THEN 1 END (0 or 1, never NULL), translated through the provider's own count translator so SQL Server keeps COUNT_BIG. A predicate on the count is applied to that term as well; a predicate that only excludes NULL on the same column (Distinct().Count(x => x != null)) leaves the SQL unchanged, as do non-nullable operands.

SQL Server:

COUNT(DISTINCT ([c].[Region])) + COUNT(DISTINCT (CASE WHEN [c].[Region] IS NULL THEN 1 END))

Added GroupBy spec tests over Customer.Region (many NULLs in Northwind) with SQL Server and Sqlite baselines; three existing SQL Server baselines over nullable columns pick up the extra term. This may need a rebase on top of #39451, which reworks this area.

@seragAhmed

Copy link
Copy Markdown
Contributor Author

The Cosmos job's failures are CosmosSessionTokensTest.Add_conflict_updates_session_token (expected a session token, got null) on the Linux emulator. This PR doesn't touch session tokens or Cosmos. Could someone re-run the Cosmos job?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Distinct Count/LongCount translation can emit invalid SQL Server SQL for coalesced selectors and return incorrect counts by evaluating volatile selectors twice.

2 open issues
What changed in this PR

This PR addresses #39759 by updating EF Core’s relational translation of grouped Distinct().Count() and LongCount() to count null as one distinct value, matching LINQ semantics.

Changes:

  • Adds a null-count compensation term through provider-specific aggregate translators, preserving SQL Server’s COUNT_BIG.
  • Applies aggregate predicates to the compensation term.
  • Adds shared regression tests and SQL Server/SQLite baselines for nullable selectors and filters.
File Description
test/​EFCore.SqlServer.FunctionalTests/​Query/​NorthwindGroupByQuerySqlServerTest.cs Adds regression baselines and updates existing nullable distinct-count SQL.
test/​EFCore.Sqlite.FunctionalTests/​Query/​NorthwindGroupByQuerySqliteTest.cs Adds SQLite baselines for nullable distinct counts and predicates.
test/​EFCore.Specification.Tests/​Query/​NorthwindGroupByQueryTestBase.cs Adds shared Count/LongCount tests using nullable customer regions.
src/​EFCore.Relational/​Query/​RelationalSqlTranslatingExpressionVisitor.cs Adds nullability checks and compensation for grouped distinct counts.

Review effort: Balanced

COUNT(DISTINCT x) skips NULL, while LINQ's Distinct().Count() and
Distinct().LongCount() count null as one more distinct value.
- When the counted operand can be NULL, add a distinct count of
  CASE WHEN x IS NULL THEN 1 END (0 or 1, never NULL) through the
  provider's own count translation, so SQL Server keeps COUNT_BIG.
- A predicate on the count also guards the NULL term; a predicate that
  only excludes NULL from the same column skips it.

Fixes dotnet#39759
@seragAhmed
seragAhmed force-pushed the fix/39759-distinct-count-null branch from c1d3ede to 58f2d76 Compare November 25, 2026 03:56
Null semantics can find the counted expression non-nullable after
translation (a parameter, a null-checked predicate) and drop the marker's
only WHEN, leaving COUNT(DISTINCT (NULL)), which SQL Server rejects. Give
the CASE a typed NULL ELSE so it collapses to CAST(NULL AS int) instead,
and treat COALESCE with a non-nullable argument and CASE with non-nullable
results as non-nullable so those get no marker at all.
@seragAhmed
seragAhmed force-pushed the fix/39759-distinct-count-null branch from 58f2d76 to 142b129 Compare November 25, 2026 03:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

GroupBy with Select(...).Distinct().Count() on a nullable column doesn't count NULL

2 participants