What are Prisma, Drizzle and Kysely, and where does each sit between ORM and typed SQL?
Prisma, Drizzle and Kysely all give you typed database access from TypeScript. They differ in who owns the schema and how much abstraction sits between your code and the SQL that runs.
Prisma is a schema-first ORM. You describe models in its own schema language, and a generator produces a client with methods like findMany and create. Your code calls the client, and the query engine turns those calls into SQL. Teams pick Prisma for fast CRUD and readable nested reads and writes, and they accept that SQL is mostly hidden.
Drizzle is a TypeScript-first ORM. You define schemas as TypeScript objects. The core API mirrors SQL closely (select().from().where(), explicit joins), and an optional relational query layer adds nested with loading. Teams pick it when they want SQL-level control without a separate schema language or code generation step.
Kysely is a typed SQL query builder. It does not own the schema and has no model layer. It types queries against a Database interface that you write by hand or generate from a live database with community tools. Teams pick it when they want a thin typed wrapper over SQL they already know.
| Prisma | Drizzle | Kysely | |
|---|---|---|---|
| Schema ownership | Prisma schema file | TypeScript schema | Database (external) |
| Type source | Generated client | Inferred from TS schema | Database interface |
| Migration tooling | Prisma Migrate | Drizzle Kit | Built-in Migrator, hand-written |
| Relation loading | include / nested select |
Joins or relational with |
Joins, JSON helpers |
Request path for each tool
Prisma: app code → generated client → query engine → driver → pooler → Postgres
Drizzle: app code → query API / relational layer → driver → pooler → Postgres
Kysely: app code → query builder → driver (dialect) → pooler → Postgres
Prisma has the most translation between your call and the SQL that reaches the driver. Kysely has the least.
PRISMA DRIZZLE KYSELY
+----------------------+ +----------------------+ +----------------------+
| app code | | app code | | app code |
+----------------------+ +----------------------+ +----------------------+
v v v
+----------------------+ +----------------------+ +----------------------+
| generated client | | query API | | query builder |
| (schema.prisma) | | + relational layer | | typed by Database |
+----------------------+ +----------------------+ +----------------------+
| | SQL+params | SQL+params
v | |
+----------------------+ | |
| query engine | | |
| builds SQL | | |
+----------------------+ | |
| SQL+params | |
v v v
+----------------------+ +----------------------+ +----------------------+
| Postgres driver | | Postgres driver | | Postgres driver |
+----------------------+ +----------------------+ +----------------------+
v v v
+----------------------+ +----------------------+ +----------------------+
| pooler | | pooler | | pooler |
+----------------------+ +----------------------+ +----------------------+
v v v
+--------------------------------------------------------------------------+
| PostgreSQL |
+--------------------------------------------------------------------------+
Request path for each tool: Prisma routes calls from its generated client through a query engine that builds the SQL, while Drizzle and Kysely build the SQL and parameters in their own layer and hand them directly to the driver, pooler and Postgres.
How does each tool produce type safety, and how do you keep code and database in sync?
Prisma's types come from schema.prisma, not from TypeScript. A model such as model User { id Int @id @default(autoincrement()) email String @unique } is compiled by prisma generate into a client with matching types. That gives you strong, relation-aware result types. It also adds a build step and a second source of truth that must agree with both your migrations and the live database. If you forget to regenerate, the types are stale even when the schema file is correct.
Drizzle has no generate step for types. You declare const users = pgTable('users', { id: serial('id').primaryKey(), email: text('email').notNull() }), and typeof users.$inferSelect gives you the row type. The table definition is ordinary TypeScript, so the compiler checks it directly. The remaining gap is between that file and the actual database.
Kysely knows only what you tell it through an interface: interface DB { users: { id: Generated<number>; email: string } }, passed as new Kysely<DB>(...). You can write this by hand, or generate it from the live database with community codegen tools. Hand-written interfaces drift silently.
In all three tools, drift is a CI problem, and you catch it the same way:
- Apply migrations to a scratch Postgres.
- Regenerate types or schema snapshots.
- Fail the build if
git diff --exit-codereports changes.
Type safety ends where Postgres hands back data the tool can't describe. JSONB columns come back as broad types. Raw SQL results are typed only as precisely as you annotate them. Views and functions often need manual typing. Validate these values at runtime, or type them explicitly and narrowly.
// Prisma lives in schema.prisma, not TS. Types exist only after `prisma generate`:
// model User {
// id Int @id @default(autoincrement())
// email String @unique
// prefs Json?
// }
import { pgTable, serial, text, jsonb } from 'drizzle-orm/pg-core';
import { Kysely, PostgresDialect, type Generated } from 'kysely';
import { Pool } from 'pg';
type Prefs = { theme: 'light' | 'dark'; digest: boolean };
// Drizzle: the table definition is the type source, with no generate step.
// $type<Prefs>() is a compile-time claim only. Postgres does not enforce it.
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: text('email').notNull(),
prefs: jsonb('prefs').$type<Prefs>(),
});
export type UserRow = typeof users.$inferSelect;
// Kysely: an interface you write by hand or generate from the live database.
// prefs is typed as unknown so callers must validate it.
interface DB {
users: { id: Generated<number>; email: string; prefs: unknown };
}
export const db = new Kysely<DB>({
dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }) }),
});
// The database boundary: JSONB holds whatever was written. Check it before trusting it.
export function parsePrefs(value: unknown): Prefs {
const v = value as Partial<Prefs> | null;
if (v && (v.theme === 'light' || v.theme === 'dark') && typeof v.digest === 'boolean') {
return { theme: v.theme, digest: v.digest };
}
throw new Error('users.prefs does not match Prefs');
}
The same users table in all three tools: a Prisma model that needs prisma generate, a Drizzle table whose row type is inferred directly, and a Kysely interface, plus a runtime check for the JSONB column that no tool's static types can guarantee.
How do migrations work in Prisma, Drizzle Kit and Kysely?
Migrations are where the source-of-truth choice becomes operational. Prisma Migrate compares your Prisma schema with the migration history and writes a timestamped folder containing a plain migration.sql. Drizzle Kit's generate does the same from your TypeScript schema. Its push applies the diff directly to a database without writing a file. That suits a throwaway local database but leaves no record for staging or production. Kysely generates nothing. Its Migrator runs files that each export an up and a down function. A typical up creates an orders table with a few columns and an index, using db.schema. The matching down drops the table. You write both functions yourself.
A generated SQL file is usually short. It contains ALTER TABLE, CREATE TABLE and CREATE INDEX statements, sometimes with a comment warning about data loss. Read every one. A diff can treat a column rename as a drop plus an add. It will not backfill data. It will not use CREATE INDEX CONCURRENTLY on a large table unless you edit the SQL.
| Prisma Migrate | Drizzle Kit | Kysely Migrator | |
|---|---|---|---|
| Source | Schema diff | Schema diff, or push | Hand-written |
| Hand-edited SQL | Edit before applying | Edit generated file | Native |
| Data migrations | Add SQL manually | Add SQL manually | Ordinary code |
| Rollback | Write a forward fix | Write a forward fix | down you maintain |
| PR review | Readable SQL | Readable SQL (generate only) | TypeScript that builds the SQL |
Generated diffs save real time on routine column and index changes. They do not remove the need to review each migration. Kysely costs more typing on every change, but it never produces a statement you did not write.
// migrations/2024_06_01_create_orders.ts
import { Kysely, sql } from 'kysely'
// Migrations should not depend on the app's current DB types,
// because those types change as later migrations run.
export async function up(db: Kysely<any>): Promise<void> {
await db.schema
.createTable('orders')
.addColumn('id', 'serial', (col) => col.primaryKey())
.addColumn('customer_id', 'integer', (col) => col.notNull())
.addColumn('total_cents', 'integer', (col) => col.notNull())
.addColumn('created_at', 'timestamptz', (col) =>
col.notNull().defaultTo(sql`now()`)
)
.execute()
// Index for the common lookup of a customer's orders.
await db.schema
.createIndex('orders_customer_id_idx')
.on('orders')
.column('customer_id')
.execute()
}
// You write and maintain the rollback yourself.
// Dropping the table also drops its index.
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable('orders').execute()
}
A hand-written Kysely migration file that the Migrator runs: up creates an orders table and index with db.schema, and down drops the table.
How do you write real Postgres queries in each tool, and when do you need raw SQL?
…migration you did not write yourself.
One query, three tools
The worked example is a keyset-paginated list of orders. Each order is joined to its customer, carries a count of line items, and is filtered on a JSONB key such as metadata->>'channel'. In Prisma, the join and the count fit naturally into findMany with relation includes and _count, and JSON path filters cover simple equality. Once you need a computed sort, a HAVING clause or a JSONB containment operator, you drop to $queryRaw. At that point the result type is whatever you assert, so you must add typing back yourself, for example by validating rows with a schema. Drizzle expresses the join and the grouping directly, and the sql template tag covers the JSONB operator inline. Types still flow through the surrounding query. Kysely builds the whole query in its builder and uses its sql helper only for the JSONB expression, so the output stays typed.
The pattern: Prisma speeds up CRUD, but reporting queries tend to push you to raw SQL, where typing is lost.
| Feature | Prisma | Drizzle | Kysely |
|---|---|---|---|
| CTEs | raw SQL | native | native |
| Window functions | raw SQL | via helper | via helper |
| ON CONFLICT upsert | native (own semantics) | native | native |
| RETURNING | implicit | native | native |
| FOR UPDATE / SKIP LOCKED | raw SQL | native | native |
| Enums | native | native | via generated types |
| Arrays | native | native | via helper |
| JSONB operators | partial | via helper | via helper |
These ratings change between releases. Verify each one against the version you run.
import { PrismaClient } from '@prisma/client';
import { z } from 'zod';
const prisma = new PrismaClient();
// $queryRaw results are not checked against your schema, so validate each row at runtime.
const OrderRow = z.object({
id: z.string(),
createdAt: z.date(),
customerName: z.string(),
lineItemCount: z.number().int(),
});
export async function listWebOrders(cursor: { createdAt: Date; id: string }, limit = 20) {
// Interpolated values in the tagged template are sent as bind parameters, not spliced into the SQL.
const filter = JSON.stringify({ channel: 'web' });
const rows = await prisma.$queryRaw`
SELECT o.id, o.created_at AS "createdAt", c.name AS "customerName",
count(li.id)::int AS "lineItemCount" -- cast so count() is not returned as bigint
FROM orders o
JOIN customers c ON c.id = o.customer_id
LEFT JOIN line_items li ON li.order_id = o.id
WHERE o.metadata @> ${filter}::jsonb -- JSONB containment, outside findMany's JSON filters
AND (o.created_at, o.id) < (${cursor.createdAt}, ${cursor.id}::uuid) -- keyset cursor
GROUP BY o.id, c.name
HAVING count(li.id) > 0
ORDER BY o.created_at DESC, o.id DESC
LIMIT ${limit}
`;
// Restore typing: the parse fails loudly if the SQL and the expected shape drift apart.
return z.array(OrderRow).parse(rows);
}
Prisma's $queryRaw expressing the JSONB containment filter, HAVING clause and keyset cursor that findMany cannot express, with a zod schema restoring the row typing that raw SQL loses.
Is Prisma slower than Drizzle or Kysely? How to reason about Postgres performance
It can be, but whether that overhead matters depends on your workload. Prisma has historically sent queries through a separate query engine written in Rust, which adds a serialization hop between your JavaScript code and the database driver. That architecture has changed over time, so check any performance claim against the Prisma version you actually run. Drizzle and Kysely compile queries in TypeScript and pass them straight to the driver, which leaves less in between.
Three other factors deserve attention:
- SQL shape. Nested relation reads can become several queries or one large join. Read what each tool generates instead of assuming.
- N+1 queries. Lazy loading inside loops costs one round trip per row, in any of the three tools.
- Serialization. Hydrating wide rows into deep object graphs costs CPU, especially for large result sets.
In most APIs, a missing index, an unbounded SELECT, or ten sequential round trips costs far more than ORM overhead. Published micro-benchmarks usually time trivial queries on localhost, so network latency and query plans barely show up in the results.
Measure your own workload
- Turn on query logging:
log: ['query']in Prisma,logger: truein Drizzle, or thelogoption in Kysely. - Paste the slow queries into
EXPLAIN (ANALYZE, BUFFERS) SELECT .... This runs the query, so wrap writes in a transaction you roll back. - Enable
pg_stat_statementsand rank queries by cumulative cost:SELECT query, calls, mean_exec_time, total_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;. Column names differ in older Postgres releases. - Load-test realistic endpoints against a production-sized dataset before you switch tools.
How does each tool handle connection pooling, serverless, drivers and transactions?
Pooling and PgBouncer
PgBouncer in transaction mode hands a server connection to a client only for the length of one transaction. Anything tied to the session breaks: named prepared statements, SET without LOCAL, advisory locks, LISTEN, and temp tables. All three tools can hit this. Prisma's pgbouncer=true connection-string flag changes how it handles prepared statements. With postgres.js, which Drizzle often uses, set prepare: false. node-postgres, the default driver for Kysely's PostgresDialect, uses unnamed statements unless you pass a name, so it usually works without changes. Session-level features still fail with any of these drivers.
Serverless and drivers
Drizzle and Kysely are thin TypeScript layers over whichever driver you install, so cold-start cost and bundle size mostly come from that driver. Prisma has historically shipped a separate query engine, which makes the deployment artifact larger and adds startup work. Its driver adapters let it run on JavaScript drivers instead. Measure cold starts on your own target runtime rather than relying on reputation.
Transactions and retries
All three provide callback-style interactive transactions:
- Prisma:
$transaction(fn, { isolationLevel }) - Drizzle:
db.transaction(fn, { isolationLevel: 'serializable' }) - Kysely:
db.transaction().setIsolationLevel('serializable').execute(fn)
Under SERIALIZABLE, Postgres aborts conflicting transactions with SQLSTATE 40001, and Prisma surfaces this class of error as P2034. The correct response is to rerun the entire callback with backoff, not the single failed statement, because the transaction's earlier reads are no longer valid. For the same reason, keep side effects such as HTTP calls or queue publishes out of the callback, since a retry would repeat them.
Which should you choose, when should you avoid each, and can you combine them?
Choose by team skill and workload shape. Feature lists matter less.
Prisma suits teams that want strong conventions and fast onboarding. One schema file, generated types and a consistent query API let new engineers ship safely in days. Avoid it when much of the workload is Postgres-specific (CTEs, window functions, jsonb operators) or reporting-heavy, because you end up in raw SQL and lose the typing that justified the tool.
Drizzle suits teams that want schemas defined in TypeScript with near-SQL control. Avoid it if the team lacks SQL fluency, since its abstractions assume you know what SQL they emit, or if you cannot absorb API churn. Its SQL-like builder and its relational query API also behave differently, in syntax and in the SQL they generate, so set a team rule for which layer to use and when.
Kysely suits SQL-fluent teams, existing databases and anyone who wants a thin typed wrapper. Avoid it if you want migrations, schema typing and relation loading handled for you, because you assemble those yourself.
Raw SQL with a typed driver is also a valid choice for small, query-heavy services.
A full switch between tools is expensive. You have to reconcile migration history and rewrite every query. A hybrid costs far less. Keep the existing ORM for CRUD, and add Kysely or typed raw SQL for the hot paths and reports. Both can share the same connection pool.
| Team traits and workload | Recommendation |
|---|---|
| Mixed SQL skill, CRUD-heavy, fast onboarding | Prisma |
| SQL-comfortable, TypeScript-first schema | Drizzle |
| SQL-fluent, existing database | Kysely |
| Few complex queries, minimal dependencies | Typed driver and raw SQL |
| Existing ORM struggling with reports | Hybrid: add Kysely or typed SQL |
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 prisma vs drizzle vs kysely, 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 shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.