<!-- SPDX-License-Identifier: MIT -->
<!-- SPDX-FileCopyrightText: 2025-2026 Marcus Quinn -->

# Cloudflare D1 Database

Managed SQLite for Workers. Use it for relational queries and stronger consistency than KV, and model many small databases rather than one shared cluster.

## Best Fit

- Per-user, per-tenant, or per-entity data sets.
- Relational queries, secondary indexes, and SQL migrations.
- Recovery needs covered by 30-day Time Travel.

## Core Properties

| Property | Detail |
|----------|--------|
| Query model | SQLite-compatible SQL |
| Scale unit | 10 GB maximum per database |
| Recovery | 30-day Time Travel |
| Access | Worker binding and HTTP API |
| Limits | 1 MB row, 30s query timeout, 10,000-statement batch |
| Pricing | Query and storage based |

## Query API

```typescript
const { results } = await env.DB.prepare('SELECT * FROM users WHERE active = ?').bind(true).all(); // all rows
const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();        // first or null
```

Methods: `.all()` rows, `.first()` / `.first(col)` single value, `.run()` writes, `.raw()` array rows. Use `batch()` for multiple independent statements in one round trip — the main transaction primitive. See [d1-patterns.md](./d1-patterns.md) for batch examples.

## Commands

```bash
# Setup: create → apply migrations → dev
wrangler d1 create <db-name>
wrangler d1 execute <db-name> --local --file=./migrations/0001_schema.sql
wrangler d1 execute <db-name> --remote --file=./migrations/0001_schema.sql
wrangler dev --persist-to=./.wrangler/state

# Inspect / manage
wrangler d1 list
wrangler d1 execute <db-name> --remote --command="SELECT * FROM users"
wrangler d1 export <db-name> --remote --output=./backup.sql
wrangler d1 time-travel restore <db-name> --timestamp="2024-01-15T14:30:00Z"
wrangler d1 delete <db-name>
```

## Read Next

- [d1-patterns.md](./d1-patterns.md) - Pagination, bulk operations, caching, session storage, multi-tenant layouts
- [d1-gotchas.md](./d1-gotchas.md) - SQL injection prevention, indexing, query limits, local-vs-remote differences
- [workers.md](./workers.md) - Runtime and handler patterns
- [kv.md](./kv.md) - Read-heavy caching and eventual consistency
- [r2.md](./r2.md) - Store blobs outside D1
- [queues.md](./queues.md) - Buffer high-throughput writes
- [durable-objects.md](./durable-objects.md) - Coordinate strongly ordered workflows
