Estimate project
← All posts

5 Reasons Drizzle ORM Beats Traditional JavaScript ORMs

Discover five reasons to give Drizzle ORM a closer look, particularly when it comes to performance, complete control over queries, and a clean TypeScript architecture.

18 min read
typescriptJavaScriptORMDrizzle

The TypeScript ecosystem is growing fast and bringing better, safer alternatives to traditional JavaScript ORMs (Object Relational Mapping). Drizzle and Prisma are among the most notable of them. Although both let developers work with databases in a type-safe manner, they embody different philosophies.

In this article, I’ll concentrate on 5 reasons why Drizzle ORM deserves your attention, particularly when it comes to:

  • performance,
  • complete control over queries,
  • a clean TypeScript architecture.

1. First-Class Developer Experience

Drizzle ORM is built for developers who want complete insight into and control over their data layer, without sacrificing comfort while coding.

It provides:

  • great IntelliSense support, with auto-completion, type inference, and inline documentation,
  • type safety at compile time, so if a query is incorrect, TypeScript will warn you,
  • no client generation step, which means fewer moving parts and faster iteration.

Regarding that last point: unlike ORMs such as Prisma, Drizzle doesn’t need an extra step to generate a client library from the schema. In Prisma, you define the database schema in a .prisma file and then, to produce a custom TypeScript client, you have to run the command:

npx prisma generate

The resulting client acts as the interface to the database and has to be regenerated each time the schema changes.

Kysely is another well-known library in the TypeScript ecosystem. It’s a lightweight, type-safe SQL query builder that likewise aims to make developers’ lives easier. Like Prisma, Kysely needs a separate step to get type information into the code. Developers typically either write interfaces by hand or rely on external tools such as kysely-codegen, which inspects the database schema and produces TypeScript definitions from the real tables:

So although Kysely provides a lot of flexibility and strong typings, it also adds extra steps and tooling to keep types aligned with the database. The schema frequently lives outside the application code, and keeping the two connected can be error-prone or result in inconsistent typings if someone skips the generation step.

Drizzle does away with all of that. Rather than depending on schema files and code generation, Drizzle has developers define the database schema directly in TypeScript, and queries are written against that schema with native TypeScript expressions. There’s no intermediate client layer, no compilation step, and no chance of the types drifting away from the real schema.

The outcome is:

  • quicker iteration (developers needn’t wait for a client to be generated),
  • leaner toolchains,
  • fewer bugs caused by schemas and clients falling out of sync,
  • smoother onboarding for new developers (since what they see in the code is exactly what they get).

Drizzle’s approach makes the developer experience more transparent and direct, and fits modern TypeScript workflows better.

A table definition could look like this:

import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').primaryKey().defaultRandom(),
  email: varchar('email').notNull().unique()
  createdAt: timestamp('created_at')
.notNull()
.defaultNow(),
});

And a query against that schema could look like this:

import { eq } from 'drizzle-orm';
import db from '../db';
import { users } from '../db/schema';

export const getAllUsers = async () => {
  return await db.select().from(users)
};

2. Queries API - typed and simple

Drizzle takes an SQL-first approach while keeping queries ergonomic and easy to read. It doesn’t make developers learn a domain schema language. With Prisma, by contrast, developers describe databases in Prisma Schema Language, and Prisma uses that schema to generate a TypeScript client. You can learn more about it on the Prisma website.

Prisma conceals SQL and offers a query API centered on working with entities. Writing a query feels like working with objects that resemble ordinary JavaScript:

// Prisma query API

const users = await prisma.users.findMany({
  where: {
    OR: [
      { email: { contains: 'mail.com' } },
      { name: { startsWith: 'C' } }
    ],
    articles: { some: { published: true } }
  },
  select: {
    id: true,
    email: true,
    _count: { select: { articles: true } }
  },
  take: 5
});

Queries like this let developers operate at a high level. They don’t have to think about joins or raw SQL – they simply describe what they want, and Prisma takes care of everything else under the hood.

Drizzle embraces SQL concepts and offers a query API that feels like writing SQL directly in TypeScript – expressive, predictable, and close to the database layer.

Unlike solutions such as Prisma, which depend on a separate domain-specific language (DSL) and a code generation step to create a typed client, Drizzle works entirely inside the TypeScript codebase. Both the database schema and the queries are defined in code, and type safety is inferred straight from those definitions, with no need for external schema files or generated clients.

This simplifies the development workflow and eliminates the need to keep the database model and the client API in sync.

When a programmer changes the schema, the TypeScript types update on their own and no additional steps are required. This gives you more control over what’s going on:

// Drizzle query API

const users = await db.select({
  id: users.id,
  email: users.email,
  articleCount: sql`count(${articles.id})`
.as('article_count')
})
.from(users)
.leftJoin(articles, eq(users.id, articles.authorId))
.where(
  or(
    like(users.email, '%mail.com%'),
    like(users.name, 'C%')
  )
)
.groupBy(users.id, users.email)
.having(gt(sql`count(${articles.id})`, 0))
.limit(5);

This API provides:

  • predictable behavior (only what you write gets executed),
  • complete TypeScript coverage,
  • no hidden magic – full visibility into which query is sent.

What’s more, because Drizzle queries look a lot like raw SQL written in template literals or structured expressions, a range of editor extensions can improve the developer experience. Visual Studio Code, for instance, has extensions such as:

  • SQL Lit,
  • SQL tagged template literals.

Such extensions can check SQL syntax or flag typical mistakes right in the editor, making it easier to spot errors early, before the application is even run.

That said, to make developers’ lives easier, Drizzle also provides a higher-level relational API:

const userWithArticles = await db.query.users.findFirst({
  where: eq(users.id, 1),
  with: {
    articles: {
      where: eq(articles.published, true),
      limit: 5
    }
  }
});

3. Prepared statements - performance boost

Drizzle supports prepared statements out of the box, giving developers a simple way to improve performance, particularly in serverless environments.

To see why prepared statements boost performance, let’s look at what goes on under the hood when a query is executed from Drizzle or another ORM. Running a query against a database involves several steps, as the figure below shows:

executing query agains sql database

The process shown above takes place every time SQL is executed through the query builder. Usually this isn’t a big deal and rarely causes performance problems. But when developers deal with very complex queries – for example ones with many joins and a range of clauses – parsing, analyzing, and compiling get needlessly repeated on every execution. This happens even if the structure of the query stays the same and only the parameters change.

If steps 1, 2, and 3 could be done in advance and their results reused, the overhead could drop considerably. The trick is to keep supporting dynamic parameters while avoiding repeated compilation. That’s precisely what prepared statements allow: they replace repeatedly running those first steps with a precompiled query structure that takes dynamic inputs at runtime:

prepare statement in executing query

Prepared statements mean that:

  • the database can reuse the query plan, cutting parsing time,
  • query latency drops – excellent for cold starts,
  • you avoid runtime string interpolation or manual sanitization, both frequent causes of SQL injection vulnerabilities. Prepared statements keep the query structure apart from the data, so user input is always safely parameterized and never runs as part of the SQL logic.

Here’s what a prepared statement could look like:

const db = drizzle(...);
const prepared = db.select()
.from(users)
.prepare("statement_name");

const res1 = await prepared.execute();
const res2 = await prepared.execute();
const res3 = await prepared.execute();

And here’s one with a placeholder (for when a dynamic runtime value needs to be embedded):

const u1 = db
  .select()
  .from(users)
  .where(eq(users.id, sql.placeholder('id')))
  .prepare("u1");

await u1.execute({ id: 1 }) // SELECT * FROM users WHERE id = 1
await u1.execute({ id: 2 }) // SELECT * FROM users WHERE id = 2

Unlike Prisma, which builds and runs SQL at runtime via a compiled client, Drizzle’s prepared statements sit closer to the database and deliver much faster cold start times – a crucial factor in serverless deployments such as AWS Lambda.

4. No runtime magic - clean and declarative code

Drizzle doesn’t make any assumptions about how queries ought to behave. There’s no hidden state, no complicated client generation, and no abstraction layers standing between your code and SQL.

In Prisma, the schema is defined in the .prisma file, after which a CLI has to be run to generate the client. Kysely has a comparable process, where type safety is usually obtained by generating TypeScript interfaces from the database schema with external tools. Either way, keeping the source schema and the generated types in sync calls for an extra build step and more tooling.

With Drizzle, by contrast:

  • programmers declare the schema and queries in plain TypeScript,
  • there’s no client layer that could misread what the developer meant,
  • queries are always transparent – the SQL structure is right there, visible in the code.

The result is more dependable debugging and fewer surprises in production.

For a deeper comparison, see the “Drizzle vs Prisma - different translation strategies” section below.

5. Minimal and composable design

Drizzle follows a modular, composable design philosophy. Rather than packing everything into one monolithic toolchain, it provides small, focused tools:

  • drizzle-orm: the query builder,
  • drizzle-kit: an optional CLI for managing migrations,
  • adapters for particular databases (such as pg, mysql, sqlite) – with no needless bloat.

Thanks to this, Drizzle is:

  • simple to integrate with any backend framework (Express, Bun, Hono, etc.),
  • lightweight enough for edge and serverless deployments,
  • a perfect fit for microservice architecture or modular monorepos.

This modularity enables flexible project layouts and a clean separation of concerns. Because Drizzle needs neither a centralized code generation step nor a monolithic client, it fits nicely into service-oriented or layered architectures. Confining database interactions to particular modules or packages becomes easier, without imposing a global runtime or a shared client instance.

On top of that, by steering clear of tightly coupled abstractions and sticking to standard TypeScript and SQL constructs, Drizzle stays fairly lightweight and adapts to various setups, from traditional server environments to edge runtimes and serverless platforms.

Drizzle vs Prisma - different translation strategies

Although Drizzle and Prisma both aim to make database access smoother, they go about it in fundamentally different ways.

Prisma: uses a schema-first model, prioritizing simplicity and abstraction. Developers define a data model in a custom schema language, and Prisma generates a client with an OOP-style API. It hides SQL, but this can also bring performance problems, less flexibility, and leaky abstractions.

Drizzle: adopts an SQL-first, schema-as-code, TypeScript-native approach. Its motto is “If you know SQL, you know Drizzle”. It puts the emphasis on transparency, control, and predictability. There’s no client generation, no hidden behavior, and nothing unexpected at runtime. It’s the perfect tool for developers who want to stay close to the database while enjoying strong typing and IDE support.

Data modeling

Let’s now look at how a database schema is defined and how developers can refer to it when querying data:

// Prisma ORM

model User {
  id         Int     @id @default(autoincrement())
  name       String?
  email      String  @unique
  articles Article[]
}

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

After that, Prisma generates a type-safe client that you can use in your code:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

async function main() {
  const user = await prisma.user.create({
    data: {
      email: 'john@doe.com',
      name: 'John',
      articles: {
        create: { title: 'Article no. 1' }
      }
    },
    include: { articles: true }
  })
}

This arrangement neatly separates the schema from the rest of the application code and gives you a single source of truth. The downside, though, is that developers have to run a code generation step every time the schema changes.

Drizzle’s approach relies on a programmatic TypeScript API to define the schema:

import {
  boolean,
  integer,
  pgTable,
  serial,
  text,
  uniqueIndex,
  varchar,
} from 'drizzle-orm/pg-core'

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: varchar('name', { length: 256 }),
  email: varchar('email', { length: 256 }).unique(),
})

export const articles = pgTable('articles', {
  id: serial('id').primaryKey(),
  title: varchar('title', { length: 256 }).notNull(),
  content: text('content'),
  published: boolean('published'),
  authorId: serial('author_id').references(() => users.id),
});

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

With Drizzle, I can use these schema objects directly in my queries, for example:

async function main() {
  const user = await db.insert(users)
    .values({ email: 'john@doe.com', name: 'John' })
    .returning();

  await db.insert(articles)
    .values(
      { title: 'Article no. 1', authorId: user.id }
    );

  const userWithArticles = await db.query.users
    .findFirst({
      where: (users, { eq }) => eq(users.id, user.id),
   with: { articles: true }
    });
}

Drizzle relies on the TypeScript compiler to catch schema-related problems, so the application reflects any schema change right away, without rebuilding or running code generation.

Relations

Handling relationships between tables is one of the trickier parts of working with databases, particularly in a TypeScript setting. How Prisma and Drizzle deal with relationships reveals their contrasting philosophies of ORM design.

Prisma regards relationships as a core part of its system. They’re built straight into both the schema and the generated client. In Prisma Schema Language, developers declare relationships in a clear, structured manner:

model User {
  id         Int        @id @default(autoincrement())
  articles   Article[]   // One-to-many relationship
  profile    Profile?    // One-to-one relationship
}

model Article {
  id       Int  @id @default(autoincrement())
  author   User @relation(fields: [authorId], references: [id])
  authorId Int
}

model Profile {
  id     Int  @id @default(autoincrement())
  user   User @relation(fields: [userId], references: [id])
  userId Int  @unique
}

This relationship-centric design extends to how developers write queries. Related data is created, fetched, and updated with a tidy, nested syntax:

const user = await prisma.user.create({
  data: {
    email: 'john@doe.com',
    articles: {
      create: [{ title: 'Article no. 1' }]
    },
    profile: {
      create: { bio: 'The programmer' }
    }
  }
});

// Querying with relationship filters
const users = await prisma.user.findMany({
  where: {
    articles: {
      some: { published: true }
    }
  }
});

The strength of Prisma’s system lies in how greatly it simplifies complex data operations. Developers can carry out multi-level operations (such as creating linked records) in one query, while Prisma maintains data integrity and consistency behind the scenes. There’s no need to deal with foreign keys by hand or write several queries to keep everything consistent.

Drizzle goes a different way. Tables and relationships are defined separately: developers use the schema builder to define tables and a distinct relations API to link them:

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

export const articles = pgTable('articles', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  authorId: serial('author_id').references(() => users.id)
});

// Relationship definitions
export const usersRelations = relations(users, ({ many }) => ({
  articles: many(articles)
}));

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

This design is more explicit – it keeps the data structure apart from its associations. To query related data, Drizzle provides a relational API that lets developers load associated records in an intuitive way:

const userWithArticles = await db.query.users.findFirst({
  with: {
    articles: {
      where: eq(articles.published, true),
      limit: 5
    }
  }
});

The key difference is how tightly relationships are integrated. Prisma weaves them deeply into both reads and writes, automating a lot of the heavy lifting. Drizzle keeps things more separate and asks the developer to be more intentional, giving up some convenience in exchange for fine-grained control.

SQL transactions with the Drizzle ORM

Keeping data consistent and intact is vital in any application that performs several related database operations. When a group of queries must all succeed or all fail together, transactional control is indispensable.

Picture a content publishing system that saves new articles in a database. Publishing an article could involve:

  • inserting the article record,
  • linking it to an author,
  • attaching a set of tags.

If the article gets inserted but tag assignment fails (say, because of a missing foreign key or a constraint violation), the system may be left with incomplete data – an orphaned article lacking any context. Such inconsistencies are hard to spot and fix after the fact.

To prevent problems like this, SQL databases offer transactions, which bundle a series of operations into one atomic unit. Transactions adhere to the ACID principles:

  • Atomicity: either every operation in the transaction succeeds, or none of them takes effect.
  • Consistency: the database is in a valid state both before and after the transaction.
  • Isolation: concurrent transactions don’t interfere with one another’s intermediate state.
  • Durability: once committed, changes survive even if the system fails.

Transactions with Drizzle

Drizzle ORM fully supports transactional operations through the underlying database adapter. In PostgreSQL, this is done with a simple, intuitive API in which the transaction context is handed over as an isolated tx instance (https://orm.drizzle.team/docs/transactions).

Below is an example of a transaction that inserts an article, assigns an author, and attaches tags – all inside a single block of operations:

const db = drizzle(...);

await db.transaction(async (tx) => {
  const [article] = await tx
    .insert(articles)
    .values({
      title: 'Understanding Drizzle Transactions',
      published: true,
    })
    .returning();

  await tx.insert(articleAuthors).values({
    articleId: article.id,
    authorId: '7d4ae4dc-faac-4d48-9320-6865110aa0d5',
  });

  await tx.insert(articleTags).values([
    { articleId: article.id, tagId: 'typescript' },
    { articleId: article.id, tagId: 'database' },
  ]);
});

Should any operation within the transaction block fail, every earlier change is rolled back automatically. You don’t have to issue ROLLBACK or COMMIT commands yourself – Drizzle does that under the hood.

This transactional model gives you:

  • Safety: partial writes never persist.
  • Clarity: the transactional intent is explicit and scoped.
  • Composability: any part of the application can use transactions safely without altering the database interface.

Savepoints and nested transactions

In more involved scenarios, you may need to commit or roll back only certain parts of a transactional workflow. That’s where savepoints and nested transactions come in handy.

Drizzle ORM supports nested transactional operations by reusing the tx object passed into the transactional block. If a nested block fails, only that part gets rolled back – the outer transaction is unaffected unless the error is propagated.

This makes it possible to build modular, resilient transactional flows. Here’s an example:

const db = drizzle(...);

await db.transaction(async (tx) => {
  await tx.insert(logs).values(
    { message: 'Starting import...' }
  );

  try {
    await tx.transaction(async (tx2) => {
      await tx2.insert(importQueue).values(
        { fileId: '9bb1fceb' }
      );
      await tx2.insert(importResults).values(
        { fileId: 'cb1f1766', success: true }
      );
    });
  } catch (error) {
    await tx.insert(logs).values(
      { message: 'Import failed. Rolling back nested transaction.' }
    );
    // The nested transaction is rolled back, the outer one continues.
  }

  await tx.insert(logs).values(
    { message: 'Outer transaction continues...' }
  );
});

This structure:

  • prevents failures from spreading needlessly,
  • helps keep side effects modular,
  • provides fine-grained control over how rollbacks behave.

Even though Drizzle lets you nest transaction blocks, PostgreSQL doesn’t natively support true nested transactions. PostgreSQL allows just one active transaction per connection. To emulate nesting, Drizzle uses SQL savepoints internally.

When a nested tx.transaction(...) is invoked, Drizzle issues a SAVEPOINT. If an error is raised, it runs a ROLLBACK TO SAVEPOINT. The outer transaction carries on unaffected unless the error is rethrown.

This implementation delivers a consistent developer experience across database backends while respecting what PostgreSQL’s transactions can actually do.

Practical summary of Drizzle ORM concepts

To round off this article, let’s take a look at an application I built to demonstrate all the key Drizzle ORM concepts discussed above.

The main aspects of the application covered in this article are:

  • a clean split between reading and writing responsibilities via two separate services – writer and reader,
  • a centralized Drizzle ORM schema definition kept in a shared module,
  • strict control of database permissions at the PostgreSQL level through dedicated database users with restricted privileges,
  • reusable, type-safe data access and validation logic shared by both services,
  • simple yet meaningful REST API endpoints for read and write operations,
  • a docker-based setup with initialization scripts that bootstrap users, roles and permissions.

Project structure

The repository is split into three top-level folders:

shared/

This folder holds the Drizzle ORM schema definitions, validators, and the shared logic for read-only endpoints, such as:

  • GET /users
  • GET /users/:id
  • GET /activities
  • GET /activities/:id

Both reader and writer use these endpoints.

reader/

A standalone application with read-only access. It imports the shared schema and endpoints, but connects to the database as a read-only user that has only SELECT privileges.

writer/

A second standalone service that imports the shared schema and read endpoints, and additionally provides write operations such as:

  • POST /users
  • PUT /users/:id
  • PATCH /users/:id
  • DELETE /users/:id

It connects as a writer user with full privileges (SELECT, INSERT, UPDATE, DELETE).

Drizzle transactions

The project shows how Drizzle ORM transactions are used. Two main examples illustrate this:

  • creating a user along with an automatic activity (POST /users),
  • updating a user with activity tracking (PATCH /users/:id).

Database roles and security

The PostgreSQL container is set up with docker-compose, and the roles are initialized by SQL scripts (shared/sql/init-users.sql and shared/sql/grant-access.sql) that:

  • create two separate users: writer_user and reader_user,
  • give the writer full privileges
  • give the reader read-only access,
  • revoke every write-related permission from the reader,
  • apply these grants once the schema has been migrated, so they’re enforced correctly.

This setup ensures a strict separation of concerns and prevents accidental mutations in the reader service.

Repository and how to run

Summary

Drizzle ORM is a great option for building modern TypeScript applications with complete control over the data layer. It brings together type safety, performance, and simplicity in a way that sits naturally in today’s JavaScript ecosystem.

Drizzle is particularly worth a try when you’re building microservices, deploying to the edge, or simply need a lightweight, composable ORM. You may well end up writing less code, making fewer mistakes, and enjoying your database layer once more.