© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•2mo ago
stefanprobst

INSERT with CTE

drizzle orm📚sql
is it currently possible to express the following in drizzle syntax?

`ts
const entities = [
  ["My first post", "my-first-post"],
  ["My second post", "my-second-post"],
];

await db.execute(sql`
  WITH
  "input" ("title", "slug") AS (
    VALUES
      ${sql.join(entities, sql`, `)}
  ),
  "new" AS (
    INSERT INTO ${schema.entities} ("slug")
    SELECT "slug"
    FROM "input"
    RETURNING "id", "slug"
  )
  INSERT INTO ${schema.posts} ("id", "title")
  SELECT "new"."id", "input"."title"
  FROM "new"
  JOIN "input" USING ("slug");
`);
`ts
const entities = [
  ["My first post", "my-first-post"],
  ["My second post", "my-second-post"],
];

await db.execute(sql`
  WITH
  "input" ("title", "slug") AS (
    VALUES
      ${sql.join(entities, sql`, `)}
  ),
  "new" AS (
    INSERT INTO ${schema.entities} ("slug")
    SELECT "slug"
    FROM "input"
    RETURNING "id", "slug"
  )
  INSERT INTO ${schema.posts} ("id", "title")
  SELECT "new"."id", "input"."title"
  FROM "new"
  JOIN "input" USING ("slug");
`);
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

Update with CTE
Drizzle TeamDTDrizzle Team / help
8mo ago
CTE / WITH + alias
Drizzle TeamDTDrizzle Team / help
13mo ago
CTE / WITH + alias
Drizzle TeamDTDrizzle Team / help
13mo ago
`with` with insert
Drizzle TeamDTDrizzle Team / help
2y ago