---
title: "Cloudflare D1 - Serverless SQL Database"
description: "The easiest way to add SQL to your application. Serverless SQLite database with global read replication, native Worker integration, and time travel backups."
url: "https://www.cloudflare.com/products/d1"
---

# D1

> D1 is built into the Cloudflare Workers Platform with out-of-the-box integration with Workers. Applications need to save data. SQLite offers a familiar, relational database with SQL querying.

## Key Features

- Serverless SQLite database
- Global read replication
- Native Workers integration
- Time travel backups (30 days)
- Prisma and Drizzle ORM support
- Generated columns
- Per-database or per-user scaling

## Benefits

### Familiar SQL at the Edge

Build applications with the power and familiarity of a relational, SQL-based database that lives on the edge, close to your users. Leverage your existing SQL knowledge to query structured data with low latency, without having to learn a new query language.

### Native Worker Integration

Query your database with near-zero latency directly from your serverless functions, as D1 is built to be the stateful backend for the Cloudflare Workers ecosystem.

### Scale for Vibe-Coding Platforms

Create millions of D1 databases, per account or per user, and scale out your vibe-coding platform to support everyone. Pay only when databases are used.

## Use Cases

### Vibe-coding platforms

Instantly provision an isolated database for each user's project on your platform, providing fast, sandboxed data storage for online IDEs, CMS platforms, or multi-tenant SaaS applications. Provide your users with a full-featured SQL database without managing complex infrastructure.

### Familiar SQL at the Edge

Build applications with the power and familiarity of a relational, SQL-based database that lives on the edge, close to your users. Leverage your existing SQL knowledge to query structured data with low latency, without having to learn a new query language.

### User Profile & Configuration Storage

Store user-specific application settings, profiles, and personalization data directly at the edge to deliver fast, customized experiences. Reduce read latency for frequently accessed data and improve your application's responsiveness globally.

## Code Examples

### Basic D1 Operations

Create tables, insert data, and query your D1 database from Workers.

```typescript
export default {
  async fetch(request, env) {
    // Create a table
    await env.DB.exec(`CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      email TEXT UNIQUE NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);

    // Insert data
    const { results } = await env.DB.prepare(
      `INSERT INTO users (name, email) VALUES (?, ?)`
    ).bind('John Doe', 'john@example.com').run();

    // Query data
    const { results: users } = await env.DB.prepare(
      `SELECT * FROM users WHERE email = ?`
    ).bind('john@example.com').all();

    return new Response(JSON.stringify(users), {
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
```

### Using D1 with Prisma ORM

Develop faster and with full type-safety using Prisma ORM with D1.

```typescript
// schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  createdAt DateTime @default(now())
  posts     Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
}

// worker.ts
import { PrismaClient } from '@prisma/client';

export default {
  async fetch(request, env) {
    const prisma = new PrismaClient({
      datasources: {
        db: {
          url: env.DATABASE_URL
        }
      }
    });

    // Create a user with posts
    const user = await prisma.user.create({
      data: {
        name: 'Jane Doe',
        email: 'jane@example.com',
        posts: {
          create: [
            { title: 'Hello World', content: 'My first post!' },
            { title: 'D1 is Great', content: 'I love using D1 with Prisma!' }
          ]
        }
      },
      include: {
        posts: true
      }
    });

    return new Response(JSON.stringify(user), {
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
```

### Global Read Replication

Query from read replicas using the [Sessions API](https://developers.cloudflare.com/d1/best-practices/read-replication/#use-sessions-api) for better performance across the globe.

```typescript
export default {
  async fetch(request, env) {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    
    if (!userId) {
      return new Response('Missing userId parameter', { status: 400 });
    }

    // Use read replica for better performance
    const dbSession = env.DB.withSession()
    const { results } = await dbSession.prepare(
      `SELECT u.*, COUNT(p.id) as post_count 
         FROM users u 
         LEFT JOIN posts p ON u.id = p.authorId 
         WHERE u.id = ?
         GROUP BY u.id`
    ).bind(userId).all();

    return new Response(JSON.stringify(results), {
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
```

### Time Travel Backups

Restore your database to any point in time within the last 30 days.

```bash
wrangler d1 time-travel restore YOUR_DATABASE --timestamp=UNIX_TIMESTAMP
        
🚧 Restoring database YOUR_DATABASE from bookmark 00000080-ffffffff-00004c60-390376cb1c4dd679b74a19d19f5ca5be

⚠️ This will overwrite all data in database YOUR_DATABASE.
In-flight queries and transactions will be cancelled.

✔ OK to proceed (y/N) … yes
⚡️ Time travel in progress...
✅ Database YOUR_DATABASE restored back to bookmark 00000080-ffffffff-00004c60-390376cb1c4dd679b74a19d19f5ca5be

↩️ To undo this operation, you can restore to the previous bookmark: 00000085-ffffffff-00004c6d-2510c8b03a2eb2c48b2422bb3b33fad5
        
```

## Resources

- [Full Documentation](https://developers.cloudflare.com/d1): Complete technical documentation
- [Get Started](https://dash.cloudflare.com/sign-up): Sign up and start building
- [Pricing](/plans.md): See pricing details

## Related Products

- [Artifacts](/products/artifacts.md): Git-native versioned storage
- [Cache Reserve](/products/cache-reserve.md): Persistent caching for static content
- [Data Platform](/products/data-platform.md): Ingest, Catalog & Query
- [Hyperdrive](/products/hyperdrive.md): Global databases

---

*This is a markdown version of [https://www.cloudflare.com/products/d1](https://www.cloudflare.com/products/d1) for AI/LLM consumption.*
