Creator
Database

Queries

How to query the database and use the pre-built helper functions.

All queries use the db client exported from lib/db/index.ts. Pre-built helpers live in lib/db/queries/.

Select

import { db } from "@/lib/db";
import { users } from "@/lib/db/schema";
import { eq } from "drizzle-orm";

const [user] = await db
  .select()
  .from(users)
  .where(eq(users.id, userId))
  .limit(1);

Insert

const [newUser] = await db
  .insert(users)
  .values({
    email: "user@example.com",
    name: "John",
    role: "user",
  })
  .returning();

Update

const [updated] = await db
  .update(users)
  .set({ name: "Jane", updatedAt: new Date() })
  .where(eq(users.id, userId))
  .returning();

Delete

await db.delete(users).where(eq(users.id, userId));

Cascading deletes are handled by foreign key constraints in the schema — deleting a user automatically removes their accounts, subscriptions, and tokens.

Adding a new query

Create a new file in lib/db/queries/ or add to an existing one. Follow the same pattern: import db and your table, write an exported async function, and use it in your API route or server component.

On this page

We use cookies to ensure you get the best experience on our website. For more information on how we use cookies, please see our cookie policy.