Drizzle ORM: Type-Safe SQL for TypeScript
You rename a column, the migration runs fine, and then a raw SQL string three files away keeps selecting the old name until it blows up in production. Or you go the other way, pick a heavy ORM, and spend an afternoon figuring out what SQL it actually sent. Most TypeScript projects end up stuck somewhere between those two.
Drizzle ORM sits in the middle. You write your schema in TypeScript, the types fall out of it, and queries look a lot like the SQL they produce. Below I'll go through setup, schema definitions, queries, migrations with Drizzle Kit, relations, and how it stacks up against Prisma, TypeORM and Sequelize.
If you already know SQL, there's very little new API to learn. And because types come straight from the schema, a renamed or dropped column shows up as a compile error in your editor instead of a runtime error in your logs.
What is Drizzle ORM?
The short version: you define tables in TypeScript, and Drizzle infers the types for every query you run against them. It doesn't try to hide SQL behind its own vocabulary. A Drizzle query maps almost 1:1 to the SQL it generates, so reading one tells you pretty exactly what hits the database.
What sets it apart from the usual ORMs:
- Thin runtime: Drizzle is a query builder sitting on top of your database driver. No separate engine, no hidden queries
- Full type inference: Column types, nullable fields, and relation shapes are all inferred from your schema definition
- SQL-like API: Methods like
select(),where(),orderBy(), andjoin()mirror SQL syntax - Multi-database support: PostgreSQL, MySQL, SQLite, and Turso (libSQL) all supported
- Drizzle Kit: A companion CLI for generating and running migrations
- Edge runtime compatible: Works in Cloudflare Workers, Vercel Edge, and other edge runtimes
How Drizzle ORM bridges TypeScript code to your database
Installation and Setup
You need the core package plus the driver for your database. That's about it: no big config file, and no code generation step before you can run your first query.
Install Drizzle ORM and your database driver
Choose the driver that matches your database. Drizzle supports postgres.js, node-postgres (pg), mysql2, and better-sqlite3 among others.
# For PostgreSQL (using postgres.js driver)
npm install drizzle-orm postgres
npm install -D drizzle-kit
# For MySQL
npm install drizzle-orm mysql2
npm install -D drizzle-kit
# For SQLite (Node.js)
npm install drizzle-orm better-sqlite3
npm install -D drizzle-kit @types/better-sqlite3
Create your database connection
Initialize the Drizzle client with your database driver. This is typically done once in a db/index.ts file.
// db/index.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);
// db/index.ts
import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise';
const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
});
export const db = drizzle(connection);
// db/index.ts
import { drizzle } from 'drizzle-orm/better-sqlite3';
import Database from 'better-sqlite3';
const sqlite = new Database('local.db');
export const db = drizzle(sqlite);
Configure Drizzle Kit
Create a drizzle.config.ts file at the project root to tell Drizzle Kit where your schema lives and how to connect to your database.
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './db/schema.ts',
out: './drizzle',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});
Defining Your Database Schema
This is the part I like most. You describe tables with Drizzle's column builders, and TypeScript then knows the shape of every row you query. The same file drives both your migrations and your types, so there's one place to change things.
PostgreSQL Schema Example
import {
pgTable,
serial,
varchar,
text,
integer,
boolean,
timestamp,
uuid,
} from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: varchar('name', { length: 255 }).notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
bio: text('bio'),
isActive: boolean('is_active').default(true).notNull(),
createdAt: timestamp('created_at').defaultNow().notNull(),
updatedAt: timestamp('updated_at').defaultNow().notNull(),
});
export const posts = pgTable('posts', {
id: uuid('id').primaryKey().defaultRandom(),
title: varchar('title', { length: 500 }).notNull(),
content: text('content').notNull(),
published: boolean('published').default(false).notNull(),
authorId: integer('author_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
// TypeScript types are automatically inferred:
// type User = typeof users.$inferSelect
// type NewUser = typeof users.$inferInsert
Common Column Types by Database
| Concept | PostgreSQL | MySQL | SQLite |
|---|---|---|---|
| Auto-increment ID | serial('id') |
int('id').autoincrement() |
integer('id') |
| UUID primary key | uuid('id').defaultRandom() |
varchar('id', {length:36}) |
text('id') |
| Variable string | varchar('name', {length:255}) |
varchar('name', {length:255}) |
text('name') |
| JSON data | jsonb('metadata') |
json('metadata') |
text('metadata') |
| Timestamp | timestamp('created_at') |
datetime('created_at') |
integer('created_at') |
| Enum | pgEnum('role', ['admin','user']) |
mysqlEnum('role', ['admin','user']) |
text('role') |
Use typeof users.$inferSelect to get the type for a queried row, and typeof users.$inferInsert for an insertable row (fields with defaults or nullable columns become optional). You don't write these types by hand, so they can't drift away from the schema.
Querying Data with Drizzle
There are two ways to query: a relational API that feels a bit like Prisma, and the SQL-like query builder. The builder is the core of Drizzle and the more flexible of the two. Queries are lazy, so nothing runs until you await them.
Select Queries
import { db } from './db';
import { users, posts } from './db/schema';
import { eq, and, like, gt, desc, count } from 'drizzle-orm';
// Select all users
const allUsers = await db.select().from(users);
// type: { id: number; name: string; email: string; ... }[]
// Select specific columns
const emails = await db
.select({ id: users.id, email: users.email })
.from(users);
// Filter with conditions
const activeUsers = await db
.select()
.from(users)
.where(and(eq(users.isActive, true), gt(users.id, 10)));
// Search with LIKE
const searchResults = await db
.select()
.from(users)
.where(like(users.name, '%John%'));
// Order and limit
const recentUsers = await db
.select()
.from(users)
.orderBy(desc(users.createdAt))
.limit(10)
.offset(0);
// Aggregate: count active users
const [{ total }] = await db
.select({ total: count() })
.from(users)
.where(eq(users.isActive, true));
Joins
// Inner join: posts with their authors
const postsWithAuthors = await db
.select({
postId: posts.id,
title: posts.title,
authorName: users.name,
authorEmail: users.email,
})
.from(posts)
.innerJoin(users, eq(posts.authorId, users.id))
.where(eq(posts.published, true))
.orderBy(desc(posts.createdAt));
// Left join: all users, even without posts
const usersWithPosts = await db
.select({
userName: users.name,
postTitle: posts.title, // null if user has no posts
})
.from(users)
.leftJoin(posts, eq(users.id, posts.authorId));
Insert, Update, and Delete
import { db } from './db';
import { users, posts } from './db/schema';
import { eq } from 'drizzle-orm';
// INSERT: single row, returning inserted data
const [newUser] = await db
.insert(users)
.values({
name: 'Alice Johnson',
email: 'alice@example.com',
})
.returning();
// newUser.id is typed as number
// INSERT: multiple rows at once
await db.insert(posts).values([
{ title: 'First Post', content: 'Hello world', authorId: newUser.id },
{ title: 'Second Post', content: 'More content', authorId: newUser.id },
]);
// UPDATE: modify matching rows
const [updated] = await db
.update(users)
.set({ name: 'Alice Smith', updatedAt: new Date() })
.where(eq(users.id, newUser.id))
.returning();
// DELETE: remove rows
await db.delete(posts).where(eq(posts.authorId, newUser.id));
// Upsert (INSERT ON CONFLICT)
await db
.insert(users)
.values({ name: 'Bob', email: 'bob@example.com' })
.onConflictDoUpdate({
target: users.email,
set: { name: 'Bob Updated' },
});
A Drizzle query is a builder object that only runs when you await it (or call .then()). Forget the await and you get the builder back instead of rows. With an insert or delete that's worse, because nothing gets written and nothing errors. The @typescript-eslint/no-floating-promises lint rule catches a lot of these.
Database Migrations with Drizzle Kit
Drizzle Kit compares your schema file with the previous snapshot and writes the SQL needed to get from one to the other. The migration files land in whatever folder you set as out in the config.
Generate a migration
Run this whenever you change your schema. Drizzle Kit will create a new migration SQL file in the drizzle/ folder with the changes needed.
# Generate migration (diffs schema against the last snapshot, creates SQL file)
npx drizzle-kit generate
# Apply pending migrations to your database
npx drizzle-kit migrate
# Push schema directly without migrations (good for prototyping)
npx drizzle-kit push
# View current DB schema in the browser
npx drizzle-kit studio
Run migrations programmatically
In production you may prefer to run migrations from code (a deploy step or startup script) instead of the CLI. Keep push for local prototyping: it changes the database directly and leaves no migration file behind, so there's nothing to review or replay on other environments.
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
const migrationClient = postgres(process.env.DATABASE_URL!, { max: 1 });
const db = drizzle(migrationClient);
await migrate(db, { migrationsFolder: './drizzle' });
await migrationClient.end();
Example Generated Migration SQL
-- drizzle/0001_create_users_and_posts.sql
CREATE TABLE IF NOT EXISTS "users" (
"id" serial PRIMARY KEY NOT NULL,
"name" varchar(255) NOT NULL,
"email" varchar(255) NOT NULL,
"bio" text,
"is_active" boolean DEFAULT true NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "users_email_unique" UNIQUE("email")
);
CREATE TABLE IF NOT EXISTS "posts" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"title" varchar(500) NOT NULL,
"content" text NOT NULL,
"published" boolean DEFAULT false NOT NULL,
"author_id" integer NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
);
ALTER TABLE "posts" ADD CONSTRAINT "posts_author_id_users_id_fk"
FOREIGN KEY ("author_id") REFERENCES "users"("id")
ON DELETE cascade ON UPDATE no action;
Working with Relations
When you just want "users with their posts", writing the join by hand gets old. The relational query API handles that. You declare relations separately from the tables, then ask for related data through db.query.
Defining Relations
import { relations } from 'drizzle-orm';
import { users, posts } from './tables'; // your table definitions
// A user has many posts
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
// A post belongs to one user (author)
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
}));
Using the Relational Query API
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './db/schema';
// Pass the full schema (including relations) to the client
const db = drizzle(postgres(process.env.DATABASE_URL!), { schema });
// Fetch users with their posts (one query, no N+1)
const usersWithPosts = await db.query.users.findMany({
with: {
posts: {
where: (posts, { eq }) => eq(posts.published, true),
orderBy: (posts, { desc }) => [desc(posts.createdAt)],
limit: 5,
},
},
});
// usersWithPosts[0].posts is fully typed as Post[]
// Fetch a single post with its author
const post = await db.query.posts.findFirst({
where: (posts, { eq }) => eq(posts.id, postId),
with: { author: true },
});
// post.author.name is typed as string
If db.query.users doesn't exist (TypeScript says Property 'users' does not exist, or you get undefined at runtime), you almost certainly created the client without { schema }, or your relations live in a file that isn't part of the imported schema object. The relational API only knows about tables and relations you pass in.
Many-to-Many Relations
import { pgTable, integer, primaryKey, varchar } from 'drizzle-orm/pg-core';
import { relations } from 'drizzle-orm';
export const tags = pgTable('tags', {
id: integer('id').primaryKey().generatedAlwaysAsIdentity(),
name: varchar('name', { length: 100 }).notNull().unique(),
});
// Junction table
export const postTags = pgTable(
'post_tags',
{
postId: integer('post_id').notNull().references(() => posts.id),
tagId: integer('tag_id').notNull().references(() => tags.id),
},
(t) => [primaryKey({ columns: [t.postId, t.tagId] })]
);
export const postsRelations = relations(posts, ({ many }) => ({
postTags: many(postTags),
}));
export const tagsRelations = relations(tags, ({ many }) => ({
postTags: many(postTags),
}));
export const postTagsRelations = relations(postTags, ({ one }) => ({
post: one(posts, { fields: [postTags.postId], references: [posts.id] }),
tag: one(tags, { fields: [postTags.tagId], references: [tags.id] }),
}));
One thing to watch: the junction table's column types must match the keys they point to. In the earlier schema posts.id is a uuid, so in that setup post_id needs to be a uuid column too, or Postgres will reject the foreign key when the migration runs.
Drizzle vs Other ORMs
Every ORM trades something away: type safety, control over SQL, API comfort, or bundle size. Here's a rough comparison with the usual alternatives:
| Feature | Drizzle ORM | Prisma | TypeORM | Sequelize |
|---|---|---|---|---|
| Type Safety | ✅ Full inference | ✅ Generated types | ⚠️ Partial | ❌ Manual types |
| Bundle Size | Small, no engine | Large (query engine, historically a Rust binary) | Medium to large | Medium to large |
| Edge Runtime | ✅ Yes | ⚠️ Via Accelerate or driver adapters | ❌ No | ❌ No |
| Raw SQL Control | ✅ SQL-like API | ⚠️ Limited | ✅ Good | ✅ Good |
| Schema in code | ✅ TypeScript file | Prisma Schema file | ✅ Decorators/classes | ✅ JS/TS models |
| Migrations | Drizzle Kit CLI | Prisma Migrate CLI | Built-in CLI | Built-in CLI |
| Learning Curve | Low (SQL familiarity) | Low (great DX) | Medium | Medium |
I'd reach for Drizzle when the code runs on the edge or in serverless functions, when I want to stay close to SQL, or when bundle size matters. Prisma is still very pleasant to use, especially its schema language and Studio, if none of those constraints apply. TypeORM and Sequelize have been around a long time and work, but their typing and APIs show their age.
Advanced Patterns
Transactions
// Drizzle transactions roll back automatically on throw
const result = await db.transaction(async (tx) => {
// All queries inside use the same transaction
const [user] = await tx
.insert(users)
.values({ name: 'Charlie', email: 'charlie@example.com' })
.returning();
await tx.insert(posts).values({
title: 'Welcome post',
content: 'My first post!',
authorId: user.id,
});
// Throw an error here to roll back both inserts
// throw new Error('Something went wrong');
return user;
});
Raw SQL Escape Hatch
import { sql } from 'drizzle-orm';
// Use the sql template tag for expressions not in the API
const results = await db
.select({
id: users.id,
name: users.name,
// Custom SQL expression, typed via the generic
nameLength: sql<number>`char_length(${users.name})`,
})
.from(users)
.where(sql`char_length(${users.name}) > 5`);
// Fully raw query (use sparingly)
const raw = await db.execute(
sql`SELECT * FROM users WHERE id = ${userId}`
);
When I'd use Drizzle (and when I wouldn't)
I'd pick Drizzle for a TypeScript project where the team is comfortable with SQL and the code runs somewhere size and cold starts matter: a Cloudflare Worker, Vercel functions, or a Next.js app talking to Postgres. Pair it with Zod or tRPC and the types run from the table definition all the way to the API response.
Before going to production
- Use
generate+migrate, notpush: commit the SQL files and read them in review. Drizzle Kit can't always tell a rename from a drop-and-add, so check for accidentalDROP COLUMNlines - Watch your connection pool in serverless: every function instance opens its own connections. Keep
maxlow or put a pooler in front. With a transaction-mode pooler like PgBouncer (or Supabase's pooler on port 6543), postgres.js needsprepare: false, otherwise you'll see errors about prepared statements that don't exist - Keep raw
sqlparameterized: interpolating values with${}inside thesqltag is safe. Building the string yourself and passing it in withsql.raw()is not
Where I wouldn't use it: if the team doesn't really know SQL, Drizzle hands them a SQL-shaped API and assumes they understand joins and indexes, and Prisma's higher-level model will probably serve them better. It's also a younger project than TypeORM or Sequelize, so expect some API changes between versions (the relational query API has been through a rewrite) and pin your drizzle-orm and drizzle-kit versions together. And if a large codebase already runs happily on another ORM, the types alone rarely justify a migration.