# Cloudflare D1: A Practical Guide to SQLite for Workers

You have written your first Cloudflare Worker and it needs a database. Out of habit you go looking for the connection string: a host, a port, a username and a password to put in an environment variable.

There is none. With Cloudflare D1 you write three lines of configuration, and a database object appears in your code as `env.DB`. No connection to open, no pool to size, no password to leak.

That missing connection string is the key to D1. It is not a database server that you connect to. It is a SQLite database attached to your code by the platform. Understand that, and its strengths and limits both make sense.

## What D1 is

D1 is Cloudflare's managed SQL database. Each D1 database is a SQLite database that Cloudflare stores, replicates for durability and backs up for you. The SQL you write is SQLite's.

It is designed to be used from **Workers**, Cloudflare's serverless functions. The link between the two is called a **binding**: a named handle, declared in your project's configuration, that the platform hands to your code at run time.

| Term | Meaning |
|---|---|
| Worker | A serverless function that runs on Cloudflare's network |
| Binding | A named link from a Worker to a resource such as a D1 database |
| Wrangler | Cloudflare's command-line tool for developing and deploying |
| Migration | A numbered SQL file that changes the schema, applied in order |
| Time Travel | D1's built-in point-in-time restore |

There are two ways in. Your Worker uses the binding, which is fast. Everything else (Wrangler, dashboards, outside tools) uses Cloudflare's HTTP API, which is meant for administration.

## Why teams choose it

- **Nothing to connect or operate.** No servers, versions, connection limits or pools.
- **It is SQLite.** Familiar SQL, including JSON functions and full-text search, and you can export a database and open it with ordinary SQLite tools.
- **It costs almost nothing when idle.** Billing follows the rows your queries touch and the storage you use.
- **Backups are built in.** Time Travel can restore a database to any minute in its recent history.
- **Local development is real.** Wrangler runs a local SQLite copy, so you can develop and test offline.
- **Many small databases are normal.** The platform expects you to create a database per customer or per project when that suits the design.

## Where D1 fits, and where it does not

**A strong choice for:**

- Applications already built on Cloudflare Workers or Pages
- Small and medium products: sites, APIs, internal tools, prototypes
- Read-heavy workloads
- Designs with a separate database per tenant

**Look elsewhere when:**

- **One database must grow very large.** Each D1 database has a size cap (10 GB on the paid plan at the time of writing). D1 scales by having many databases, not one huge one.
- **Writes are heavy.** A D1 database handles one query at a time. Short queries make that fine. Sustained heavy writing calls for PostgreSQL or MySQL.
- **Your application does not run on Cloudflare.** From outside you only have the HTTP API, which is slower and rate limited. A service such as Turso, or a managed PostgreSQL, suits a server elsewhere.
- **You need long, interactive transactions.** D1 does not accept `BEGIN` and `COMMIT` from your code. You get batches, described below.
- **You need PostgreSQL features.** If your Worker should talk to an existing PostgreSQL or MySQL database, Cloudflare's Hyperdrive service is the tool for that.

## Using it the right way

### Create a database and bind it

```bash
npx wrangler d1 create shop-db
```

Wrangler prints a block to add to your `wrangler.toml`:

```toml
[[d1_databases]]
binding = "DB"
database_name = "shop-db"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
```

`binding` is the name your code will use.

### Change the schema with migrations

```bash
npx wrangler d1 migrations create shop-db create_orders
```

That creates a numbered file in a `migrations` folder. Put your SQL in it:

```sql
CREATE TABLE customers (
  id          INTEGER PRIMARY KEY,
  email       TEXT NOT NULL UNIQUE,
  order_count INTEGER NOT NULL DEFAULT 0
);

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers (id),
  total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
  status      TEXT NOT NULL DEFAULT 'pending',
  created_at  TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
);

CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at);
```

Then apply it, first to your local copy and then to the real database:

```bash
npx wrangler d1 migrations apply shop-db --local
npx wrangler d1 migrations apply shop-db --remote
```

D1 records which migrations have run, so each is applied once. Unlike plain SQLite, D1 enforces foreign keys by default.

### Query from a Worker

```ts
export interface Env {
  DB: D1Database;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { results } = await env.DB
      .prepare(
        "SELECT id, total_cents, status FROM orders WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20",
      )
      .bind(42)
      .all();

    return Response.json(results);
  },
};
```

`prepare` plus `bind` keeps values out of the SQL text, which is your protection against SQL injection. Three methods finish a statement:

| Method | Returns | Use for |
|---|---|---|
| `.all()` | All rows, plus metadata | Lists |
| `.first()` | The first row, or `null` | Lookups by key |
| `.run()` | Metadata only | `INSERT`, `UPDATE`, `DELETE` |

### Use batch as your transaction

```ts
await env.DB.batch([
  env.DB.prepare("INSERT INTO orders (customer_id, total_cents) VALUES (?, ?)").bind(42, 1250),
  env.DB.prepare("UPDATE customers SET order_count = order_count + 1 WHERE id = ?").bind(42),
]);
```

A batch sends the statements in one call and runs them as a single transaction. If any statement fails, none of them take effect. Because you cannot hold a transaction open between calls, design writes so that everything belonging together goes in one batch.

### Run SQL from the terminal

```bash
npx wrangler d1 execute shop-db --remote \
  --command "SELECT status, count(*) FROM orders GROUP BY status"

npx wrangler d1 execute shop-db --remote --file=./seed.sql
```

Without `--remote`, current Wrangler versions run against your local development copy. That default has saved many people from changing production by accident, and has confused just as many who wondered where their rows went.

### Know your undo

```bash
npx wrangler d1 time-travel info shop-db
npx wrangler d1 time-travel restore shop-db --timestamp=2026-03-01T09:00:00Z
```

Time Travel restores the database in place: the current contents are replaced by the earlier state. The history window is 30 days on the paid plan and shorter on the free plan. For a copy you keep yourself:

```bash
npx wrangler d1 export shop-db --remote --output=./shop-backup.sql
```

## How the pricing shapes your habits

D1 meters three things: rows read, rows written and storage. There is a free allowance, the paid Workers plan includes a larger one, and use beyond that is charged. D1 adds no charge for data transfer. Your Worker's own requests are billed as usual.

As with other row-metered services, "rows read" means rows the database had to examine, not rows it returned. That gives three rules:

- **Index what you filter on.** Without an index, a query examines every row in the table and you pay for each one. With the index above, "orders for customer 42" examines only that customer's rows.
- **Do not add indexes you will not use.** Each index on a table is written on every insert, and those writes count as rows written.
- **Measure, do not guess.** Every result carries the numbers:

```ts
const res = await env.DB.prepare("SELECT * FROM orders WHERE status = ?").bind("pending").all();
console.log(res.meta.rows_read, res.meta.rows_written);
```

If `rows_read` is close to the size of the table, the query is scanning it. `EXPLAIN QUERY PLAN` will confirm that, and an index will usually fix it. After adding indexes, run `PRAGMA optimize;` so SQLite refreshes the statistics it plans with.

Counting is the classic trap. `SELECT count(*) FROM orders` examines every row. If a page shows a total on every load, keep that total in a small counter table that you update in the same batch as the write.

## Common mistakes

- **Running a command without `--remote` and thinking production changed.** Or the reverse.
- **Sending `BEGIN` and `COMMIT`.** Use `batch`.
- **One query per row in a loop.** Each call is a round trip. Write one query with `IN (...)` or a join, or batch the statements.
- **Unindexed filters.** Slow, and billed by the row.
- **Planning for one giant database.** The size cap means large systems should split by tenant or by function from the start.
- **Using the HTTP API as your application's data path.** It is for administration. Applications should run in a Worker and use the binding.
- **Editing the schema by hand in production.** Use migration files so local, staging and production stay in step.
- **Treating Time Travel as an archive.** It covers a limited window. Export what you must keep.
- **An account-wide API token in scripts.** Create a token limited to D1 on the one account.

## Quick reference

| Task | Command |
|---|---|
| Create a database | `npx wrangler d1 create shop-db` |
| List databases | `npx wrangler d1 list` |
| Database details and size | `npx wrangler d1 info shop-db` |
| Run a statement | `npx wrangler d1 execute shop-db --remote --command "..."` |
| Run a SQL file | `npx wrangler d1 execute shop-db --remote --file=./file.sql` |
| New migration | `npx wrangler d1 migrations create shop-db <name>` |
| Pending migrations | `npx wrangler d1 migrations list shop-db --remote` |
| Apply migrations | `npx wrangler d1 migrations apply shop-db --remote` |
| Export | `npx wrangler d1 export shop-db --remote --output=./backup.sql` |
| Restore to a time | `npx wrangler d1 time-travel restore shop-db --timestamp=<time>` |
| List tables | `SELECT name FROM sqlite_master WHERE type = 'table';` |

D1 works best when you accept its shape: small databases, short queries, indexes on every filter, batches for anything that must happen together.

## Exploring Cloudflare D1 with CreamDB

Wrangler runs one statement at a time and prints text. To look through a D1 database, [CreamDB](https://www.creamdb.com) connects to it from a browser tab, with nothing to install.

- Connect with your Cloudflare account ID, an API token that has D1 permission, and the database name. The token is stored encrypted.
- Browse tables, views and columns in a tree, and open a table in a grid where paging, sorting and filtering run in the database.
- Write SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- Ask in plain English and get the SQL, a result table and a chart.

The assistant only reads on its own. Any change waits as an approval card that you answer, and read-only mode on the server blocks writes.

CreamDB reaches D1 through Cloudflare's HTTP API, the same door Wrangler uses. That makes it right for exploring, checking data and occasional fixes, and it is subject to Cloudflare's API rate limits. Queries you run still count as rows read. It is free to start.

