Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Serverless SQL Database Bindings, Schema Execute, and Worker Queries

How to create a D1 database, bind it to Workers and Pages, run SQL locally or remotely, and query with prepared statements.

This page summarizes Cloudflare documentation on D1, Cloudflare’s native serverless SQL database. D1 behaves like familiar SQL storage (SQLite-compatible SQL): you create databases and tables, connect compute through bindings, and run queries from the Wrangler CLI or from Worker and Pages Function code.

D1 database: what it is and when you use it

Section titled “D1 database: what it is and when you use it”

A D1 database is conceptually similar to other SQL databases: it can hold tables, accept queries, and use indexes. Cloudflare positions it as the platform’s serverless SQL option for Workers and related products.

D1 is Cloudflare’s native serverless database.

— Cloudflare, Bindings

You typically reach for D1 when you want relational data next to Workers or Pages Functions without operating your own database servers—comments on a blog, a staff directory, member registries, or any app that needs SELECT, INSERT, and parameterized queries at the edge.

d1_databases bindings: connect Workers and Pages to D1

Section titled “d1_databases bindings: connect Workers and Pages to D1”

Bindings are how Workers and Pages Functions access D1. You declare them in the Wrangler configuration file (or in the Cloudflare dashboard), then read the database in code as env.<BINDING_NAME>.

Bindings allow your Workers to access resources, like D1 databases, KV namespaces, and R2 buckets, using a variable name in code.

— Cloudflare, Build a Comments API

Required fields for each binding:

Field Purpose
binding JavaScript variable name (for example DB); must be a valid JS identifier
database_name Human-readable name set at creation
database_id Unique ID from wrangler d1 create or wrangler d1 list

Optional fields include preview_database_id (recommended when using remote dev with wrangler dev --remote), migrations_dir, and migrations_pattern for migration file layout. See Wrangler configuration.

The binding name used to refer to the D1 database. The value (string) you set will be used to reference this database in your Worker. The binding must be a valid JavaScript variable name.

— Cloudflare, Wrangler configuration

D1 database bindings in the Cloudflare dashboard

Section titled “D1 database bindings in the Cloudflare dashboard”

For Pages Functions, you can add a binding under Settings → Bindings → Add → D1 database bindings, set Variable name, pick the database, then redeploy so the binding takes effect. Steps match Bindings.

For Workers, the Getting started guide describes the same flow under Workers & Pages → your Worker → Bindings.

wrangler d1 create: create a database from the CLI

Section titled “wrangler d1 create: create a database from the CLI”

Create a database with Wrangler (installed with npm create cloudflare or usable via npx wrangler):

npx wrangler@latest d1 create prod-d1-tutorial

When prompted Would you like Wrangler to add it on your behalf?, choosing Yes adds the d1_databases block to your Wrangler file automatically (Getting started).

Naming guidance from the docs: use ASCII, stay under 32 characters, prefer dashes over spaces, and name by use case (for example staging-db-web), not by binding names used in code.

Schema and wrangler d1 execute: local vs remote SQL

Section titled “Schema and wrangler d1 execute: local vs remote SQL”

Schema and seed data are usually kept in a .sql file, then applied with wrangler d1 execute.

Local execution writes to local storage under .wrangler/state, not to production:

npx wrangler d1 execute prod-d1-tutorial --local --file=./schema.sql

The same pattern appears in Adding local data and Build a Comments API (local schema first, then remote).

Verify tables locally:

npx wrangler d1 execute prod-d1-tutorial --local --command="SELECT name FROM sqlite_schema WHERE type='table'"

Run a SQL file on the remote database (--remote)

Section titled “Run a SQL file on the remote database (--remote)”

Before deploy, apply schema to the live database:

npx wrangler d1 execute prod-d1-tutorial --remote --file=./schema.sql

Without --local, commands target the remote database on Cloudflare’s network; with --local, they target the local dev copy (Getting started, Local development).

When using Wrangler in the default local development mode, files will be written to local storage instead of the preview or production database.

— Cloudflare, Wrangler configuration

Ad-hoc SQL:

npx wrangler d1 execute staff-directory --command "SELECT name FROM sqlite_schema WHERE type ='table'"

Or with a file:

wrangler d1 execute staff-directory --file=./schema.sql

(Build a Staff Directory Application).

For imports, use SQL dump files (not raw .sqlite3 files directly). Example:

npx wrangler d1 execute example-db --remote --file=users_export.sql

wrangler d1 execute --file is limited to 5GiB per file (Import and export data). After import you may see a reserved _cf_KV table in sqlite_schema; it is not user-queryable.

D1 Workers Binding API: prepare, bind, and run in Worker code

Section titled “D1 Workers Binding API: prepare, bind, and run in Worker code”

In a Worker, the binding exposes the D1 Workers Binding API. The usual pattern is prepared statements with placeholders, bind() for parameters, then run(), first(), all(), raw(), or batch operations (Workers Binding API).

Example from Getting started:

const { results } = await env.prod_d1_tutorial
.prepare("SELECT * FROM Customers WHERE CompanyName = ?")
.bind("Bs Beverages")
.run();

The docs stress that bind() passes values safely and helps prevent SQL injection when users influence query arguments.

Hono on Workers types the binding and uses c.env.DB (Query D1 from Hono):

let { results } = await c.env.DB.prepare(
"SELECT * FROM users WHERE user_id = ?",
).bind(userId).run();

Express on Workers can use env.DB from cloudflare:workers with the same prepare / bind / all pattern (Deploy an Express.js application on Cloudflare Workers). Python Workers call self.env.DB.prepare(...).bind(...).run() (Query a D1 Database).

Pages Functions: D1 bindings and local wrangler pages dev

Section titled “Pages Functions: D1 bindings and local wrangler pages dev”

Pages Functions access D1 through context.env.<BINDING_NAME> after dashboard or Wrangler configuration (Bindings).

For local Pages development with D1:

  1. Configure D1 in a Wrangler file in the Pages project root (see Local development for the preview_database_id pattern when needed).

  2. Run npx wrangler pages dev with an explicit D1 mapping, for example:

    npx wrangler pages dev <OUTPUT_DIR> --d1 NORTHWIND_DB=xxxx-xxxx-xxxx-xxxx-xxxx
  3. Use context.env.NORTHWIND_DB in your function code.

If a binding is specified in a Wrangler configuration file and via a command-line argument, the command-line argument takes precedence.

— Cloudflare, Bindings

Framework access patterns (Workers vs Pages)

Section titled “Framework access patterns (Workers vs Pages)”
Runtime How you reach D1 Doc
Workers + Hono c.env.DB on Bindings type Query D1 from Hono
Pages + Hono handle(app) export; --d1 on pages dev Query D1 from Hono
Pages + Remix context.cloudflare.env.DB in loaders Query D1 from Remix
Pages + SvelteKit platform.env.DB in +server.ts Query D1 from SvelteKit
Django on Workers ENGINE: django_cf.db.backends.d1, CLOUDFLARE_BINDING Django D1 backend

Community options such as Prisma ORM with D1 or libraries listed under Community projects sit on top of the same bindings and Wrangler migration/execute workflow.

Bulk import via D1 REST API (outside Workers)

Section titled “Bulk import via D1 REST API (outside Workers)”

When you need large imports from a Node script rather than Wrangler, the Bulk import to D1 using REST API tutorial uses a four-step flow: init upload (MD5 etag), upload SQL to R2, ingest, then poll until complete. The target table schema must already exist and match the data. If you hit statement too long, split SQL into smaller chunks.

D1’s built-in REST API is described as best for administrative use with global API rate limits; for app access from outside Workers, Cloudflare documents a proxy Worker API pattern instead.

Common mistakes when using D1 bindings and execute

Section titled “Common mistakes when using D1 bindings and execute”
  • Deploying without remote schema: Running only --local --file leaves production empty until you run --remote --file (Getting started, Build a Comments API).
  • Wrong binding name in code: The property on env must match binding in d1_databases, not database_name.
  • Assuming local equals production: Default Wrangler dev uses local D1 storage; remote queries need --remote on execute or an explicit remote dev/binding setup (Remote development).
  • Skipping redeploy after dashboard binding changes on Pages (Bindings).
  • Importing raw .sqlite3 files: Convert to SQL first (Import and export data).
  1. Confirm d1_databases (or dashboard bindings) lists the expected binding, database_name, and database_id (Wrangler configuration).
  2. Run npx wrangler d1 execute <DATABASE_NAME> --local --command="SELECT name FROM sqlite_schema WHERE type='table'" and repeat with --remote after schema deploy (Getting started).
  3. Deploy the Worker or Pages project, then call a route that uses env.<BINDING>.prepare(...).run() and inspect JSON results (Workers Binding API).
  4. In the Cloudflare dashboard, open D1 SQL database, select your database, and use Console or Tables to verify rows match CLI output (Getting started).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match your setup or the linked Cloudflare docs, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong so it can be corrected or clarified.