Skip to content

EF10 generated SQL query for ExecuteDeleteAsync when using Take not optimal #38324

@matnun-br

Description

@matnun-br

Bug description

As part of EF10 we can now use Take when using ExecuteDeleteAsync but the SQL generated is not optimal and does not perform as well as it could. The code provided generates the following SQL;

DELETE FROM [s]
FROM [Schema].[Entity] AS [s]
WHERE EXISTS (
    SELECT 1
    FROM (
        SELECT TOP(100) [s0].[Id]
        FROM  [Schema].[Entity] AS [s0]
        WHERE [s0].[field1] < 100
    ) AS [s1]
    WHERE [s1].[Id] = [s].[Id])

The sub query is not required. Instead the following optimal SQL should be generated;

DELETE tail
                FROM
                (
                    SELECT TOP (100) [Id]
                    FROM [Schema].[Entity]
                    WHERE [s0].[field1] < 100
                ) tail

Your code

await ctx.Set<Entity>().Where(e => e.field1 < 100).Take(100).ExecuteDeleteAsync();

Stack traces


Verbose output


EF Core version

10.0.8

Database provider

Microsoft.EntityFramework.SqlServer

Target framework

.Net 10.0

Operating system

Windows 11

IDE

VS Code 1.121.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions