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.
# Core + driver (example: PostgreSQL with postgres.js)npm i drizzle-orm postgresnpm i -D drizzle-kit dotenv
# Other popular drivers# npm i drizzle-orm @neondatabase/serverless# npm i drizzle-orm better-sqlite3# npm i drizzle-orm mysql2import { 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";
// Enumexport const roleEnum = pgEnum("role", ["guest", "user", "admin"]);
// Users tableexport 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 tableexport 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 tableexport 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 rowsconst allUsers = await db.select().from(users);
// Specific columnsconst result = await db .select({ id: users.id, name: users.name, }) .from(users);
// With filterconst user = await db .select() .from(users) .where(eq(users.id, 1));
// Multiple conditionsawait db .select() .from(users) .where( and( gt(users.id, 10), like(users.name, "%Rahim%") ) );
// Order, limit, offsetawait db .select() .from(users) .orderBy(users.createdAt) .limit(10) .offset(20);// Singleawait db.insert(users).values({ name: "Rahim", email: "rahim@example.com",});
// Multipleawait 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 conflictawait 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";
// Exampleseq(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 joinawait db .select({ userId: users.id, userName: users.name, postTitle: posts.title, }) .from(users) .innerJoin(posts, eq(posts.authorId, users.id));
// Left joinawait db .select() .from(users) .leftJoin(posts, eq(posts.authorId, users.id));
// Multiple joins + where + orderawait db .select() .from(users) .leftJoin(posts, eq(posts.authorId, users.id)) .where(eq(users.role, "admin")) .orderBy(users.id);// Find many with nested relationsconst usersWithPosts = await db.query.users.findMany({ with: { posts: true, },});
// Find firstconst 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 selectionawait 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";
// Countconst [{ value }] = await db .select({ value: count() }) .from(users);
// Group byconst 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)), },});// Subqueryconst 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 onceconst getUserById = db .select() .from(users) .where(eq(users.id, sql.placeholder("id"))) .prepare("get_user_by_id");
// Execute many timesconst user1 = await getUserById.execute({ id: 1 });const user2 = await getUserById.execute({ id: 2 });
// With relational queriesconst prepared = db.query.users .findMany({ where: eq(users.id, sql.placeholder("id")), with: { posts: true }, }) .prepare();
await prepared.execute({ id: 10 });# Generate migration files from schema changesnpx drizzle-kit generate
# Apply migrationsnpx drizzle-kit migrate
# Push schema directly (prototyping / development)npx drizzle-kit push
# Pull schema from existing databasenpx drizzle-kit pull
# Open Drizzle Studio (visual browser)npx drizzle-kit studioTypical workflow (codebase-first):
- Change
schema.ts drizzle-kit generate- Review the generated SQL
drizzle-kit migrate
import { sql } from "drizzle-orm";
// Templateawait db.execute(sql`SELECT * FROM users WHERE id = ${userId}`);
// Inside query builderawait db .select({ id: users.id, nameLength: sql<number>`length(${users.name})`, }) .from(users);export const users = pgTable("users", { // ... deletedAt: timestamp("deleted_at"),});
// Always filterawait 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;}- Schema is the source of truth — keep it clean and well-typed.
- Prefer relational queries (
db.query) for nested data; use the query builder for complex joins, aggregations, and reports. - Use prepared statements for any query that runs frequently.
- Select only the columns you need.
- Push aggregations and filtering to the database.
- Index columns used in
WHERE,JOIN, andORDER BY. - Use transactions for multi-step writes.
- Generate migrations (
generate+migrate) instead ofpushin production. - Keep relations defined in one place with
defineRelations. - Handle errors and always validate user input before building queries.
// Selectdb.select().from(users).where(eq(users.id, 1))
// Insert + returningdb.insert(users).values({...}).returning()
// Updatedb.update(users).set({...}).where(eq(users.id, 1))
// Deletedb.delete(users).where(eq(users.id, 1))
// Relationaldb.query.users.findMany({ with: { posts: true } })
// Transactiondb.transaction(async (tx) => { ... })
// Countdb.select({ value: count() }).from(users)
// Prepareddb.select().from(users).where(eq(users.id, sql.placeholder("id"))).prepare("name")- Official docs: https://orm.drizzle.team/docs/overview
- Relational Queries: https://orm.drizzle.team/docs/rqb
- Drizzle Kit: https://orm.drizzle.team/kit-docs/overview
- GitHub: https://github.com/drizzle-team/drizzle-orm
- Studio:
npx drizzle-kit studio
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.