or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

examples

edge-cases.mdreal-world-scenarios.md
index.md
tile.json

quick-start.mddocs/guides/

Quick Start Guide

Step-by-step guide to get started with Drizzle ORM.

Installation

npm install drizzle-orm
npm install pg                    # For PostgreSQL
npm install -D @types/pg          # TypeScript types

Step 1: Choose Your Driver

Select the appropriate driver for your database:

  • PostgreSQL: drizzle-orm/node-postgres or drizzle-orm/postgres-js
  • MySQL: drizzle-orm/mysql2
  • SQLite: drizzle-orm/better-sqlite3

Step 2: Define Your Schema

import { 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(),
});

Step 3: Initialize Database Connection

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 });

Step 4: Basic CRUD Operations

Create (Insert)

// 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' },
]);

Read (Select)

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

// 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

// 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();

Step 5: Define Relations (Optional)

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],
  }),
}));

Step 6: Use Relational Queries

// 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,
  },
});

Step 7: Use Joins (Alternative to Relations)

// 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));

Step 8: Transactions

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 });
});

Next Steps

  • Explore Schema Definition Reference for advanced schema features
  • Learn about Query Building for complex queries
  • Check Real-World Examples for practical patterns
  • Review Database Drivers for your specific database setup