Step-by-step guide to get started with Drizzle ORM.
npm install drizzle-orm
npm install pg # For PostgreSQL
npm install -D @types/pg # TypeScript typesSelect the appropriate driver for your database:
drizzle-orm/node-postgres or drizzle-orm/postgres-jsdrizzle-orm/mysql2drizzle-orm/better-sqlite3import { pgTable, serial, text, varchar, timestamp } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: serial('id').primaryKey(),
name: text('name').notNull(),
email: varchar('email', { length: 255 }).notNull().unique(),
createdAt: timestamp('created_at').defaultNow().notNull(),
});
export const posts = pgTable('posts', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
content: text('content'),
authorId: integer('author_id').notNull().references(() => users.id),
createdAt: timestamp('created_at').defaultNow().notNull(),
});import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
const db = drizzle(pool, { schema });// Single insert
const [newUser] = await db.insert(users)
.values({ name: 'John', email: 'john@example.com' })
.returning();
// Multiple inserts
await db.insert(users).values([
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' },
]);import { eq, and, or } from 'drizzle-orm';
// Select all
const allUsers = await db.select().from(users);
// Select with conditions
const user = await db.select()
.from(users)
.where(eq(users.id, 1));
// Select specific fields
const userNames = await db.select({
id: users.id,
name: users.name,
}).from(users);
// Complex conditions
const activeUsers = await db.select()
.from(users)
.where(and(
eq(users.active, true),
or(
eq(users.role, 'admin'),
eq(users.role, 'moderator')
)
));// Update single record
await db.update(users)
.set({ name: 'John Updated' })
.where(eq(users.id, 1));
// Update with returning
const [updated] = await db.update(users)
.set({ name: 'John Updated' })
.where(eq(users.id, 1))
.returning();// Delete single record
await db.delete(users)
.where(eq(users.id, 1));
// Delete with returning
const [deleted] = await db.delete(users)
.where(eq(users.id, 1))
.returning();import { relations } from 'drizzle-orm';
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id],
}),
}));// Load user with posts
const userWithPosts = await db.query.users.findFirst({
where: eq(users.id, 1),
with: {
posts: true,
},
});
// Load post with author
const postWithAuthor = await db.query.posts.findFirst({
where: eq(posts.id, 1),
with: {
author: true,
},
});// Inner join
const usersWithPosts = await db.select()
.from(users)
.innerJoin(posts, eq(users.id, posts.authorId));
// Left join
const allUsersWithPosts = await db.select()
.from(users)
.leftJoin(posts, eq(users.id, posts.authorId));await db.transaction(async (tx) => {
const [user] = await tx.insert(users)
.values({ name: 'John', email: 'john@example.com' })
.returning();
await tx.insert(posts)
.values({ title: 'Hello', authorId: user.id });
});