dotnet / dotnet/efcore

Better translation for COUNT with predicate checking for non-null

Open
#26,940 0 comments 0 reactions 0 assignees View on GitHub
area-groupby area-perf area-query
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

We currently translate the following LINQ query:

```c#
_ = ctx.Blogs
.GroupBy(b => b.Id)
.Select(g => new { g.Key, Count = g.Select(x => x.Name).Count(n => n != null) })
.ToList();
```

... to:

```sql
SELECT [b].[Id] AS [Key], COUNT(CASE
WHEN [b].[Name] IS NOT NULL THEN 1
END) AS [Count]
FROM [Blogs] AS [b]
GROUP BY [b].[Id]
```

... when we could just translate to:

```sql
SELECT [b].[Id] AS [Key], COUNT([b].[Name]) AS [Count]
FROM [Blogs] AS [b]
GROUP BY [b].[Id]
```

... since `COUNT(x)` only counts non-null values. This may have a perf impact (index usage).

Related to #26938

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.