Skip to content
Advertisement

Why there is no GroupBy clause in internal SQL of Entity Framework linq query?

In documentation of Entity Framework: https://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx

in section regarding GroupBy we can read that following code:

executes internally following SQL:

Why there is no GroupBy clause in SQL? If there is no GroupBy clause needed, can’t we just use simple Select with OrderBy and without Joins? Can anyone explain the above query?

Advertisement

Answer

The bottom line is: because SQL can’t return nested result sets.

Every SQL SELECT statement returns a flat list of values. LINQ is capable of returning object graphs, i.e. objects with nested objects. That’s exactly what LINQ’s GroupBy does.

In SQL, a GROUP BY statement only returns the grouping columns and aggregate results:

The rest of the student columns is gone.

A LINQ GroupBy statement returns something like

Therefore, a SQL GROUP BY statement can never be the source for a LINQ GroupBy.

Entity Framework (6) knows this and it generates a SQL statement that pulls all required data from the database, adds some parts that make grouping easier, and it creates the groupings client-side.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement