Skip to content

Undesirable composite ORDER BY clause when loading included data on a one-to-many relation #19571

Closed as not planned

Description

Entity Framework is generating a composite ORDER BY clause when a query on one entity .Includes() an entity under a one-to-many relation and that related entity is loaded in the SELECT clause. The order by clause includes the primary keys of every single entity in the query as a whole, not just those under that relation. None of this happens if the relation is on a *-to-one relation. I haven't tested many-to-many.

This in combination with the change in EF 3.0 to utilize joins instead of multiple selects can have severe negative performance implications for queries with .Include() calls that worked well enough prior to EF 3.0. Not only does that mean there's extra load on the database server to do these orderings - the sql generated by EF 3.1 for one of our large queries executes in two minutes with the ORDER BY clause and 30 seconds without it - but also the database server isn't able to even start streaming results until it more or less has all the results assembled, leading to client-side timeouts.

I'm not sure if this is a bug or just undesirable behavior. I've found nothing documenting this on pages like https://docs.microsoft.com/en-us/ef/core/querying/related-data, and I've found no clear way to disable it or get around it, absent rewriting these queries or doing something ugly with a command interceptor, but I could have just missed a source of information. I totally understand the pivot to joins implies some things need to be rewritten, but this ORDER BY especially on every entity is excessive and mandates us to manually fine tune data loading where we were previously able to rely on EF for it, even when joins alone are fine.

Solutions in order of preference:

  1. Don't introduce these order by clauses unless asked for in the query
  2. Document this and provide some way to opt out of this behavior on a global or per-query basis.
  3. Document this and don't order by other entitles' keys outside the one-to-many-relation
  4. Document this behavior loudly and provide best practices to work around it

Steps to reproduce

See my gist with code and comments at https://gist.github.com/cwhitelaw/df7d12778966e16e0119a4ffce0a06dc?ts=4

Model:

public class MainEntity
{
	public int Id { get; set; }
	public int SingleRelatedEntityId { get; set; }
	public SingleRelatedEntity SingleRelatedEntity { get; set; }
	public List<ManyRelatedEntity> ManyRelatedEntities { get; set; }
}
public class SingleRelatedEntity
{
	public int Id { get; set; }
}
public class ManyRelatedEntity
{
	public int Id { get; set; }
	public int MainEntityId { get; set; }
	public MainEntity MainEntity { get; set; }
}

Output (the problem manifests in the queries labeled with main entities including to-many relation):

Query: main entities
SELECT [m].[Id], [m].[SingleRelatedEntityId]
FROM [MainEntities] AS [m]

Query: single-related entities
SELECT [s].[Id]
FROM [SingleRelatedEntities] AS [s]

Query: many-related entities
SELECT [m].[Id], [m].[MainEntityId]
FROM [ManyRelatedEntities] AS [m]

Query: main entities including to-one relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [s].[Id]
FROM [MainEntities] AS [m]
INNER JOIN [SingleRelatedEntities] AS [s] ON [m].[SingleRelatedEntityId] = [s].[Id]

Query: main entities including to-many relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id], [m0].[Id]

Query: main entities including to-many relation, order by MainEntity.Id descending
SELECT [m].[Id], [m].[SingleRelatedEntityId], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id] DESC, [m0].[Id]

Query: main entities including both to-one and to-many relation
SELECT [m].[Id], [m].[SingleRelatedEntityId], [s].[Id], [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
INNER JOIN [SingleRelatedEntities] AS [s] ON [m].[SingleRelatedEntityId] = [s].[Id]
LEFT JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]
ORDER BY [m].[Id], [s].[Id], [m0].[Id]

Query: many-related entities through MainEntity relation
SELECT [m0].[Id], [m0].[MainEntityId]
FROM [MainEntities] AS [m]
INNER JOIN [ManyRelatedEntities] AS [m0] ON [m].[Id] = [m0].[MainEntityId]

Query: many-related entities including their MainEntity
SELECT [m].[Id], [m].[MainEntityId], [m0].[Id], [m0].[SingleRelatedEntityId]
FROM [ManyRelatedEntities] AS [m]
INNER JOIN [MainEntities] AS [m0] ON [m].[MainEntityId] = [m0].[Id]

Further technical details

EF Core version: 3.1.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer 3.1.0
Target framework: .NET Core 3.1
Operating system: Windows 10 x64
IDE: Visual Studio 2019

Activity

  1. ajcvickers commented on Jan 13, 2020

    @ajcvickers
    Contributor

    @roji @maumar Any thoughts on this?

  2. roji commented on Jan 13, 2020

    @roji
    Member

    I remember doing some performance tests on ordering by primary keys some time ago (on PostgreSQL), and definitely did not see any difference close to 2 minutes vs. 30 seconds - but we should definitely look into this. I can do a quick perf investigation here.

    @CWhitelaw this isn't exactly my domain, but to give some context... The ORDER By clause is added when materializing 1-to-many relations, so that the principal is grouped together while loading the dependent. If we don't have this, rows come at totally random order, and we must track all principals and look them up again on for each row. Having said that, if the ORDER BY necessarily triggers such a perf degradation I definitely agree we should re-examine this.

  3. roji commented on Jan 13, 2020

    @roji
    Member

    What I don't understand following that is, using my schema as an example, why does it also need to order by the ManyRelatedEntity id?

    That's a good observation and we've raised this internally - it seems like the last dependent entity does not need necessarily need an ORDER BY on its primary key.

    However, from the rest of your comment, it seems like the performance degradation you're experiencing could be completely unrelated to the ORDER BY clauses, but rather a case of eager loading being done with a single query. In a nutshell, versions before 3.0 sent a separate query for each related entity, where since 3.0 EF Core always generates a single query - which can cause a so-called "cartesian explosion" if too many joins are present. There are ways to rewrite your query to return to the pre-3.0 multiple query mechanism: please see this comment.

    For now I'm going to assume that any perf issue here is related to the single-query issue, rather than to the ORDER BY clause - could you please take a look and confirm?

  4. roji commented on Jan 13, 2020

    @roji
    Member

    However, just to clarify, that 30s -> 2min difference is not an EF 2.x to 3.1 change - it's predicated solely on the the ORDER BY clause on the same query generated by EF Core 3.1, so the joins themselves were only 30 seconds even for such a large query. So I think the ordering is still significant. But now that I see why ordering on the primary key of just one entity is desirable, I could test it against the minimal orderings rather than against none.

    So to be sure I understand - can you please confirm you're seeing a 30s -> 2min difference on a single-join query (e.g. the query tagged "main entities including to-many relation" above), predicated solely on the existence or absence of the ORDER BY clause? If so, I'll definitely look into this.

  5. roji commented on Jan 13, 2020

    @roji
    Member

    Thanks, I'll look into this and will get back to you soon if I have any questions.

  6. roji commented on Jan 13, 2020

    @roji
    Member

    Thanks for the added info, it's important to know that the degradation is (for now) seen on a query with 8 includes/joins. This also means that you may be able to work around the issue here by breaking the query into separate parts as described in #18022.

    Out of curiosity, if E8 seems to be the cause of the issue, do you have the same problem when removing the entire first include chain (i.e. E2-E7)?

    Also, is there any chance you can provide your (minimal!) model, with an idea of the data required to reproduce this? Also, any chance you could check if this occurs on a regular, on-premise SQL Server instance rather than Azure?

    This might be a good motivation to only be ordering on the left side of the one-to-many relation rather than both but I don't know how representative this case is. Hope this helps.

    I think it would be good to get to the bottom of this even though not ordering on the dependent side here may mitigate the issue you're specifically seeing.

  7. roji commented on Jan 13, 2020

    @roji
    Member

    Also, if you could post the specific SQL being generated that could be helpful.

  8. 15 remaining items

  9. roji commented on Feb 26, 2020

    @roji
    Member

    Opened #20076 to track the removal of ORDER BY for buffered tracked queries. Between that, #19828 (remove last ORDER BY) and #18022 ("easy API" to split queries), I don't think there's anything more to do here - am closing this issue.

    @CWhitelaw at this point, the right thing to do is to manually split the query as described in #18022 (and to switch to the "easy API" once it's introduced). If, after splitting the query, you still encounter a scenario where an ORDER BY generates a significant perf degradation, please post a repro for that to #20076 - that would help us evaluate the necessity of doing that.

  10. removed this from the 5.0.0 milestone on Feb 26, 2020
  11. stijnherreman commented on Aug 6, 2025

    @stijnherreman

    For searchability reasons: this impacts keyless entity types and you may need to generate an artificial key instead.

    For example: configure an artificial entity using builder.HasNoKey() and builder.ToSqlQuery(...) with a one-to-one navigation property to a real entity, which in turn has a one-to-many navigation property. Accessing the one-to-many navigation property throws an exception, even though the keyless entity itself is not relevant in the JOIN.

    Unable to translate a collection subquery in a projection since either parent or the subquery doesn't project necessary information required to uniquely identify it and correctly generate results on the client side. This can happen when trying to correlate on keyless entity type. This can also happen for some cases of projection before 'Distinct' or some shapes of grouping key in case of 'GroupBy'. These should either contain all key properties of the entity that the operation is applied on, or only contain simple property access expressions.

    #29788 is probably the same kind of issue as I described here.

  12. roji commented on Mar 9, 2026

    @roji
    Member

    Note that #29182 removes ORDER BYs for reference joins (to-one).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions