Skip to content

Remove reference joins in split queries (and their orderings in single) #29182

Description

@stevendarby

If I include both reference navigations and collection navigations in a query and execute with AsSplitQuery then joins to the reference navigations are present in all of the collection queries. This doesn't appear to be necessary and can slow down the query significantly if there are multiple reference navigations.

Repro:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

{
    using var context = new MyContext();

    if (context.Database.EnsureCreated())
    {
        var blogType = new BlogType { Type = "Development" };
        var blog = new Blog { Name = "EF", BlogType = blogType };
        var post = new Post { Title = "Split Query", Blog = blog };

        context.AddRange(blogType, blog, post);
        context.SaveChanges();
    }
}
{
    using var context = new MyContext();
    var result = context.Blogs
        .Include(x => x.BlogType)
        .Include(x => x.Posts)
        .AsSplitQuery()
        .ToList();
}

public class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer("Server=.;Database=Split;Trusted_Connection=True;Encrypt=False")
            .LogTo(Console.WriteLine, LogLevel.Information);
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int BlogTypeId { get; set; }
    public BlogType BlogType { get; set; }
    public ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

public class BlogType
{
    public int Id { get; set; }
    public string Type { get; set; }
    public ICollection<Blog> Blogs { get; set; }
}

Produces this SQL:

SELECT [b].[Id], [b].[BlogTypeId], [b].[Name], [b0].[Id], [b0].[Type]
FROM [Blogs] AS [b]
INNER JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
ORDER BY [b].[Id], [b0].[Id]

SELECT [p].[Id], [p].[BlogId], [p].[Title], [b].[Id], [b0].[Id]
FROM [Blogs] AS [b]
INNER JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
INNER JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId]
ORDER BY [b].[Id], [b0].[Id]

I believe the second query could simply be:

SELECT [p].[Id], [p].[BlogId], [p].[Title], [b].[Id]
FROM [Blogs] AS [b]
INNER JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId]
ORDER BY [b].[Id]

The reduced joins, and reduced fields selected and in the order by, would improve the query plan. I don't think the BlogType ID is required to match the Posts up to the Blog.

Note that in this example, I am just using a single reference navigation, but when multiple are included, joins to all of them are repeated in each collection query and this begins to really impact the performance.

Same behaviour also occurs in non-entity projection and split query.

Activity

  1. changed the title [-]Unnecessary joins in split queries[/-] [+]Unnecessary joins in split queries causing performance issues[/+] on Sep 22, 2022
  2. stevendarby commented on Sep 23, 2022

    @stevendarby
    ContributorAuthor

    Just a quick example with a couple more reference navigations and an extra collection navigation, just to show how the problem grows. The reference navigations are also optional in this example.

    SELECT [b].[Id], [b].[AccountId], [b].[BlogTypeId], [b].[Name], [b].[OwnerId], [b0].[Id], [b0].[Type], [o].[Id], [o].[Name], [a].[Id], [a].[Name]
    FROM [Blogs] AS [b]
    LEFT JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
    LEFT JOIN [Owner] AS [o] ON [b].[OwnerId] = [o].[Id]
    LEFT JOIN [Account] AS [a] ON [b].[AccountId] = [a].[Id]
    ORDER BY [b].[Id], [b0].[Id], [o].[Id], [a].[Id]
    
    SELECT [p].[Id], [p].[BlogId], [p].[Title], [b].[Id], [b0].[Id], [o].[Id], [a].[Id]
    FROM [Blogs] AS [b]
    LEFT JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
    LEFT JOIN [Owner] AS [o] ON [b].[OwnerId] = [o].[Id]
    LEFT JOIN [Account] AS [a] ON [b].[AccountId] = [a].[Id]
    INNER JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId]
    ORDER BY [b].[Id], [b0].[Id], [o].[Id], [a].[Id]
    
    SELECT [s].[Id], [s].[BlogId], [s].[Name], [b].[Id], [b0].[Id], [o].[Id], [a].[Id]
    FROM [Blogs] AS [b]
    LEFT JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
    LEFT JOIN [Owner] AS [o] ON [b].[OwnerId] = [o].[Id]
    LEFT JOIN [Account] AS [a] ON [b].[AccountId] = [a].[Id]
    INNER JOIN [Subscriber] AS [s] ON [b].[Id] = [s].[BlogId]
    ORDER BY [b].[Id], [b0].[Id], [o].[Id], [a].[Id]

    I believe this could be simplified to:

    SELECT [b].[Id], [b].[AccountId], [b].[BlogTypeId], [b].[Name], [b].[OwnerId], [b0].[Id], [b0].[Type], [o].[Id], [o].[Name], [a].[Id], [a].[Name]
    FROM [Blogs] AS [b]
    LEFT JOIN [BlogType] AS [b0] ON [b].[BlogTypeId] = [b0].[Id]
    LEFT JOIN [Owner] AS [o] ON [b].[OwnerId] = [o].[Id]
    LEFT JOIN [Account] AS [a] ON [b].[AccountId] = [a].[Id]
    ORDER BY [b].[Id], [b0].[Id], [o].[Id], [a].[Id]
    
    SELECT [p].[Id], [p].[BlogId], [p].[Title], [b].[Id]
    FROM [Blogs] AS [b]
    INNER JOIN [Post] AS [p] ON [b].[Id] = [p].[BlogId]
    ORDER BY [b].[Id]
    
    SELECT [s].[Id], [s].[BlogId], [s].[Name], [b].[Id]
    FROM [Blogs] AS [b]
    INNER JOIN [Subscriber] AS [s] ON [b].[Id] = [s].[BlogId]
    ORDER BY [b].[Id]
  3. added this to the Backlog milestone on Sep 27, 2022
  4. changed the title [-]Unnecessary joins in split queries causing performance issues[/-] [+]Remove reference joins in split queries[/+] on Oct 19, 2022
  5. stevendarby commented on Oct 19, 2022

    @stevendarby
    ContributorAuthor

    Thanks for accepting this into the backlog. I believe this has come up at least once before and was closed, perhaps due to misunderstanding: #25731

    Bringing query filters into it muddied the waters but I'm fairly sure the core issue there was about the unnecessary repetition of reference joins in each split query.

  6. stevendarby commented on Oct 19, 2022

    @stevendarby
    ContributorAuthor

    Here's another that was possibly trying to get at this issue but struggled to describe it clearly: #24420

    Hoping this can be considered for 8.0 👀

  7. stevendarby commented on Dec 4, 2022

    @stevendarby
    ContributorAuthor

    FYI found this when looking for a duplicates for something else, which I didn't see before. Was closed because of single query in 3.0. #12022

  8. 29 remaining items

  9. added this to the 11.0.0 milestone on Mar 1, 2026
  10. added 2 commits that reference this issue on Mar 2, 2026
    eeaf668
    4a3ef03
  11. roji commented on Mar 2, 2026

    @roji
    Member

    @stevendarby and others, good news - I've submitted #37819 which does this. It goes far beyond just removing reference joins in split queries - it also removes ORDER BY and projection for keys ("identifiers") joined via reference joins, as these are not necessary (also in non-split queries). The result cuts down on a lot of expensive joins and ordering, and should be a substantial improvement in terms of SQL query performance; take a look at all the SQL changes in #37819 to get an idea.

    Wide-ranging SQL changes like this are inherently risky, so any help you could provide by (a) testing this on your applications to ensure the change is correct, and (b) direct reviewing of #37819 and especially the SQL baseline changes.

  12. changed the title [-]Remove reference joins in split queries[/-] [+]Improve generated SQL for reference joins[/+] on Mar 2, 2026
  13. stevendarby commented on Mar 2, 2026

    @stevendarby
    ContributorAuthor

    Nice one @roji, I will try to take a look and test against some real examples over the next week or so. BTW it sounds like this covers #29662 too!

  14. roji commented on Mar 2, 2026

    @roji
    Member

    Yep, it indeed does!

  15. changed the title [-]Improve generated SQL for reference joins[/-] [+]Remove reference joins in split queries[/+] on Mar 2, 2026
  16. added a commit that references this issue on Mar 4, 2026
    0d29024
  17. added a commit that references this issue on Mar 9, 2026
    be6a920
  18. roji commented on Apr 12, 2026

    @roji
    Member

    I did a quick benchmark to see what kind of performance improvements this can be expected to provide; the below exercises a simple scenario with both single and split query, with one collection include (to exercise split query) and a varying number of one-to-one includes (which are affected by this change).

    50K blogs, 3 posts/blog, 100K ref entities.

    Method RefCount Before After Improvement Alloc Before Alloc After Alloc Δ
    Split query 1 750 ms 530 ms −29% 305 MB 287 MB −6%
    Split query 3 1,368 ms 1,125 ms −18% 562 MB 508 MB −10%
    Split query 5 1,965 ms 1,653 ms −16% 818 MB 729 MB −11%
    Single query 1 868 ms 763 ms −12% 445 MB 434 MB −3%
    Single query 3 2,089 ms 1,929 ms −8% 948 MB 915 MB −3%
    Single query 5 4,051 ms 3,146 ms −22% 1,453 MB 1,396 MB −4%

    Some notes:

    • Split queries benefit more from this optimization as we're actually eliminating unneeded JOINs, where the JOINs need to stay for single queries (in order to actually fetch the data); for single queries we still eliminate costly ORDER BY, though.
    • This benchmark uses EF and LINQ - I saw more dramatic improvements when testing the raw SQL that EF sends to the database. When using EF, there are some unrelated constant costs (around materialization) which dilute the optimization a bit.
    • I saw scenarios where the performance improvement are more pronounced (even much more pronounced), but here I wanted to show the simple, obvious scenarios where we're likely to impact a large number of mainstream users.
    Benchmark code
    // =============================================================================
    // EF Core 11 Join Optimization Benchmark (dotnet/efcore#29182)
    //
    // Measures the impact of to-one join pruning using NESTED (chained) references:
    //   Blog → Ref → Ref.NextRef → Ref.NextRef.NextRef → ...
    // Nested LEFT JOINs form a dependency chain that is harder for SQL Server to
    // optimize, making the ORDER BY reduction especially impactful for single queries.
    // Uses nullable FKs (LEFT JOINs, all prunable) + a covering index on Posts.
    //
    // Prerequisites:
    //   - SQL Server instance (Docker works fine)
    //   - EF_BENCHMARK_CONNECTION or Test__SqlServer__DefaultConnection env var
    //
    // Usage:
    //   dotnet run -c Release -- seed                  # Create + seed database
    //   dotnet run -c Release -- --filter '*Split*'    # Split query benchmarks
    //   dotnet run -c Release -- --filter '*Single*'   # Single query benchmarks
    //   dotnet run -c Release -- --filter '*'          # All benchmarks
    //   dotnet run -c Release -- cleanup               # Drop database
    //
    // A/B testing:
    //   1. Run benchmarks on current EF (AFTER / optimized)
    //   2. git checkout be6a9208b0^ -- \
    //        src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs \
    //        src/EFCore.Relational/Query/SqlExpressions/SelectExpression.cs
    //   3. Run benchmarks again (BEFORE / unoptimized)
    //   4. git checkout main -- <same two files>
    // =============================================================================
    
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Columns;
    using BenchmarkDotNet.Running;
    using Microsoft.Data.SqlClient;
    using Microsoft.EntityFrameworkCore;
    
    if (args is ["seed"])
    {
        Seed();
        return;
    }
    
    if (args is ["cleanup"])
    {
        Cleanup();
        return;
    }
    
    BenchmarkSwitcher.FromAssembly(typeof(JoinOptimizationBenchmarks).Assembly).Run(args);
    
    // ═══════════════════════════════════════════════════════════════════════════════
    // Seed / Cleanup (top-level functions — must precede type declarations)
    // ═══════════════════════════════════════════════════════════════════════════════
    
    static string GetBaseConnectionString() => Helpers.GetBaseConnectionString();
    static string GetConnectionString() => Helpers.GetConnectionString();
    
    static void Seed()
    {
        const int blogCount = 50_000;
        const int postsPerBlog = 3;
        const int refTableSize = 100_000;
    
        var connStr = GetConnectionString();
        Console.WriteLine($"Seeding: {blogCount:N0} blogs × {postsPerBlog} posts, "
                          + $"ref table: {refTableSize:N0} rows (chained via NextRefId)");
    
        using var ctx = new BenchmarkContext(connStr);
        ctx.Database.EnsureDeleted();
        ctx.Database.EnsureCreated();
    
        var conn = (SqlConnection)ctx.Database.GetDbConnection();
        conn.Open();
    
        // Each RefEntity points to the next one (Id+1), forming chains of depth up to 100K.
        // Last row has NextRefId = NULL (chain terminator).
        Console.Write("  RefEntity (chained)...");
        var extraCols = string.Join(", ", Enumerable.Range(2, 9).Select(i => $"Col{i}"));
        var extraVals = string.Join(",\n    ", Enumerable.Range(2, 9).Select(_ =>
            "'Value_' + CAST(rn AS NVARCHAR(20))"));
        Exec(conn, $"""
            ;WITH N AS (
                SELECT TOP ({refTableSize}) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
                FROM sys.all_objects a CROSS JOIN sys.all_objects b
            )
            INSERT INTO [RefEntity] ([Name], [NextRefId], {extraCols})
            SELECT
                'Ref_' + CAST(rn AS NVARCHAR(20)),
                CASE WHEN rn < {refTableSize} THEN rn + 1 ELSE NULL END,
                {extraVals}
            FROM N
            """);
        Console.WriteLine(" done");
    
        // Blog.RefId points to a RefEntity with enough chain depth (at least 10).
        Console.Write($"  {blogCount:N0} Blogs...");
        Exec(conn, $"""
            ;WITH N AS (
                SELECT TOP ({blogCount}) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
                FROM sys.all_objects a CROSS JOIN sys.all_objects b
            )
            INSERT INTO [Blogs] ([Name], [RefId])
            SELECT 'Blog_' + CAST(rn AS NVARCHAR(20)),
                   ((rn * 7) % {refTableSize - 10}) + 1
            FROM N
            """);
        Console.WriteLine(" done");
    
        Console.Write($"  {(long)blogCount * postsPerBlog:N0} Posts...");
        Exec(conn, $"""
            ;WITH N AS (
                SELECT TOP ({postsPerBlog}) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS pn
                FROM sys.all_objects
            )
            INSERT INTO [Post] ([BlogId], [Title])
            SELECT b.Id, 'Post_' + CAST(b.Id AS NVARCHAR(20)) + '_' + CAST(N.pn AS NVARCHAR(5))
            FROM [Blogs] b CROSS JOIN N
            """);
        Console.WriteLine(" done");
    
        // Covering index prevents query-plan divergence between before/after query shapes
        Console.Write("  Covering index...");
        Exec(conn, "CREATE NONCLUSTERED INDEX IX_Posts_Covering ON [Post] ([BlogId]) INCLUDE ([Id], [Title])");
        Console.WriteLine(" done");
    
        conn.Close();
        Console.WriteLine("Seeding complete.");
    }
    
    static void Cleanup()
    {
        var masterCs = new SqlConnectionStringBuilder(GetBaseConnectionString())
            { InitialCatalog = "master" }.ConnectionString;
        using var conn = new SqlConnection(masterCs);
        conn.Open();
        Exec(conn, """
            IF DB_ID('EFJoinBenchmark') IS NOT NULL
            BEGIN
                ALTER DATABASE [EFJoinBenchmark] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
                DROP DATABASE [EFJoinBenchmark];
            END
            """);
        Console.WriteLine("Database dropped.");
    }
    
    static void Exec(SqlConnection conn, string sql)
    {
        using var cmd = new SqlCommand(sql, conn) { CommandTimeout = 600 };
        cmd.ExecuteNonQuery();
    }
    
    // ═══════════════════════════════════════════════════════════════════════════════
    // Benchmark
    // ═══════════════════════════════════════════════════════════════════════════════
    
    [MemoryDiagnoser]
    public class JoinOptimizationBenchmarks
    {
        private string _connectionString = null!;
    
        [Params(1, 3, 5)]
        public int RefCount { get; set; }
    
        [GlobalSetup]
        public async Task Setup()
        {
            _connectionString = Helpers.GetConnectionString();
            await using var ctx = new BenchmarkContext(_connectionString);
            if (!await ctx.Database.CanConnectAsync())
            {
                throw new InvalidOperationException(
                    "Database not found. Run 'dotnet run -c Release -- seed' first.");
            }
    
            // Warm SQL Server buffer pool
            await RunQueryAsync(split: true);
            await RunQueryAsync(split: false);
        }
    
        [Benchmark(Description = "Split query")]
        public Task<List<Blog>> SplitQuery() => RunQueryAsync(split: true);
    
        [Benchmark(Description = "Single query")]
        public Task<List<Blog>> SingleQuery() => RunQueryAsync(split: false);
    
        private async Task<List<Blog>> RunQueryAsync(bool split)
        {
            await using var ctx = new BenchmarkContext(_connectionString);
            IQueryable<Blog> q = ctx.Blogs;
    
            // Build nested Include path: "Ref", "Ref.NextRef", "Ref.NextRef.NextRef", ...
            if (RefCount >= 1)
            {
                var path = "Ref" + string.Concat(Enumerable.Repeat(".NextRef", RefCount - 1));
                q = q.Include(path);
            }
    
            q = q.Include(b => b.Posts);
            if (split)
            {
                q = q.AsSplitQuery();
            }
    
            return await q.AsNoTracking().ToListAsync();
        }
    }
    
    // ═══════════════════════════════════════════════════════════════════════════════
    // Model
    // ═══════════════════════════════════════════════════════════════════════════════
    
    public class BenchmarkContext : DbContext
    {
        private readonly string _connectionString;
    
        public BenchmarkContext(string connectionString) => _connectionString = connectionString;
    
        public DbSet<Blog> Blogs => Set<Blog>();
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseSqlServer(_connectionString).EnableThreadSafetyChecks(false);
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>(b =>
            {
                b.HasOne(x => x.Ref).WithMany().HasForeignKey(x => x.RefId);
                b.HasMany(x => x.Posts).WithOne().HasForeignKey(x => x.BlogId);
            });
    
            modelBuilder.Entity<RefEntity>(r =>
            {
                r.HasOne(x => x.NextRef).WithMany().HasForeignKey(x => x.NextRefId);
            });
        }
    }
    
    public class Blog
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
    
        public int? RefId { get; set; }
        public RefEntity? Ref { get; set; }
    
        public ICollection<Post> Posts { get; set; } = null!;
    }
    
    public class Post
    {
        public int Id { get; set; }
        public int BlogId { get; set; }
        public string Title { get; set; } = null!;
    }
    
    public class RefEntity
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public string Col2 { get; set; } = null!;
        public string Col3 { get; set; } = null!;
        public string Col4 { get; set; } = null!;
        public string Col5 { get; set; } = null!;
        public string Col6 { get; set; } = null!;
        public string Col7 { get; set; } = null!;
        public string Col8 { get; set; } = null!;
        public string Col9 { get; set; } = null!;
        public string Col10 { get; set; } = null!;
    
        public int? NextRefId { get; set; }
        public RefEntity? NextRef { get; set; }
    }
    
    public static class Helpers
    {
        public static string GetBaseConnectionString()
            => Environment.GetEnvironmentVariable("EF_BENCHMARK_CONNECTION")
               ?? Environment.GetEnvironmentVariable("Test__SqlServer__DefaultConnection")
               ?? throw new InvalidOperationException(
                   "Set EF_BENCHMARK_CONNECTION or Test__SqlServer__DefaultConnection.");
    
        public static string GetConnectionString()
            => new SqlConnectionStringBuilder(GetBaseConnectionString())
               { InitialCatalog = "EFJoinBenchmark" }.ConnectionString;
    }
  19. changed the title [-]Remove reference joins in split queries[/-] [+]Remove reference joins in split queries (and their orderings in single)[/+] on Apr 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-perfarea-querycustomer-reportedpreview-3priority-bug

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions