Skip to content

Index recommendations

D1 Insights recommends indexes for your D1 databases. Each recommendation includes a CREATE INDEX statement, the queries it is expected to speed up, and usage metrics for those queries.

An index lets D1 find rows without scanning a whole table. Scanning fewer rows makes queries faster and lowers rows-read charges. Indexes also use storage and add work to every write to the table, so review each recommendation before you change your schema.

View recommendations

  1. In the Cloudflare dashboard, go to the D1 SQL database page.

    Go to D1 SQL database ↗

    Databases with recommendations have a dot on their ... menu button. Their menu includes View recommendations.

  2. Select a database, then select the Metrics tab.

    The Recommendations card at the top lists up to 10 recommendations for the database, highest impact first.

List recommendations for every database in your account:

npx cf d1 insights recommendations

List recommendations for specific databases:

npx cf d1 insights recommendations --database-id <DATABASE_ID_1>,<DATABASE_ID_2>

The API token needs the D1 Read permission.

List recommendations for every database in your account:

curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/d1/insights/recommendations" \
	--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

List recommendations for specific databases:

curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/d1/insights/recommendations?database_id=$DATABASE_ID_1,$DATABASE_ID_2" \
	--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"

Recommendations are sorted from highest to lowest estimated impact. The CLI and API accept these options:

API parameter CLI flag Description
database_id --database-id Only return recommendations for these databases, up to 50. A database that does not exist or is in another account returns no results.
limit --limit Number of recommendations per page, from 1 to 100 (default: 20).
cursor --cursor result_info.next_cursor from the previous page. Pass the same database_id values as the previous request.

result_info.next_cursor is null on the last page. When the Insights setting is off, the list is empty.

How recommendations are generated

D1 analyzes your databases in the background. For a database with recent queries that scan many more rows than they return, D1 sends the query statements, their usage, and the database schema to Workers AI, which suggests indexes.

D1 checks that each suggested statement is a single valid CREATE INDEX statement. It does not run the statement or check it against your schema, so test it before you apply it.

Each analysis replaces the previous recommendations for that database. Recommendations that are not refreshed expire after 7 days. You cannot request an analysis on demand, but you can fetch the underlying query data and have an AI agent find missing indexes for you.

A database has no recommendations when it had little recent query activity, its queries already use indexes well, or D1 did not find an index that would help.

Turn recommendations on or off

The Insights setting controls whether D1 sends your account's query data to Workers AI. It applies to every database in the account.

When you turn the setting off, D1 stops generating recommendations for your account and stops returning them in the dashboard and API. D1 query metrics, billing, and other D1 features are not affected. Recommendations generated less than 7 days earlier show again if you turn the setting back on.

  1. In the Cloudflare dashboard, go to the D1 SQL database page.

    Go to D1 SQL database ↗
  2. Select a database, then select the Metrics tab.

  3. In the Recommendations card, select the settings icon. If recommendations are off, select Turn on instead.

  4. Confirm the change.

Only account administrators can change this setting.

Check the setting:

npx cf d1 insights settings get
{
	"ai_enabled": true
}

Turn it off:

npx cf d1 insights settings update --ai-enabled=false

Check the setting. The API token needs the Account Settings Read permission:

curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/d1/insights/settings" \
	--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"
{
	"success": true,
	"result": { "ai_enabled": true },
	"errors": [],
	"messages": []
}

Turn it off. The API token needs the Account Settings Write permission:

curl --request PUT "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/d1/insights/settings" \
	--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
	--json '{ "ai_enabled": false }'

Set ai_enabled to true to turn it back on.

Read a recommendation

The following response contains one recommendation for the orders-prod database:

{
	"success": true,
	"result": {
		"recommendations": {
			"items": [
				{
					"id": "9f8a7b6c-5d4e-4a21-9234-6f7890abcdef",
					"database_id": "7c9e2b14-3f6a-4d8e-9b21-5a0c8f3e6d47",
					"database_name": "orders-prod",
					"generated_at": "2026-11-20T10:32:00.000Z",
					"query_window": {
						"from": "2026-11-19T10:00:00.000Z",
						"to": "2026-11-20T10:00:00.000Z"
					},
					"type": "index_suggestion",
					"priority": "high",
					"summary": "Create an index on OrderDetail.OrderId",
					"reasoning": "Two query patterns filter OrderDetail by OrderId and scan the whole table.",
					"suggestions": [
						{
							"kind": "index_creation",
							"sql": "CREATE INDEX idx_OrderDetail_OrderId ON OrderDetail(OrderId);"
						}
					],
					"impacted_queries": [
						{
							"query": "SELECT * FROM OrderDetail WHERE OrderId = ?",
							"metrics": {
								"execution_count": 320,
								"total_rows_read": 1250000,
								"total_rows_written": 0,
								"p95_query_duration_ms": 42.8
							}
						}
					]
				}
			]
		}
	},
	"result_info": {
		"next_cursor": null
	},
	"errors": [],
	"messages": []
}

Each item in result.recommendations.items has these fields:

Field Description
id Recommendation identifier.
database_id, database_name The database the recommendation is for.
generated_at When D1 generated the recommendation.
query_window.from, query_window.to The window of query usage the recommendation is based on. from is inclusive, to is exclusive.
type Always index_suggestion.
priority high or low. high means the impacted queries spend a lot of time scanning rows they do not return. Review these first.
summary A short description of the change.
reasoning Why the change is recommended.
suggestions[].kind Always index_creation.
suggestions[].sql The CREATE INDEX statement to apply.
impacted_queries[].query A query the index is expected to speed up.
impacted_queries[].metrics How many times the query ran (execution_count), the rows it read and wrote (total_rows_read, total_rows_written), and its 95th percentile duration (p95_query_duration_ms) during query_window.

The metrics come from D1 query analytics, not from Workers AI. Like other D1 per-query analytics, they are estimates computed from sampled data.

Apply a recommendation

Apply the suggested statement with a D1 migration, so the schema change is stored with your application code.

  1. Review the suggested statement, the table and columns it indexes, and the impacted queries.

  2. From your Worker project directory, create a migration:

    npx cf d1 migrations create add_orderdetail_orderid_index
    npx wrangler d1 migrations create <DATABASE_NAME> add_orderdetail_orderid_index
  3. Add the suggested statement to the new migration file:

    migrations/0001_add_orderdetail_orderid_index.sqlsql
    CREATE INDEX idx_OrderDetail_OrderId ON OrderDetail(OrderId);
  4. Apply the migration to your local database:

    npx cf d1 migrations apply <DATABASE_ID> --local
    npx wrangler d1 migrations apply <DATABASE_NAME> --local
  5. Run the impacted queries against your local database, and check that they return the same results and read fewer rows.

  6. Apply the migration to your remote database:

    npx cf d1 migrations apply <DATABASE_ID>
    npx wrangler d1 migrations apply <DATABASE_NAME> --remote

    If you use Wrangler environments, add --env <ENVIRONMENT> to the Wrangler commands and repeat steps 4 to 6 for each environment.

If the index fixes the impacted queries, the next analysis of the database no longer recommends it.

Use an AI agent

You can give the recommendations to an AI coding agent to write the migration. Copy the following prompt and replace the placeholder with the output of npx cf d1 insights recommendations --database-id <DATABASE_ID>:

You are a database engineer working on a Cloudflare D1 (SQLite) database.

Below is a JSON list of D1 index recommendations. For each recommendation, review the
suggested CREATE INDEX statement against the impacted queries and the current schema.
Write a D1 migration file that contains only the statements that are safe to apply.
Explain any recommendation you leave out.

```json
<PASTE_RECOMMENDATIONS_JSON_HERE>
```

Was this helpful?