Skip to content

Support for common table expressions (aka WITH) via special LINQ operator #26486

Description

@roji

We could have a special queryable-returning function which we'd translate into a TableExpressionBase:

from foo in EF.With(ctx.Foos.Where(....))
from bar in EF.With(ctx.Bars.Where(....))
from baz in ctx.Bazes.Where(...)
...

... becomes:

WITH foo AS (
    SELECT * FROM Foos
    WHERE ...
), bar AS (
    SELECT * FROM Bars
    WHERE ...
),
SELECT * FROM Bazes WHERE ...

Do recursive CTEs as well.

Note: CTEs are also valid with WITH ... INSERT ... INTO, WITH ... DELETE, WITH ... UPDATE.

See also #29918 (embedded IQueryables to common table expressions)

Community implementations

Activity

  1. changed the title [-]Support for common table expressions (aka WITH)[/-] [+]Support for common table expressions (aka WITH) using LINQ[/+] on Oct 28, 2021
  2. 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
  3. added this to the Backlog milestone on Nov 2, 2021
  4. roji commented on Dec 19, 2021

    @roji
    MemberAuthor

    Note: all major databases support prefixing UPDATE/DELETE with CTEs (see #795 for bulk updates).

  5. 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
  6. roji commented on Aug 27, 2023

    @roji
    MemberAuthor

    Note: all databases - except SQL Server - support embedding CTEs within arbitrary subqueries inside the query;

    SELECT * FROM (WITH t AS (SELECT 1) 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 (SELECT 1 AS q) SELECT * FROM t; -- Column name bubbles out of the subquery
    WITH t (q) AS (SELECT 1) SELECT * FROM t; -- Column explicitly specified as part of the CTE syntax
    WITH t AS (SELECT 1) SELECT * FROM t; -- Fails in SQL Server, works elsewhere (with unknown column name)
  7. mojtabakaviani commented on Nov 23, 2024

    @mojtabakaviani

    @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.

  8. Pepsi1x1 commented on Dec 6, 2024

    @Pepsi1x1

    +1 this would be great to see and would benefit us across a number of projects

  9. added theissue type on Jun 15, 2025
  10. marked Common Table Expression (CTE) #30757 as a duplicate of this issue on Jun 16, 2025
  11. Aykuttonpc commented on Nov 15, 2026

    @Aykuttonpc
    Contributor

    @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:

    • 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.
    from c in EF.With(context.Customers.Where(c => c.IsActive))
    join o in context.Orders on c.Id equals o.CustomerId
    select new { c.Name, o.Total }
    WITH [cte] AS (
        SELECT [c].[Id], [c].[Name]
        FROM [Customers] AS [c]
        WHERE [c].[IsActive] = CAST(1 AS bit)
    )
    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.

  12. AndriySvyryd commented on Nov 15, 2026

    @AndriySvyryd
    Member

    @Aykuttonpc Sounds good
    @cincuranet FYI

  13. roji commented on Nov 17, 2026

    @roji
    MemberAuthor

    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.

  14. Aykuttonpc commented on Nov 17, 2026

    @Aykuttonpc
    Contributor

    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?

  15. roji commented on Nov 20, 2026

    @roji
    MemberAuthor

    What is it blocked on?

    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.

  16. Aykuttonpc commented on Nov 20, 2026

    @Aykuttonpc
    Contributor

    @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.

  17. AndriySvyryd commented on Nov 23, 2026

    @AndriySvyryd
    Member

    Always translating to a CTE sounds ok, especially if that simplifies the logic

  18. Aykuttonpc commented on Nov 23, 2026

    @Aykuttonpc
    Contributor

    Thanks @roji and @AndriySvyryd! Always translating to a CTE makes sense, and it does keep the logic simpler. I'll start working on this.

  19. roji commented on Nov 24, 2026

    @roji
    MemberAuthor

    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.

  20. Aykuttonpc commented on Nov 25, 2026

    @Aykuttonpc
    Contributor

    @roji Thanks, both are handled in #39803:

    • 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions