You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support for common table expressions (aka WITH) via special LINQ operator #26486
Reacted by Albert Ragány-Németh, Massimiliano Donini, Steven Rasmussen, JohnEffo, sidneyxvr, levyhnunes, LucasLima, matt beary, Volodymyr Rets, Jan Jones and 128 more
Reacted by netotz, Denis Zimin, Viesturs Priedītis, Milo, Miguel Oliveira, Joona Luoma, Sujan Sapkota, Yimmy Quispe Yujra, David Thompson, Fabien Ménager and 11 more
changed the title [-]Support for common table expressions (aka WITH)[/-][+]Support for common table expressions (aka WITH) using LINQ[/+]on Oct 28, 2021
changed the title [-]Support for common table expressions (aka WITH) using LINQ[/-][+]Support for common table expressions (aka WITH) by translating LINQ query[/+]on Oct 28, 2021
changed the title [-]Support for common table expressions (aka WITH) by translating LINQ query[/-][+]Support for common table expressions (aka WITH) via special LINQ operator[/+]on Apr 25, 2023
Note: all databases - except SQL Server - support embedding CTEs within arbitrary subqueries inside the query;
SELECT*FROM (WITH t AS (SELECT1) SELECT*FROM t) AS foo;
This effectively makes CTEs an optional prefix of SelectExpression.
In addition, SQL Server (but not other databases) requires that column names be explicitly specified when they're not named within the subquery:
WITH t AS (SELECT1AS q) SELECT*FROM t; -- Column name bubbles out of the subquery
WITH t (q) AS (SELECT1) SELECT*FROM t; -- Column explicitly specified as part of the CTE syntax
WITH t AS (SELECT1) SELECT*FROM t; -- Fails in SQL Server, works elsewhere (with unknown column name)
Reacted by Carlos Martos, Miguel Oliveira, Joona Luoma, David Rettenbacher and zejji
@ajcvickers and @roji
I hope CTEs and window functions #12747 will be added to 10.0 milestone for boost performance of advanced queries with grouping and aggregation.
Reacted by Miguel Oliveira, Kostiantyn Nesterenko, zejji, Hicham el Allouchi, Mauricio Dominguez, Christian Nagel, David Drápela, Jeremy Salwen, Jay Chu, Manuel Moser and 14 more
+1 this would be great to see and would benefit us across a number of projects
Reacted by Carlos Martos, Miguel Oliveira, zejji, Hicham el Allouchi, Mattia Ricci, jaglick, yair-legit, Jannes Ströhlein, David Drápela, Jeremy Salwen and 21 more
My plan for a first PR, based on the EF.With(...) sketch in the original post:
Non-recursive CTEs only, behind [Experimental].
All WITH definitions are hoisted to the top-level query, since SQL Server doesn't allow them inside subqueries. Projected columns are always aliased, so SQL Server's column-naming requirement is covered too.
If the same source is wrapped in EF.With more than once, it becomes a single CTE.
Correlated sources, ExecuteUpdate/ExecuteDelete and split queries throw a clear error for now.
Tested on SQL Server and SQLite.
fromcinEF.With(context.Customers.Where(c =>c.IsActive))
join oincontext.Orders on c.Id equals o.CustomerIdselectnew{c.Name,o.Total}
WITH [cte] AS (
SELECT [c].[Id], [c].[Name]
FROM [Customers] AS [c]
WHERE [c].[IsActive] = CAST(1ASbit)
)
SELECT [c0].[Name], [o].[Total]
FROM [cte] AS [c0]
INNER JOIN [Orders] AS [o] ON [c0].[Id] = [o].[CustomerId]
Recursive CTEs would come later as a separate step on top of this.
Does this sound like a reasonable first slice? If you'd rather see a different API shape or a smaller scope, I'm happy to adjust before I start.
Am noting that EF.With() for non-recursive CTEs doesn't seem to be a good direction, since non-recursive CTEs can already be expressed without a special LINQ operator, by simply referencing an external IQueryable (that's #29918).
It's also a good idea to consider why non-recursive CTEs are even needed. Sure, they can contribute to more readable SQL, but that seems pretty minor where the developer is writing LINQ and not SQL. The one reason IMHO is to allow the same CTE to be referenced more than once in the same query, and for it to get materialized once (as opposed to inlined and evaluated multiple times) - that's a perf optimization. AFAIK PostgreSQL supports CTE materialization while SQL Server does not. So on SQL Server, whether one uses a (non-recursive) CTE or not is largely irrelevant.
To summarize, I'd (a) concentrate on #29918 for non-recursive CTE expression, and (b) keep EF.With() for the recursive case.
Thanks @roji, that makes sense. I'll drop the non-recursive EF.With idea and look at #29918 instead. I see it's labeled blocked. What is it blocked on? Also, would you want a CTE only when the same embedded IQueryable is referenced more than once, or for every embedded IQueryable?
I honestly don't remember at this point - it has been a while. You'll have to try and see.
Also, would you want a CTE only when the same embedded IQueryable is referenced more than once, or for every embedded IQueryable?
Good question - I think it would make sense to always translate to a CTE when an IQueryable is embedded; AFAIK there's never a performance degradation when doing that, and it's embedded IQueryable -> CTE seems to be a very natural, logical correspondence (query embedded within another). But @AndriySvyryd should chime in here.
@roji Thanks! I tried it on current main, and I couldn't find anything that blocks #29918 on the core side:
I changed ExpressionTreeFuncletizer to wrap the inlined IQueryable in a marker call carrying the variable name (e.g. AsCte(source, "active")), instead of splicing it in directly.
The marker gets through normalization and nav expansion untouched, and reaches QueryableMethodTranslatingExpressionVisitor with the name intact, including in parameterized, correlated and ExecuteDelete queries.
Translated as a pass-through, it produces exactly the same SQL as today.
So the remaining work looks to be on the relational side: a CTE table expression, WITH generation at the top-level statement, alias handling, Quote() support for precompiled queries, and reusing a single CTE when the same variable is referenced more than once.
One thing I noticed: only variables captured inside lambdas go through the funcletizer. For active.Concat(active), or when active is the root of the query, Queryable itself splices in the expression at composition time, so those cases would stay as they are today.
@AndriySvyryd whenever you get a chance, I'd appreciate your take on always vs. multiple references only, before I start on the relational part.
I changed ExpressionTreeFuncletizer to wrap the inlined IQueryable in a marker call carrying the variable name (e.g. AsCte(source, "active")), instead of splicing it in directly.
@Aykuttonpc sounds good, but make sure to always visit the wrapped IQueryable as well, in case it contains stuff that needs to be handled by ExpressionTreeFuncletizer (the same needs to be true of nav expansion and any other visitor). In other words, your marker expression which holds the referenced expression needs to have VisitChildren properly implemented so that all visitors automatically visit the queryable, without needing to know about it.
Another thing to keep in mind is that non-relational databases (most likely) don't support CTE-like constructs, but should not be broken by this change.
The marker is a plain method call, EmbeddedQueryable.Marker(source, name), so every visitor, nav expansion included, visits the wrapped query through the normal path without knowing about the marker. The funcletizer also visits the captured query before wrapping it.
Core's TranslateEmbeddedQuery just returns the translated source, so non-relational providers translate the query as before. Only the relational override turns it into a CTE, and the InMemory tests pass unchanged.
Activity
[-]Support for common table expressions (aka WITH)[/-][+]Support for common table expressions (aka WITH) using LINQ[/+][-]Support for common table expressions (aka WITH) using LINQ[/-][+]Support for common table expressions (aka WITH) by translating LINQ query[/+]roji commentedon Dec 19, 2021
Note: all major databases support prefixing UPDATE/DELETE with CTEs (see #795 for bulk updates).
[-]Support for common table expressions (aka WITH) by translating LINQ query[/-][+]Support for common table expressions (aka WITH) via special LINQ operator[/+]roji commentedon Aug 27, 2023
Note: all databases - except SQL Server - support embedding CTEs within arbitrary subqueries inside the query;
This effectively makes CTEs an optional prefix of SelectExpression.
In addition, SQL Server (but not other databases) requires that column names be explicitly specified when they're not named within the subquery:
mojtabakaviani commentedon Nov 23, 2024
@ajcvickers and @roji
I hope CTEs and window functions #12747 will be added to 10.0 milestone for boost performance of advanced queries with grouping and aggregation.
Pepsi1x1 commentedon Dec 6, 2024
+1 this would be great to see and would benefit us across a number of projects
Aykuttonpc commentedon Nov 15, 2026
@roji @AndriySvyryd I'd like to take a stab at this, starting small.
My plan for a first PR, based on the
EF.With(...)sketch in the original post:[Experimental].WITHdefinitions are hoisted to the top-level query, since SQL Server doesn't allow them inside subqueries. Projected columns are always aliased, so SQL Server's column-naming requirement is covered too.EF.Withmore than once, it becomes a single CTE.ExecuteUpdate/ExecuteDeleteand split queries throw a clear error for now.Recursive CTEs would come later as a separate step on top of this.
Does this sound like a reasonable first slice? If you'd rather see a different API shape or a smaller scope, I'm happy to adjust before I start.
AndriySvyryd commentedon Nov 15, 2026
@Aykuttonpc Sounds good
@cincuranet FYI
roji commentedon Nov 17, 2026
Am noting that EF.With() for non-recursive CTEs doesn't seem to be a good direction, since non-recursive CTEs can already be expressed without a special LINQ operator, by simply referencing an external IQueryable (that's #29918).
It's also a good idea to consider why non-recursive CTEs are even needed. Sure, they can contribute to more readable SQL, but that seems pretty minor where the developer is writing LINQ and not SQL. The one reason IMHO is to allow the same CTE to be referenced more than once in the same query, and for it to get materialized once (as opposed to inlined and evaluated multiple times) - that's a perf optimization. AFAIK PostgreSQL supports CTE materialization while SQL Server does not. So on SQL Server, whether one uses a (non-recursive) CTE or not is largely irrelevant.
To summarize, I'd (a) concentrate on #29918 for non-recursive CTE expression, and (b) keep EF.With() for the recursive case.
Aykuttonpc commentedon Nov 17, 2026
Thanks @roji, that makes sense. I'll drop the non-recursive
EF.Withidea and look at #29918 instead. I see it's labeledblocked. What is it blocked on? Also, would you want a CTE only when the same embeddedIQueryableis referenced more than once, or for every embeddedIQueryable?roji commentedon Nov 20, 2026
I honestly don't remember at this point - it has been a while. You'll have to try and see.
Good question - I think it would make sense to always translate to a CTE when an IQueryable is embedded; AFAIK there's never a performance degradation when doing that, and it's embedded IQueryable -> CTE seems to be a very natural, logical correspondence (query embedded within another). But @AndriySvyryd should chime in here.
Aykuttonpc commentedon Nov 20, 2026
@roji Thanks! I tried it on current main, and I couldn't find anything that blocks #29918 on the core side:
ExpressionTreeFuncletizerto wrap the inlinedIQueryablein a marker call carrying the variable name (e.g.AsCte(source, "active")), instead of splicing it in directly.QueryableMethodTranslatingExpressionVisitorwith the name intact, including in parameterized, correlated andExecuteDeletequeries.So the remaining work looks to be on the relational side: a CTE table expression, WITH generation at the top-level statement, alias handling,
Quote()support for precompiled queries, and reusing a single CTE when the same variable is referenced more than once.One thing I noticed: only variables captured inside lambdas go through the funcletizer. For
active.Concat(active), or whenactiveis the root of the query,Queryableitself splices in the expression at composition time, so those cases would stay as they are today.@AndriySvyryd whenever you get a chance, I'd appreciate your take on always vs. multiple references only, before I start on the relational part.
AndriySvyryd commentedon Nov 23, 2026
Always translating to a CTE sounds ok, especially if that simplifies the logic
Aykuttonpc commentedon Nov 23, 2026
Thanks @roji and @AndriySvyryd! Always translating to a CTE makes sense, and it does keep the logic simpler. I'll start working on this.
roji commentedon Nov 24, 2026
@Aykuttonpc sounds good, but make sure to always visit the wrapped IQueryable as well, in case it contains stuff that needs to be handled by ExpressionTreeFuncletizer (the same needs to be true of nav expansion and any other visitor). In other words, your marker expression which holds the referenced expression needs to have VisitChildren properly implemented so that all visitors automatically visit the queryable, without needing to know about it.
Another thing to keep in mind is that non-relational databases (most likely) don't support CTE-like constructs, but should not be broken by this change.
Aykuttonpc commentedon Nov 25, 2026
@roji Thanks, both are handled in #39803:
EmbeddedQueryable.Marker(source, name), so every visitor, nav expansion included, visits the wrapped query through the normal path without knowing about the marker. The funcletizer also visits the captured query before wrapping it.TranslateEmbeddedQueryjust returns the translated source, so non-relational providers translate the query as before. Only the relational override turns it into a CTE, and the InMemory tests pass unchanged.