© 2026 Hedgehog Software, LLC

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

Effectively mixing QueryBuilder and sql`` using CTEs

Is it possible to amend Drizzle QueryBuilder queries with custom SQL?

For example, I have a query composing of an update, a CTE and a returning clause. The query however cannot execute because its missing a FROM clause that actual "connects" the CTE and the update query. Drizzle does not support from on its update or insert query builders. I'd like to "hack" that from clause in the otherwise QueryBuilder constructed query. Like sql``.append, but for QueryBuilder. Is there a way to do that? Example code:

const q = await db
    .with(myCte)
    .update(myTable)
    .set({ myCol: 'val' })
    // Eample 1: This API doesnt exist
    //.from(myCte)
    // Example 2: This API doesnt exist
    //.appendSQL(sql`from ${myCte}`)
    .where(eq(myTable.myCol. myCte.myCol))
    .returning({col: myCte.myCol});
const q = await db
    .with(myCte)
    .update(myTable)
    .set({ myCol: 'val' })
    // Eample 1: This API doesnt exist
    //.from(myCte)
    // Example 2: This API doesnt exist
    //.appendSQL(sql`from ${myCte}`)
    .where(eq(myTable.myCol. myCte.myCol))
    .returning({col: myCte.myCol});


If not, how do I obtain the SQL for a CTE? I could construct the update query manually and just pull in the CTE "pre-built" into the custom sql. For example:

  const customSql = sql`with ${myCte} update ${myTable} set ${myTable.myCol} = ${'val'} from ${myCte} where ${myTable.myCol} = ${myCte.myCol} returning ${myCte.myCol}`
  const customSql = sql`with ${myCte} update ${myTable} set ${myTable.myCol} = ${'val'} from ${myCte} where ${myTable.myCol} = ${myCte.myCol} returning ${myCte.myCol}`


The
${myCte}
${myCte}
use just inserts the CTE's alias, which is the required behavior in the second case, but not the first where I need the actual CTE table sql. How do I get that so I can construct my own custom update using CTEs?
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

Recursive CTEs
Drizzle TeamDTDrizzle Team / help
2y ago
PgCore: QueryBuilder Issue
Drizzle TeamDTDrizzle Team / help
17mo ago
MySQL Standalone queryBuilder?
Drizzle TeamDTDrizzle Team / help
3y ago
Typed results from QueryBuilder
Drizzle TeamDTDrizzle Team / help
9mo ago