© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•15mo ago
Jetrak

Nested select in an insert

Hi, is there a better way to use nested
select
select
inside an
insert
insert
than to just use the
sql
sql
function?

For example I have this function:
  static async upsert(idPerson: number, studyType: StudyType) {
    const idStudyTypeSql = sql`(select id_study_type from study_type where study_type = ${studyType})`;
    await db
      .insert(student)
      .values({
        idPerson,
        idStudyType: idStudyTypeSql,
      })
      .onConflictDoUpdate({
        target: student.idPerson,
        set: {
          idStudyType: idStudyTypeSql,
        },
      });
  }
  static async upsert(idPerson: number, studyType: StudyType) {
    const idStudyTypeSql = sql`(select id_study_type from study_type where study_type = ${studyType})`;
    await db
      .insert(student)
      .values({
        idPerson,
        idStudyType: idStudyTypeSql,
      })
      .onConflictDoUpdate({
        target: student.idPerson,
        set: {
          idStudyType: idStudyTypeSql,
        },
      });
  }


It works well, but by using the
sql
sql
I lose the benefit of typescript and I have to execute the query to verify that it works as expected. If I, for example, use non-existing column in the
sql
sql
, I won't get any warnings.

I could create a separate query to get the
id_study_type
id_study_type
, but I would prefer to have just one database call if possible.

    const idStudyType = (
      await db
        .select({ id: studyType.idStudyType })
        .from(studyType)
        .where(eq(studyType.studyType, studyTypeEnum))
    )[0]?.id;
    const idStudyType = (
      await db
        .select({ id: studyType.idStudyType })
        .from(studyType)
        .where(eq(studyType.studyType, studyTypeEnum))
    )[0]?.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

Infer insert model for select in "Insert into ... select"
Drizzle TeamDTDrizzle Team / help
15mo ago
insert from select
Drizzle TeamDTDrizzle Team / help
12mo ago
Nested insert not working
Drizzle TeamDTDrizzle Team / help
2y ago
Select in nested findMany query ?
Drizzle TeamDTDrizzle Team / help
2y ago