DEV Community

Alex Spinov
Alex Spinov

Posted on

Drizzle ORM Has a Free API That Makes SQL Type-Safe Without Code Generation

Drizzle ORM: SQL-like syntax in TypeScript, fully type-safe, no code generation step. Your schema IS your types.

Quick Start

npm install drizzle-orm postgres
npm install -D drizzle-kit
Enter fullscreen mode Exit fullscreen mode

Define Schema

// schema.ts
import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core'

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
  createdAt: timestamp('created_at').defaultNow()
})

export const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  content: text('content'),
  authorId: serial('author_id').references(() => users.id)
})
Enter fullscreen mode Exit fullscreen mode

Queries (SQL-Like, Type-Safe)

import { eq, and, like } from 'drizzle-orm'

// Select
const allUsers = await db.select().from(users)
const user = await db.select().from(users).where(eq(users.id, 1))

// Insert
await db.insert(users).values({ name: 'John', email: 'john@example.com' })

// Update
await db.update(users).set({ name: 'Jane' }).where(eq(users.id, 1))

// Join
const postsWithAuthors = await db
  .select()
  .from(posts)
  .leftJoin(users, eq(posts.authorId, users.id))
  .where(like(posts.title, '%TypeScript%'))
Enter fullscreen mode Exit fullscreen mode

Migrations

npx drizzle-kit generate
npx drizzle-kit migrate
npx drizzle-kit studio  # visual database browser
Enter fullscreen mode Exit fullscreen mode

Drizzle vs Prisma

Feature Drizzle Prisma
Syntax SQL-like Custom DSL
Code gen None Required
Bundle ~30KB ~1MB+
SQL control Full Abstracted
Edge/serverless Yes Limited
Learning curve Know SQL? You're done Learn Prisma Query

The Bottom Line

Drizzle is for developers who think in SQL. Type-safe, lightweight, no code generation, edge-compatible. If Prisma feels too magical, Drizzle is your ORM.


Need to automate data collection or build custom scrapers? Check out my Apify actors for ready-made tools, or email spinov001@gmail.com for custom solutions.

Top comments (0)