Getting Started with Drizzle ORM: A Practical Database Tutorial

Drizzle ORM is a modern, lightweight TypeScript ORM that makes database interactions fast, type-safe, and intuitive. Unlike heavy ORMs, Drizzle provides a thin layer over SQL, giving you full control while benefiting from excellent autocompletion and error checking. This tutorial will walk you through the essential steps to start using Drizzle with your database.

First, install Drizzle and your preferred database driver (e.g., postgres or mysql2) via npm. Initialize your schema by defining tables as objects with the pgTable (or mysqlTable) function. Each column is defined with a type, constraints, and optional relations. Drizzle automatically generates TypeScript types from your schema, so you get end-to-end type safety without extra boilerplate.

Article illustration

1. Defining Schemas and Migrations

Create a schema.ts file and define your tables. For example:

import { pgTable, serial, text, integer } from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  age: integer('age')
});

Then generate and run migrations using drizzle-kit: run npx drizzle-kit push:pg to sync your schema with the database. This keeps your schema as the single source of truth.

2. Running Queries with Type Safety

Drizzle uses a query builder similar to SQL. Import your schema and database instance:

import { db } from './drizzle';
import { users } from './schema';
const allUsers = await db.select().from(users);
const over18 = await db.select()
  .from(users)
  .where(eq(users.age, 18));

Every query’s result is fully typed – no need for manual `as` casts.

3. Inserting, Updating, and Deleting

Insert new records with:

await db.insert(users).values({ name: 'Alice', age: 30 });

Update or delete using where clauses:

await db.update(users).set({ age: 31 }).where(eq(users.name, 'Alice'));
await db.delete(users).where(eq(users.id, 1));

Drizzle also supports complex joins, subqueries, and raw SQL for advanced use cases.

4. Using Relations (Joins)

Define relations by importing relations from Drizzle:

import { relations } from 'drizzle-orm';
export const usersRelations = relations(users, ({ many }) => ({
  posts: many(posts)
}));

Then fetch related data with `with` clause: db.query.users.findMany({ with: { posts: true } }). This gives you nested, typed results effortlessly.

Drizzle ORM strikes a perfect balance between power and simplicity. Start with a simple schema, run your first query, and experience how type-safe SQL can improve your development speed and reliability.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *