How do Drizzle and Prisma work under the hood?
Drizzle is a TypeScript query builder that stays close to SQL. You define tables as TypeScript objects, and each query call (select, where, innerJoin) maps closely to the SQL clause of the same name. At runtime, Drizzle compiles the call chain into a parameterized SQL string and hands it to a driver you install and configure yourself, such as a Postgres, MySQL or SQLite client library. Drizzle does not run its own process or pool connections, and it does not use an intermediate query format. Its relational query API, which fetches nested data, still compiles to SQL that you can log and read.
Prisma is a higher-level data layer. You describe models in its own schema language, and a generator turns that schema into a typed client. Your code calls the client with object-shaped queries such as findMany with include. An engine layer then plans those queries, generates SQL, and assembles the results into nested objects. That engine has changed significantly across releases. It was historically a separate compiled binary, and newer versions have moved toward driver adapters and less native code. Check how the version you run executes queries before assuming anything about its behavior.
This layering explains most of the practical differences between the two tools. SQL generation is rarely the expensive part of a query. Cost comes from what happens around it: how many round trips a relation query makes, how results are serialized and assembled, and how much code and native tooling ships with your deployment. Drizzle adds very little between your code and the driver. Prisma adds more, and in exchange you get schema-driven tooling and a more abstract API.
DRIZZLE PRISMA
+------------------------------+ +--------------------------------+
| App code (TypeScript) | | schema.prisma (models) |
| db.select().from(t).where() | +--------------------------------+
+------------------------------+ | prisma generate
| v
v +--------------------------------+
+------------------------------+ | Generated typed client |
| Drizzle query builder | | app: findMany({ include }) |
| -> parameterized SQL string | +--------------------------------+
+------------------------------+ |
| SQL + params v
v +--------------------------------+
+------------------------------+ | Query engine layer |
| Driver you install | | plans query, generates SQL |
| (Postgres/MySQL/SQLite lib) | | assembles nested objects |
+------------------------------+ | (impl. varies by release) |
| +--------------------------------+
v |
+------------------------------+ v
| Database | +--------------------------------+
+------------------------------+ | Driver / adapter |
| -> Database |
+--------------------------------+
Few layers before the driver More layers: schema, client, engine
Drizzle compiles query-builder calls directly to SQL for a driver you choose, while Prisma routes object-shaped client calls through a generated client and a version-dependent query engine layer that plans the SQL and assembles nested results.
How do you measure ORM query performance honestly?
Start with what the tools emit, not with a stopwatch. Prisma accepts a log option that includes query events, and Drizzle accepts a logger setting. Turn both on and capture the exact SQL for each endpoint you care about. Run that SQL through EXPLAIN ANALYZE against a copy of production-sized data. Two ORMs can return identical rows while one uses an index scan and the other a sequential scan. That plan difference will outweigh any runtime overhead.
| Layer | How to measure | What it reveals |
|---|---|---|
| Emitted SQL | ORM query logging | Query count, joins vs. separate queries |
| Database time | EXPLAIN ANALYZE, pg_stat_statements |
Plan quality, index use |
| ORM-side time | Wall time minus DB time, CPU profiler | Query building, result mapping, serialization |
| End to end | Load test over a real network path | Pool contention, latency effects |
Most published microbenchmarks run against a local database with tiny tables and no connection pool. That removes the network round trip, the query planner's choices and pool waits, which are the costs that dominate a real service.
Illustrative estimate. These inputs are assumed, not measured: a fixed ORM overhead of 0.2 ms per query.
- Cross-zone query: with a 3 ms database round trip, the overhead is about 6% of latency, which is noise.
- Simple lookup in the same zone: a primary-key lookup with a 0.5 ms round trip makes the overhead about 29%. At 2,000 QPS, it consumes roughly 0.4 CPU cores per instance.
High-QPS, simple-lookup endpoints are therefore where ORM overhead deserves profiling.
import { PrismaClient } from '@prisma/client';
import { drizzle } from 'drizzle-orm/node-postgres';
import type { Logger } from 'drizzle-orm/logger';
import { eq } from 'drizzle-orm';
import { Pool } from 'pg';
import { users } from './schema'; // your Drizzle table definition
const url = 'postgres://app:changeme@db.internal:5432/app_staging';
// Prisma: emit query events so we see the exact SQL and the duration Prisma reports.
const prisma = new PrismaClient({ log: [{ emit: 'event', level: 'query' }] });
prisma.$on('query', (e) => {
console.log('[prisma]', e.duration, 'ms', e.query, e.params);
});
// Drizzle: a custom logger captures SQL and params so you can paste them into EXPLAIN ANALYZE.
class SqlCapture implements Logger {
logQuery(query: string, params: unknown[]): void {
console.log('[drizzle]', query, JSON.stringify(params));
}
}
const db = drizzle(new Pool({ connectionString: url, max: 10 }), { logger: new SqlCapture() });
// Wall time per call. Compare it with the database time from EXPLAIN ANALYZE or
// pg_stat_statements; the gap is ORM-side and driver work plus the network round trip.
async function timeIt(label: string, fn: () => Promise<unknown>) {
const start = performance.now();
await fn();
console.log(label, (performance.now() - start).toFixed(2), 'ms wall');
}
async function main() {
// Warm up first so connection setup and query preparation are not counted.
await prisma.user.findUnique({ where: { id: 42 } });
await db.select().from(users).where(eq(users.id, 42));
await timeIt('prisma pk lookup', () => prisma.user.findUnique({ where: { id: 42 } }));
await timeIt('drizzle pk lookup', () => db.select().from(users).where(eq(users.id, 42)));
}
main().finally(() => prisma.$disconnect());
The script turns on SQL logging in both Prisma and Drizzle and times the same primary-key lookup in each, so you can check the emitted SQL with EXPLAIN ANALYZE and compare wall time against database time to estimate ORM-side overhead.
What SQL do relation queries actually generate, and how do you spot N+1?
Relation loading is where the two tools differ most, and where the SQL is hardest to predict from the TypeScript.
Prisma's nested include and select do not map one-to-one onto SQL joins. Depending on the Prisma version, database and configured relation load strategy, a nested read may run as one statement using joins and JSON aggregation, or as several statements: a parent query followed by one batched WHERE ... IN (...) query per relation level. Neither approach is N+1, but the query count and shape can change after an upgrade. Treat the generated SQL as something to re-check, not something you know once. Enabling log: ['query'] on the client prints each statement as it runs.
Drizzle gives you two paths. The core query builder sends exactly the joins you write. The relational query API (db.query.<table>.findMany({ with: ... })) compiles a nested read into a single SQL statement. Passing logger: true to drizzle() prints what goes over the wire.
In either tool's logs, N+1 shows up as one parent query followed by a run of identical statements that differ only in a bound parameter. In production, pg_stat_statements reveals the same pattern: a simple single-row query whose call count is far higher than the request count of the endpoint that issues it. The usual cause is an ORM call inside a loop, such as Promise.all over a list of records, and neither ORM prevents this.
The trade-off is that Drizzle's core builder leaves the join strategy to you. A team that writes a loop of lookups, or joins two one-to-many relations and inflates the row count, will get slower queries than Prisma's batched defaults would have produced.
import { PrismaClient } from '@prisma/client';
import { drizzle } from 'drizzle-orm/node-postgres';
import { inArray } from 'drizzle-orm';
import { Pool } from 'pg';
import * as schema from './schema'; // users, posts + relations() definitions
// Print every SQL statement each ORM sends to the database
const prisma = new PrismaClient({ log: ['query'] });
const pool = new Pool({ connectionString: 'postgres://app:app_password@localhost:5432/app_dev' });
const db = drizzle(pool, { schema, logger: true });
async function main() {
// N+1: one parent SELECT, then 50 identical SELECTs that differ only in the bound
// authorId parameter. Neither ORM stops you from writing this.
const list = await prisma.user.findMany({ take: 50 });
await Promise.all(list.map((u) => prisma.post.findMany({ where: { authorId: u.id } })));
// Prisma nested read: not N+1. Depending on version and relationLoadStrategy,
// the log shows one joined statement or a parent query plus one batched IN query.
await prisma.user.findMany({ take: 50, include: { posts: true } });
// Drizzle relational API: the nested read compiles to a single statement.
await db.query.users.findMany({ limit: 50, with: { posts: true } });
// Drizzle core builder: you pick the strategy. Here, two queries batched by hand.
// A plain LIMIT on a users-posts join would cap rows, not users.
const parents = await db.select().from(schema.users).limit(50);
const ids = parents.map((u) => u.id);
const children = ids.length
? await db.select().from(schema.posts).where(inArray(schema.posts.authorId, ids))
: [];
return { parents, children };
}
main().finally(async () => {
await prisma.$disconnect();
await pool.end();
});
With query logging enabled in both ORMs, an N+1 loop appears as a run of identical statements. Prisma's include, Drizzle's relational API and a hand-written batched query each load the same data in one or two statements.
Which ORM fits serverless and edge deployments?
Runtime footprint is where the two tools differ most. Drizzle is a TypeScript layer that builds SQL strings and passes them to a driver you choose, so the deployed code is roughly your schema, the query builder and that driver. Prisma ships a generated client plus a query engine that turns its query format into SQL. Depending on the Prisma version and build target, that engine has been a native binary, a WebAssembly module or TypeScript code paired with a driver adapter. Bundle size and initialization cost vary with each option, so don't trust general claims, including this one. Build your actual deployment artifact, measure its size, and time the first query on a cold instance.
| Concern | Drizzle | Prisma |
|---|---|---|
| Runtime code | Query builder plus your chosen driver | Generated client plus query engine (form depends on version and target) |
| Cold start cost | Mostly driver and module loading | Client and engine initialization, which you should measure per build |
| Edge runtimes | Use an HTTP or WebSocket driver | Requires a supported driver adapter or proxy path |
On a long-running server, an in-process connection pool works well. The process lives for hours, connections get reused, and the pool size gives a predictable connection count. Serverless removes those guarantees. Every concurrent instance opens its own pool, and a traffic spike can exhaust the database's connection limit. The fix is the same with either ORM: give each instance a small pool and put an external pooler in front of the database. In transaction mode, that pooler may break session-level features such as prepared statements, so check how your driver behaves behind it. Edge runtimes often lack raw TCP sockets, so the driver choice decides whether the ORM can run there at all.
How do Prisma migrations and Drizzle migrations compare?
Both tools follow the same loop: declare the schema, generate SQL from the diff, commit the SQL, and apply it in order. They differ in where the schema lives and what extra build steps that location requires.
| Step | Prisma | Drizzle |
|---|---|---|
| Source of truth | schema.prisma |
TypeScript schema files |
| Generate SQL | prisma migrate dev |
drizzle-kit generate |
| Apply in CI/prod | prisma migrate deploy |
drizzle-kit migrate or the runtime migrator |
| Local iteration | prisma db push |
drizzle-kit push |
| History | _prisma_migrations table |
migrations table plus journal files |
prisma migrate dev replays your migration history against a shadow database and compares the result with the live dev database. This catches drift, meaning manual changes that the migration files don't account for, before the next migration is generated. migrate deploy skips that check and applies only pending files, so it is the right command for pipelines.
Both push commands write the schema straight to the database and record nothing in the migration history. That works for a throwaway local database. On a shared staging database it causes drift: the next generated migration may try to recreate objects that already exist, or it may miss changes nobody committed.
The ongoing costs differ. Prisma's client is generated code, so every schema change needs prisma generate. A stale client in CI or in a Docker layer shows up as type or runtime mismatches. Drizzle has no codegen step, but its types are inferred from the schema. On large schemas, that inference can slow tsc and editor feedback noticeably, and type errors can turn into long nested generics that are hard to trace back to the column that caused them.
# --- Prisma: schema.prisma is the source of truth ---
# Dev: diff schema against migration history (replayed on a shadow DB),
# write a new SQL file under prisma/migrations/, apply it, regenerate the client
npx prisma migrate dev --name add_user_email
# CI/prod: apply only pending migration files, no shadow DB, no drift check
npx prisma migrate deploy
# Regenerate the client in every build that runs after a schema change,
# for example in the Dockerfile after copying schema.prisma,
# so the build never ships a stale client
npx prisma generate
# Prototyping only: sync schema directly, records nothing in _prisma_migrations
npx prisma db push
# --- Drizzle: TypeScript schema files are the source of truth ---
# Dev: diff TS schema against the last snapshot, write SQL + journal entry
npx drizzle-kit generate
# CI/prod: apply pending SQL files and record them in the migrations table
npx drizzle-kit migrate
# Prototyping only: sync schema directly, skips migration files and history
npx drizzle-kit push
# No codegen step, but check how much type inference costs on a large schema
npx tsc --noEmit --extendedDiagnostics
# Rule for both tools: never run push against a shared database.
# Commit the generated SQL and let CI apply it with deploy/migrate.
Side-by-side shell commands for the generate, apply and push steps in Prisma and Drizzle, including the extra Prisma codegen step and a way to measure Drizzle's type-checking cost.
When does schema diffing get migrations wrong?
A diff tool compares two schema states. It cannot see intent, so it fails whenever the right migration depends on what you meant rather than what changed.
Renames. Rename fullName to displayName and Prisma sees one column removed and another added. The generated SQL drops the old column and creates an empty one. Prisma warns about data loss, but the warning is easy to skim past. Drizzle Kit asks interactively whether the column was renamed or created. That is safer, but only if the person answering the prompt reads it carefully.
Data changes. Neither tool generates backfills. Splitting a column, or adding a NOT NULL column with no default to a populated table, produces a migration that is correct as DDL and fails against real rows. On large Postgres tables, a backfill run as a single UPDATE can hold locks and bloat the table. Batched updates belong in hand-written SQL.
Concurrent indexes. CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Generators emit plain CREATE INDEX, which blocks writes while it builds. Check whether your migration runner wraps each file in a transaction before you add one.
Expand/contract. Zero-downtime changes take several deploys: add the new column, dual-write, backfill, switch reads, then drop the old column. A diff tool collapses all of that into one step.
Make reviewing generated SQL a required part of code review. In Prisma, run prisma migrate dev --create-only, edit the SQL file, then apply it. In Drizzle, edit the generated file, or create an empty one with drizzle-kit generate --custom and write the SQL yourself.
What happens when you need raw SQL or Postgres-specific features?
The same escape-hatch question comes up at query time. Both tools let you write SQL directly, and in both cases the type checker stops verifying it.
Prisma's $queryRaw takes a tagged template and parameterises interpolated values. The result type is a generic that you supply, and nothing checks it against the database. A misspelled column or wrong cast fails at runtime. TypedSQL closes part of this gap by generating types from .sql files checked against a live database, but those queries sit outside the Prisma Client API. Drizzle's sql template can be dropped into any position in a query builder chain and can reference schema columns, so renames still propagate. Its sql<T> annotation is still an unchecked assertion.
| Feature | Prisma | Drizzle |
|---|---|---|
| CTEs | Raw SQL only | $with / with in the builder |
| Window functions | Raw SQL only | sql fragment inside a typed select |
| Partial indexes | Usually added by editing migration SQL | .where() on index definitions |
| Enums | Native enum in schema |
pgEnum |
| Unmodelled types | Unsupported("..."), which the client can't query |
customType with your own mapping |
Drizzle stays closer to SQL, so Postgres features degrade more gradually: you lose typing on a fragment rather than on the whole query. With Prisma, one window function sends the entire query to raw SQL.
If a large share of your queries are raw SQL, you're paying for an abstraction you mostly bypass. At that point, plain SQL through a Postgres driver or a thinner query builder is often the more honest fit. You still get parameterisation without a second schema language to keep in sync.
Should you choose Drizzle or Prisma, and when should you avoid each?
For most teams, the decision comes down to five questions you can answer before writing any code.
| Factor | Lean towards Prisma | Lean towards Drizzle |
|---|---|---|
| Team SQL fluency | Mixed; many engineers rarely write SQL | Most engineers read and write SQL comfortably |
| Schema source of truth | A dedicated DSL file reviewed separately | TypeScript modules next to application code |
| Deployment target | Long-running servers | Serverless or edge, where client weight matters |
| Custom SQL frequency | Occasional | Routine |
| Switching cost | Greenfield, or already on Prisma | Greenfield, or already on Drizzle |
Choose Prisma when you want productive defaults. The generated client, the opinionated migration workflow and the uniform relation API save a mixed-skill team many small decisions. Avoid it if your engineers keep reaching for raw queries to get the SQL they want, because then you pay for the abstraction without using it.
Choose Drizzle when you want control and have someone who owns query design. Avoid it if nobody does. Its flexibility moves decisions onto the team that Prisma would otherwise make for you. Prisma's cost usually appears later, when you work around its abstraction. Drizzle's cost appears up front, in more design decisions.
Switching an existing service is rarely cheap. You have to do three things:
- Reconcile migration history. The new tool knows nothing about migrations the old tool already applied.
- Baseline the current schema. Create an initial migration that matches production and mark it as applied without running it.
- Retest semantics. Transaction APIs and rollback-on-throw behaviour differ between the two tools. Error handling also changes: code that checks Prisma's
P2002must instead inspect the driver's Postgres SQLSTATE, such as23505for a unique violation.
Unless profiling shows the ORM is your bottleneck, this cost usually outweighs any performance gain.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to drizzle vs prisma, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.