Logo

dev-resources.site

for different kinds of informations.

How to Write a SQL Subquery with Drizzle ORM

Published at
6/16/2024
Categories
sql
drizzle
orm
mysql
Author
gitdagray
Categories
4 categories in total
sql
open
drizzle
open
orm
open
mysql
open
Author
9 person written this
gitdagray
open
How to Write a SQL Subquery with Drizzle ORM

I need to write a SQL select query that joins a couple of tables.

No problem.

However, I also need to join that query with the results of another query.

This is possible in SQL with a subquery.

I am using Drizzle ORM to write type-safe queries instead of just raw SQL statements.

I create the main query BEFORE adding in the subquery:

import { db } from "@/index"
import { plant, genus } from "@/schema"
import { eq, or, like } from "drizzle-orm"

const plantData = await db.select({
        ID: plant.plantVarietyInfoId,
        Genus: genus.description,
}).from(plant)
        .leftJoin(genus, eq(plant.genusId, genus.id))
        .where(or(
            like(plant.plantVarietyInfoId, `%${searchTerm}%`),
            like(genus.description, `%${searchTerm}%`),
        ))
        .orderBy(genus.description)
Enter fullscreen mode Exit fullscreen mode

Next, I need to add in a max ship week value from a Shipping Records table. This table has a many-to-many relationship with the Plant table.

To begin, I create the ship week subquery above the main query in the file:

import { db } from "@/index"
import { plant, genus } from "@/schema"
import { eq, or, like, max } from "drizzle-orm"

const shipWeekQuery = db.select({
        ShipWeek: max(shippingRecord.expectedShipWeek).as('shipWeek'),
        ID: shippingRecord.plantVarietyInfoId,
    }).from(shippingRecord)
        .groupBy(shippingRecord.plantVarietyInfoId)
        .as('shipWeekRecords')
Enter fullscreen mode Exit fullscreen mode

I need to use as() for aliases in the above subquery twice. Once on the max ship week value, and once on the overall subquery. Without these, the subquery will not work.

When adding the subquery ShipWeek value to the main query, I need to refer to the shipWeekQuery.

Finally, I can add the subquery to the main query with a left join:

const plantData = await db.select({
        ID: plant.plantVarietyInfoId,
        Genus: genus.description,
        ShipWeek: shipWeekQuery.ShipWeek,
}).from(plant)
        .leftJoin(genus, eq(plant.genusId, genus.id))
        .leftJoin(shipWeekQuery, eq(plant.plantVarietyInfoId, shipWeekQuery.ID))
        .where(or(
            like(plant.plantVarietyInfoId, `%${searchTerm}%`),
            like(genus.description, `%${searchTerm}%`),
        ))
        .orderBy(genus.description)
Enter fullscreen mode Exit fullscreen mode

You can read more about creating a select from subquery in the Drizzle ORM docs.


Let's Connect!

Hi, I'm Dave. I work as a full-time developer, instructor and creator.

If you enjoyed this article, you might enjoy my other content, too.

My Stuff: Courses, Cheat Sheets, Roadmaps

My Blog: davegray.codes

YouTube: @davegrayteachescode

X: @yesdavidgray

GitHub: gitdagray

LinkedIn: /in/davidagray

Patreon: Join my Support Team!

Buy Me A Coffee: You will have my sincere gratitude

Thank you for joining me on this journey.

Dave

drizzle Article's
30 articles in total
Favicon
Setting Up Drizzle & Postgres with tRPC and Next.js App
Favicon
Placegoose: Building data APIs with HONC
Favicon
Quick REST API with Hono JS and Drizzle ORM
Favicon
Remix Drizzle Auth Template
Favicon
Resolving the `DO $$` Issue in Drizzle ORM with Nile Postgres
Favicon
How to use ORMs (Prisma / Drizzle / Knex.js) in a TypeScript backend built with Encore.ts
Favicon
NextJS + Drizzle -- 8 Things I Learned Spinning up a New Project
Favicon
How to integrate Drizzle ORM with Nest Js
Favicon
Build Nextjs 15 & React 19 Dashboard App Step By Step
Favicon
Verifying Lemon Squeezy Subscription Webhooks in Cloudflare Workers
Favicon
Drizzle Vs Prisma
Favicon
Nuxt3 x MySQL (& Drizzle ORM)
Favicon
Building a Scalable REST API with TypeScript, Express, Drizzle ORM, and Turso Database: A Step-by-Step Guide
Favicon
Prisma vs. Drizzle: A Comprehensive Guide for Your NextJS Project
Favicon
Next.js authentication using Clerk, Drizzle ORM, and Neon
Favicon
I created basic analytics with Vercel Postgres, Drizzle & Astro
Favicon
How to Write a SQL Subquery with Drizzle ORM
Favicon
Drizzle ORM in a Supabase edge function
Favicon
Drizzle or Prisma? I Built an App Twice to Find Out Which Is Better
Favicon
Drizzle ORM, NextAuth and Supabase
Favicon
Drizzle ORM SQLite and Nuxt - Integrating Nuxt Auth, Part 2
Favicon
Drizzle ORM SQLite and Nuxt - Integrating Nuxt Auth, Part 1
Favicon
Drizzle ORM, SQLite and Nuxt JS - Getting Started
Favicon
How I implemented Drizzle ORM with Nextauth
Favicon
How to Build a Contextual Chatbot with LangChain and PostgreSQL + Drizzle ORM
Favicon
Building a full stack app with Remix & Drizzle ORM: Drizzle Relations & Deployment
Favicon
Building a full stack app with Remix & Drizzle ORM: Upload images to Cloudflare
Favicon
Building a full stack app with Remix & Drizzle ORM: Project setup
Favicon
Building a full stack app with Remix & Drizzle ORM: Folder structure
Favicon
Building a full stack app with Remix & Drizzle ORM: Register & Login users

Featured ones: