zudo-cloudflare-wisdom

Type to search...

to open search from anywhere

D1 (SQL Database)

CreatedApr 4, 2026Takeshi Takatsudo

Cloudflare D1 SQLite database usage

Overview

D1 is a serverless SQL database built on SQLite. It provides strong consistency and supports complex queries.

Setup

Create a Database

npx wrangler d1 create my-database

Add to wrangler.toml:

[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "abc123-def456-ghi789"

Run Migrations

# Create a migration
npx wrangler d1 migrations create my-database "create-users-table"

# Apply migrations locally
npx wrangler d1 migrations apply my-database --local

# Apply to production
npx wrangler d1 migrations apply my-database --remote

Usage in Functions

interface Env {
  DB: D1Database;
}

// Query
const { results } = await env.DB.prepare(
  "SELECT * FROM users WHERE id = ?"
).bind(userId).all();

// Insert
await env.DB.prepare(
  "INSERT INTO users (name, email) VALUES (?, ?)"
).bind(name, email).run();

// Batch operations
const batch = [
  env.DB.prepare("INSERT INTO logs (msg) VALUES (?)").bind("log1"),
  env.DB.prepare("INSERT INTO logs (msg) VALUES (?)").bind("log2"),
];
await env.DB.batch(batch);

Gotchas

  • SQLite syntax: D1 uses SQLite, not PostgreSQL or MySQL. Some SQL features differ (e.g., no ALTER TABLE ... ADD CONSTRAINT).
  • Size limits: Each database has a 10 GB limit on the free plan.
  • Migrations: Always test migrations locally with --local before applying to production with --remote.