Skip to content
jshacks.dev
Node.js

How to Use an ORM in Node.js: Prisma vs Drizzle

Compare Prisma and Drizzle in Node.js 26 by defining the same users and posts schema, running the same queries in each, and learn when raw SQL is better.

7 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Node.js, Prisma, JavaScript and TypeScript logos.

An object-relational mapper, or ORM, lets you work with database rows as JavaScript objects and build queries with method calls instead of SQL strings. In Node.js two libraries dominate for TypeScript projects: Prisma, which generates a typed client from a schema file, and Drizzle, which describes tables in TypeScript and keeps the query builder close to SQL. This post builds the same small model in both, a users table and a posts table with a one-to-many relation, and runs the same four operations: create, read with a filter, read with a relation and update. Then it compares them and says when neither is the right choice. The queries target PostgreSQL 17 and Node.js 26. Setup details change between major versions of both tools, so use their documentation, the Prisma docs and the Drizzle docs, for installation and connection configuration, and treat the code here as the model and query layer.

What an ORM gives you, and what it costs

An ORM gives you four things:

  • Typed results. You get an object with known fields instead of an untyped row.

  • Composable queries. You build a filter from conditions in code, without joining strings.

  • Migrations. Schema changes are tracked as files that you apply in order.

  • Protection against injection by default. Values travel as parameters.

The costs are real. An ORM is another layer to learn, it can hide an inefficient query behind a pleasant method call, and it cannot express everything SQL can. Knowing SQL remains necessary. Use the ORM for the large number of ordinary queries and drop to raw SQL for the hard ones.

The model in Prisma

Prisma starts from a schema file, written in its own language, which describes models and relations. The migration tool and the generated client both come from it.

schema.prismaprisma
model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  name  String
  posts Post[]
}

model Post {
  id       Int     @id @default(autoincrement())
  title    String
  public   Boolean @default(false)
  author   User    @relation(fields: [authorId], references: [id])
  authorId Int
}

After editing the schema you run npx prisma migrate dev to create and apply a migration, and npx prisma generate to rebuild the client, which gives you typed methods named after your models. The relation is declared on both sides: Post holds the foreign key authorId, and User.posts is the reverse side that exists only in the client.

The model in Drizzle

Drizzle defines tables in TypeScript, so the schema is ordinary code that you import wherever you need it. There is no generation step for the client, because the types are inferred from these definitions.

schema.tsTypeScript
import { boolean, integer, pgTable, serial, text } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";

export const users = pgTable("users", {
  id: serial("id").primaryKey(),
  email: text("email").notNull().unique(),
  name: text("name").notNull(),
});

export const posts = pgTable("posts", {
  id: serial("id").primaryKey(),
  title: text("title").notNull(),
  public: boolean("public").notNull().default(false),
  authorId: integer("author_id")
    .notNull()
    .references(() => users.id),
});

export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts),
}));

export const postsRelations = relations(posts, ({ one }) => ({
  author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));

The foreign key is declared on the column with references, which creates it in the database. The relations calls are separate, query-time metadata that lets Drizzle's relational query API load related rows, and they do not change the database. You generate migrations with the drizzle-kit command line tool.

Create rows

In both libraries, creating a row returns the inserted data, including the generated id.

create-prisma.tsTypeScript
const ada = await prisma.user.create({
  data: {
    email: "[email protected]",
    name: "Ada",
    posts: {
      create: [{ title: "Notes on engines", public: true }, { title: "Draft" }],
    },
  },
});

console.log(ada);
Text
{ id: 1, email: '[email protected]', name: 'Ada' }

Prisma supports nested writes: the user and both posts are created in one call and one transaction. The result is the user only, because relations are not included unless you ask.

create-drizzle.tsTypeScript
const [ada] = await db
  .insert(users)
  .values({ email: "[email protected]", name: "Ada" })
  .returning();

await db.insert(posts).values([
  { title: "Notes on engines", public: true, authorId: ada.id },
  { title: "Draft", authorId: ada.id },
]);

console.log(ada);
Text
{ id: 1, email: '[email protected]', name: 'Ada' }

Drizzle is explicit. Each insert is a separate statement, returning() gives you the row back, and you pass the foreign key yourself. Wrap the two inserts in db.transaction() if they must succeed together. The extra lines buy you a clear picture of the SQL that runs.

Read with a filter

read-prisma.tsTypeScript
const published = await prisma.post.findMany({
  where: { public: true, author: { email: "[email protected]" } },
  select: { id: true, title: true },
  orderBy: { id: "asc" },
});

console.log(published);
Text
[ { id: 1, title: 'Notes on engines' } ]
read-drizzle.tsTypeScript
import { and, asc, eq } from "drizzle-orm";

const published = await db
  .select({ id: posts.id, title: posts.title })
  .from(posts)
  .innerJoin(users, eq(posts.authorId, users.id))
  .where(and(eq(posts.public, true), eq(users.email, "[email protected]")))
  .orderBy(asc(posts.id));

console.log(published);
Text
[ { id: 1, title: 'Notes on engines' } ]

The results are identical, and the styles differ. Prisma describes the data you want as a nested object and works out the join. Drizzle reads like SQL with the keywords as functions, so anyone who knows SQL can predict the statement. Both infer the result type from the select, so published[0].title is a string and a typo is a compile error.

Read with a relation

Loading a user with their posts is the case where an ORM saves the most code.

relation-prisma.tsTypeScript
const user = await prisma.user.findUnique({
  where: { email: "[email protected]" },
  include: { posts: { select: { title: true } } },
});

console.log(user);
Text
{
  id: 1,
  email: '[email protected]',
  name: 'Ada',
  posts: [ { title: 'Notes on engines' }, { title: 'Draft' } ]
}
relation-drizzle.tsTypeScript
const user = await db.query.users.findFirst({
  where: (u, { eq }) => eq(u.email, "[email protected]"),
  with: { posts: { columns: { title: true } } },
});

console.log(user);
Text
{
  id: 1,
  email: '[email protected]',
  name: 'Ada',
  posts: [ { title: 'Notes on engines' }, { title: 'Draft' } ]
}

Drizzle's db.query API is the relational layer that uses the relations definitions from earlier. Both produce a nested object. Look at the logged SQL once in development, because nested loading can issue more than one query or build a large join, and you should know which one you are paying for.

Update

update-prisma.tsTypeScript
const updated = await prisma.post.update({
  where: { id: 2 },
  data: { public: true },
});

console.log(updated.public);
Text
true
update-drizzle.tsTypeScript
import { eq } from "drizzle-orm";

const [updated] = await db
  .update(posts)
  .set({ public: true })
  .where(eq(posts.id, 2))
  .returning();

console.log(updated.public);
Text
true

Prisma's update throws if the record does not exist. Drizzle returns an empty array in that case, so updated would be undefined, and you decide what that means. Forgetting the where in Drizzle's update changes every row, which is the same as in SQL, so it is worth a lint rule or a code review habit.

Comparison

ConcernPrismaDrizzle
SchemaSeparate schema file, generates a clientTypeScript files, no client generation
Query styleObject arguments, hides joinsSQL-like builder, plus a relational API
FeelHigher level, fewer decisionsCloser to SQL, more explicit
Raw SQLAvailable through raw query methodsTemplate tag sql mixes freely with builders
Migrationsprisma migratedrizzle-kit
Learning curveLearn its schema language and clientLearn the builder, which mirrors SQL

Neither is better in general. Choose Prisma if you value a single schema file and a high-level API that keeps code short for typical application queries. Choose Drizzle if you think in SQL, want the generated statements to be predictable, or want schemas as plain TypeScript with no extra build step. Check the bundle and startup implications if you deploy to serverless or edge environments, since the runtimes differ and the documentation lists the supported drivers for each.

When to use raw SQL instead

Both libraries let you write SQL when the builder cannot express a query, such as window functions, recursive queries or database-specific features. Use them for reports and bulk operations. Keep parameters as parameters in raw queries too.

raw.tsTypeScript
import { sql } from "drizzle-orm";

const rows = await db.execute(
  sql`SELECT author_id, COUNT(*) AS total FROM posts WHERE public = ${true} GROUP BY author_id`,
);

console.log(rows.rows);
Text
[ { author_id: 1, total: '2' } ]

The sql template tag turns interpolated values into parameters, not into string concatenation, so ${true} is sent as a bound value. The count arrives as a string because PostgreSQL's COUNT is a 64-bit integer, which the underlying driver returns as text. Prisma's $queryRaw tagged template works the same way.

Habits that keep ORM code healthy

  • Select only what you need. Fetching whole rows and relations by default wastes memory and bandwidth.

  • Watch for N+1 queries. Loading related data inside a loop issues one query per item. Use include, with or a join to load it once.

  • Log queries in development. Seeing the generated SQL is the fastest way to learn what the ORM does.

  • Keep migrations in version control and run them as a deploy step, never from application startup in several instances at once.

  • Do not leak the models. Map database objects to the shapes your API returns, so a new column is not exposed by accident.

Taggedbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.