Skip to content

Join condition that isn't an outer/inner column comparison causes a subquery pushdown #33745

Open

Description

@smarts

Redirected here from npgsql/efcore.pg#3176

  1. Declarative-style equijoin
from foo in dbContext.Set<Foo>()
join bar in dbContext.Set<Bar>() on
new { foo.Id, State = "Blah" } equals new { Id = bar.FooId, bar.State } into barGroupJoin
from subBar in barGroupJoin.DefaultIfEmpty()
select new { /* use subBar instead of bar */ }
  1. Method-style equijoin
from foo in dbContext.Set<Foo>()
from bar in dbContext.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == "Blah").DefaultIfEmpty()
select new { /* use bar */ }

I generally prefer 2 because it's arguably just as easy to read, doesn't leave a variable that goes unused, etc.
But one thing I notice is that the former style will generate something like

LEFT JOIN mySchema."Bars" AS B ON B."FooId" = F."Id" AND B."State" = 'Blah'

while the latter generates something like

LEFT JOIN (
SELECT …
FROM mySchema."Bars" AS B
WHERE B."State" = 'Blah'
) as C ON C."FooId" = F."Id"

Is this intentional, and if so why?

Include provider and version information

EF Core version: 8.0.4
Database provider: Npgsql.EntityFrameworkCore.PostgreSQL
Target framework: .NET 8
Operating system: MacOS Sonoma 14.4.1
IDE: Rider

Activity

  1. roji commented on Sep 17, 2024

    @roji
    Member

    Sorry it took so long to get a response on this.

    I took a look and our current join logic only extracts parts of the Where() predicate to the join condition which are comparisons between outer and inner columns. Anything which does not get extracted causes the inner query to get pushed down into a subquery.

    For example, the following:

    _ = await (
        from foo in context.Set<Foo>()
        from bar in context.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == foo.State).DefaultIfEmpty()
        select bar

    ... gets translated to:

    SELECT [b].[Id], [b].[FooId], [b].[State]
    FROM [Foos] AS [f]
    LEFT JOIN [Bars] AS [b] ON [f].[Id] = [b].[FooId] AND [f].[State] = [b].[State]

    But the following (as in the OP):

    _ = await (
        from foo in context.Set<Foo>()
        from bar in context.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == "Blah").DefaultIfEmpty()
        select bar

    ... gets translated to:

    SELECT [b0].[Id], [b0].[FooId], [b0].[State]
    FROM [Foos] AS [f]
    LEFT JOIN (
        SELECT [b].[Id], [b].[FooId], [b].[State]
        FROM [Bars] AS [b]
        WHERE [b].[State] = N'Blah'
    ) AS [b0] ON [f].[Id] = [b0].[FooId]

    I'll look into the reasons things are implemented this way, and we'll consider relaxing this.

    Minimal repro
    await using var context = new BlogContext();
    await context.Database.EnsureDeletedAsync();
    await context.Database.EnsureCreatedAsync();
    
    // All comparisons in the predicate compare outer to inner columns -> results in LEFT JOIN without subquery
    _ = await (
        from foo in context.Set<Foo>()
        from bar in context.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == foo.State).DefaultIfEmpty()
        select bar
    ).ToListAsync();
    
    // Predicate contains something that isn't a comparison of outer to inner column -> results in LEFT JOIN with subquery
    _ = await (
        from foo in context.Set<Foo>()
        from bar in context.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == "Blah").DefaultIfEmpty()
        select bar
    ).ToListAsync();
    
    public class BlogContext : DbContext
    {
        public DbSet<Foo> Foos { get; set; }
        public DbSet<Bar> Bars { get; set; }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                .UseSqlServer("Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
                .LogTo(Console.WriteLine, LogLevel.Information)
                .EnableSensitiveDataLogging();
    }
    
    public class Foo
    {
        public int Id { get; set; }
        public string State { get; set; }
    }
    
    public class Bar
    {
        public int Id { get; set; }
        public string State { get; set; }
    
        public int FooId { get; set; }
    }
  2. changed the title [-]Question: SQL LEFT JOIN clause varies based on declarative- vs. method-style join[/-] [+]Join condition that isn't an outer/inner column comparison causes a subquery pushdown[/+] on Sep 17, 2024
  3. assigned and unassigned on Sep 17, 2024
  4. added this to the Backlog milestone on Sep 17, 2024
  5. roji commented on Sep 18, 2024

    @roji
    Member

    Next steps:

    Verify that join conditions can indeed be arbitrary bool-returning expression, across the major databases. For example, we can test something like x.Id > 5 || x.Name.StartsWith("foo) on dbfiddle. If so, we should be able to just always lift the predicate out of the inner query, and make it the join condition, regardless of its contents.

    The one exception to this is when the inner subquery predicate affects which rows are returned from the subquery:

    from foo in context.Set<Foo>()
    from bar in context.Set<Bar>().Where(x => x.FooId == foo.Id).OrderBy(bla).Take(5).DefaultIfEmpty()
    select bar

    If the predicate is lifted out of the subquery, arbitrary 5 rows are returned (unrelated to the principal) and we get wrong results. For this case, the subquery must be left as-is, and the current logic extracting the "join key" is probably OK.

  6. added theissue type on Oct 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions