Skip to content

Drizzle ORM Cheatsheet

A complete Drizzle ORM cheatsheet from beginner to advanced — schema design, queries, relations, joins, transactions, migrations, prepared statements, aggregations, and production patterns for PostgreSQL, MySQL, and SQLite.

Drizzle is a lightweight, fully type-safe TypeScript ORM. It feels close to SQL while giving you excellent TypeScript inference, migrations, and relational querying. It supports PostgreSQL, MySQL, SQLite, CockroachDB, SingleStore, and more.

This cheatsheet goes from beginner setup to advanced production patterns.

Terminal window
# Core + driver (example: PostgreSQL with postgres.js)
npm i drizzle-orm postgres
npm i -D drizzle-kit dotenv
# Other popular drivers
# npm i drizzle-orm @neondatabase/serverless
# npm i drizzle-orm better-sqlite3
# npm i drizzle-orm mysql2

import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";
import { relations } from "./relations"; // if using relational queries
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client, { schema, relations });

import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql", // "mysql" | "sqlite" | ...
schema: "./src/db/schema.ts",
out: "./drizzle", // migrations folder
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});

import {
pgTable,
serial,
text,
varchar,
integer,
boolean,
timestamp,
pgEnum,
uniqueIndex,
primaryKey,
AnyPgColumn,
} from "drizzle-orm/pg-core";
// Enum
export const roleEnum = pgEnum("role", ["guest", "user", "admin"]);
// Users table
export const users = pgTable(
"users",
{
id: serial("id").primaryKey(),
// or: integer("id").primaryKey().generatedAlwaysAsIdentity(),
name: text("name").notNull(),
email: varchar("email", { length: 256 }).notNull(),
role: roleEnum("role").default("user").notNull(),
invitedBy: integer("invited_by").references((): AnyPgColumn => users.id),
createdAt: timestamp("created_at").defaultNow().notNull(),
},
(table) => [
uniqueIndex("email_idx").on(table.email),
]
);
// Posts table
export const posts = pgTable("posts", {
id: serial("id").primaryKey(),
title: text("title").notNull(),
content: text("content"),
authorId: integer("author_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
published: boolean("published").default(false),
createdAt: timestamp("created_at").defaultNow().notNull(),
});
// Many-to-many junction table
export const usersToGroups = pgTable(
"users_to_groups",
{
userId: integer("user_id")
.notNull()
.references(() => users.id),
groupId: integer("group_id")
.notNull()
.references(() => groups.id),
},
(t) => [primaryKey({ columns: [t.userId, t.groupId] })]
);

Common column helpers: serial, integer, bigint, text, varchar, boolean, timestamp, json / jsonb, uuid, numeric, etc.

import { defineRelations } from "drizzle-orm";
import * as schema from "./schema";
export const relations = defineRelations(schema, (r) => ({
users: {
posts: r.many.posts(),
invitee: r.one.users({
from: r.users.invitedBy,
to: r.users.id,
}),
groups: r.many.groups({
from: r.users.id.through(r.usersToGroups.userId),
to: r.groups.id.through(r.usersToGroups.groupId),
}),
},
posts: {
author: r.one.users({
from: r.posts.authorId,
to: r.users.id,
}),
},
groups: {
users: r.many.users(),
},
}));

Pass relations when creating the db instance to enable db.query.

import { eq, gt, and, or, like, inArray, sql } from "drizzle-orm";
// All rows
const allUsers = await db.select().from(users);
// Specific columns
const result = await db
.select({
id: users.id,
name: users.name,
})
.from(users);
// With filter
const user = await db
.select()
.from(users)
.where(eq(users.id, 1));
// Multiple conditions
await db
.select()
.from(users)
.where(
and(
gt(users.id, 10),
like(users.name, "%Rahim%")
)
);
// Order, limit, offset
await db
.select()
.from(users)
.orderBy(users.createdAt)
.limit(10)
.offset(20);

// Single
await db.insert(users).values({
name: "Rahim",
email: "rahim@example.com",
});
// Multiple
await db.insert(users).values([
{ name: "A", email: "a@example.com" },
{ name: "B", email: "b@example.com" },
]);
// Returning (PostgreSQL / SQLite)
const [newUser] = await db
.insert(users)
.values({ name: "Karim", email: "karim@example.com" })
.returning();
// On conflict
await db
.insert(users)
.values({ email: "rahim@example.com", name: "Rahim" })
.onConflictDoUpdate({
target: users.email,
set: { name: "Rahim Updated" },
});

await db
.update(users)
.set({ name: "New Name" })
.where(eq(users.id, 1));
await db
.update(users)
.set({ name: sql`${users.name} || ' Jr.'` })
.where(eq(users.id, 1))
.returning();

await db.delete(users).where(eq(users.id, 1));
await db
.delete(users)
.where(eq(users.role, "guest"))
.returning();

import {
eq, ne, gt, gte, lt, lte,
and, or, not,
inArray, notInArray,
like, ilike, notLike,
isNull, isNotNull,
between, exists, sql,
} from "drizzle-orm";
// Examples
eq(users.id, 1)
gt(users.id, 10)
and(eq(users.role, "admin"), gt(users.id, 5))
or(eq(users.role, "admin"), eq(users.role, "user"))
inArray(users.id, [1, 2, 3])
like(users.name, "%john%")
ilike(users.email, "%@gmail.com") // case-insensitive (PG)
isNull(users.invitedBy)
between(users.id, 10, 20)

// Inner join
await db
.select({
userId: users.id,
userName: users.name,
postTitle: posts.title,
})
.from(users)
.innerJoin(posts, eq(posts.authorId, users.id));
// Left join
await db
.select()
.from(users)
.leftJoin(posts, eq(posts.authorId, users.id));
// Multiple joins + where + order
await db
.select()
.from(users)
.leftJoin(posts, eq(posts.authorId, users.id))
.where(eq(users.role, "admin"))
.orderBy(users.id);

// Find many with nested relations
const usersWithPosts = await db.query.users.findMany({
with: {
posts: true,
},
});
// Find first
const user = await db.query.users.findFirst({
where: eq(users.id, 1),
with: {
posts: {
where: eq(posts.published, true),
orderBy: [desc(posts.createdAt)],
limit: 5,
},
groups: true,
},
});
// Columns selection
await db.query.users.findMany({
columns: {
id: true,
name: true,
email: false, // exclude
},
with: {
posts: {
columns: { title: true },
},
},
});
// Extras (computed fields)
await db.query.users.findMany({
extras: {
lowerName: (table) => sql<string>`lower(${table.name})`,
},
});

import { count, sum, avg, min, max, sql } from "drizzle-orm";
// Count
const [{ value }] = await db
.select({ value: count() })
.from(users);
// Group by
const stats = await db
.select({
authorId: posts.authorId,
postCount: count(),
avgLength: avg(sql`length(${posts.content})`),
})
.from(posts)
.groupBy(posts.authorId)
.having(gt(count(), 5));
// $count helper (useful in relational queries)
await db.query.users.findMany({
extras: {
totalPosts: (table) =>
db.$count(posts, eq(posts.authorId, table.id)),
},
});

// Subquery
const sq = db
.select()
.from(users)
.where(eq(users.role, "admin"))
.as("admin_users");
const result = await db.select().from(sq);
// WITH (CTE)
const cte = db.$with("admins").as(
db.select().from(users).where(eq(users.role, "admin"))
);
const result = await db
.with(cte)
.select()
.from(cte);

await db.transaction(async (tx) => {
const [user] = await tx
.insert(users)
.values({ name: "New User", email: "new@example.com" })
.returning();
await tx.insert(posts).values({
title: "First post",
authorId: user.id,
});
// If any query throws, the whole transaction rolls back
});

import { sql } from "drizzle-orm";
// Prepare once
const getUserById = db
.select()
.from(users)
.where(eq(users.id, sql.placeholder("id")))
.prepare("get_user_by_id");
// Execute many times
const user1 = await getUserById.execute({ id: 1 });
const user2 = await getUserById.execute({ id: 2 });
// With relational queries
const prepared = db.query.users
.findMany({
where: eq(users.id, sql.placeholder("id")),
with: { posts: true },
})
.prepare();
await prepared.execute({ id: 10 });

Terminal window
# Generate migration files from schema changes
npx drizzle-kit generate
# Apply migrations
npx drizzle-kit migrate
# Push schema directly (prototyping / development)
npx drizzle-kit push
# Pull schema from existing database
npx drizzle-kit pull
# Open Drizzle Studio (visual browser)
npx drizzle-kit studio

Typical workflow (codebase-first):

  1. Change schema.ts
  2. drizzle-kit generate
  3. Review the generated SQL
  4. drizzle-kit migrate

import { sql } from "drizzle-orm";
// Template
await db.execute(sql`SELECT * FROM users WHERE id = ${userId}`);
// Inside query builder
await db
.select({
id: users.id,
nameLength: sql<number>`length(${users.name})`,
})
.from(users);

export const users = pgTable("users", {
// ...
deletedAt: timestamp("deleted_at"),
});
// Always filter
await db
.select()
.from(users)
.where(and(eq(users.id, id), isNull(users.deletedAt)));

async function paginate<T>(
query: any,
page: number,
pageSize = 20
) {
const offset = (page - 1) * pageSize;
const data = await query.limit(pageSize).offset(offset);
return data;
}

function buildUserFilters(filters: {
role?: string;
search?: string;
}) {
const conditions = [];
if (filters.role) conditions.push(eq(users.role, filters.role));
if (filters.search)
conditions.push(ilike(users.name, `%${filters.search}%`));
return conditions.length ? and(...conditions) : undefined;
}

  1. Schema is the source of truth — keep it clean and well-typed.
  2. Prefer relational queries (db.query) for nested data; use the query builder for complex joins, aggregations, and reports.
  3. Use prepared statements for any query that runs frequently.
  4. Select only the columns you need.
  5. Push aggregations and filtering to the database.
  6. Index columns used in WHERE, JOIN, and ORDER BY.
  7. Use transactions for multi-step writes.
  8. Generate migrations (generate + migrate) instead of push in production.
  9. Keep relations defined in one place with defineRelations.
  10. Handle errors and always validate user input before building queries.

// Select
db.select().from(users).where(eq(users.id, 1))
// Insert + returning
db.insert(users).values({...}).returning()
// Update
db.update(users).set({...}).where(eq(users.id, 1))
// Delete
db.delete(users).where(eq(users.id, 1))
// Relational
db.query.users.findMany({ with: { posts: true } })
// Transaction
db.transaction(async (tx) => { ... })
// Count
db.select({ value: count() }).from(users)
// Prepared
db.select().from(users).where(eq(users.id, sql.placeholder("id"))).prepare("name")


This cheatsheet targets modern Drizzle (Relational Queries v2 / recent releases). Always check the official docs for the exact version you are using.

Frequently asked questions

What is Drizzle ORM?

Drizzle is a TypeScript ORM that provides a thin, type-safe layer over SQL. You define your schema in TypeScript and get fully typed queries, migrations, and relational querying without a heavy runtime.

How do I define relations in Drizzle?

Use defineRelations (Relational Queries v2) to declare one-to-one, one-to-many, and many-to-many relationships in one place, then pass them when creating the db instance.

What is the difference between db.select and db.query?

db.select is the SQL-like query builder (joins, groupBy, etc.). db.query is the relational query API that lets you fetch nested data with with: { ... } in a more object-oriented style.

How do migrations work with Drizzle?

Define schema in TypeScript, then use drizzle-kit generate to create SQL migration files and drizzle-kit migrate to apply them. You can also use push for rapid prototyping.

How can I improve query performance?

Use prepared statements for repeated queries, select only needed columns, add proper indexes, push aggregations to the database, and prefer relational queries or well-written joins over N+1 patterns.

You're offline Check your connection.