© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•2y ago•
3 replies
AH

Self-Join on a CTE

Is it possible to perform a self-join on a CTE?

The main problem is that I cannot alias the CTE for the self-join operation. This prevents me from referencing the previous year's data within the same query. The documentation example demonstrates how to alias and self-join a regular table, but I am unsure how to apply this to a CTE.

Below is a minimal code snippet demonstrating the issue:

const cte = ctx.db.main.$with("cte").as(
  ctx.db.main
    .select({
      year: MainTable.Year,
    })
    .from(MainTable)
);

// can't do this
const cteAlias = alias(cte, "parent");

return ctx.db.main
  .with(cte)
  .select({
    prevYear: sql<number>`CAST(SUM(${cteAlias.year} - 1) AS numeric)`,
  })
  .from(cte)
  .leftJoin(cteAlias, eq(cteAlias.id, cte.id));
const cte = ctx.db.main.$with("cte").as(
  ctx.db.main
    .select({
      year: MainTable.Year,
    })
    .from(MainTable)
);

// can't do this
const cteAlias = alias(cte, "parent");

return ctx.db.main
  .with(cte)
  .select({
    prevYear: sql<number>`CAST(SUM(${cteAlias.year} - 1) AS numeric)`,
  })
  .from(cte)
  .leftJoin(cteAlias, eq(cteAlias.id, cte.id));
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Self join breaks return type
Drizzle TeamDTDrizzle Team / help
13mo ago
Getting type from a CTE
Drizzle TeamDTDrizzle Team / help
10mo ago
Type issue when creating self join
Drizzle TeamDTDrizzle Team / help
3y ago