Inferensys

Prompt

Indexing Strategy Recommendation Prompt

A practical prompt playbook for generating, validating, and integrating AI-powered index recommendations into database engineering workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

A practical guide for database engineers and backend developers to generate risk-aware index recommendations from concrete schemas and query patterns.

This prompt is designed for database engineers and backend developers who need to move beyond generic indexing advice and produce a prioritized, production-ready set of index recommendations. The core job-to-be-done is taking a concrete CREATE TABLE statement and a representative sample of SELECT, UPDATE, and DELETE queries, then generating a list of proposed indexes that balances query performance against write amplification. It is most effective when used during schema review, before writing a migration script, or when diagnosing a specific slow query pattern where the current indexing strategy is insufficient. The ideal user has the actual DDL and can provide real query patterns from application code, an observability platform, or a slow-query log.

The prompt forces the model to reason about trade-offs rather than suggesting every possible index. It requires the model to consider covering indexes to avoid key lookups, the write cost of maintaining additional indexes on high-throughput tables, and the migration cost of creating an index on a large production table. Do not use this prompt for abstract database theory questions, for schemas where you cannot provide actual query samples, or when you need a real-time performance diagnosis from a running system. It is a design-time reasoning tool, not a replacement for EXPLAIN ANALYZE or a database monitoring platform. The output is a structured recommendation list, not executable SQL, and should always be reviewed by an engineer who understands the specific database system, version, and workload characteristics.

Before using this prompt, gather the exact DDL for the table in question, including all existing indexes and constraints. Collect a representative set of query patterns, parameterized to hide sensitive values but preserving the WHERE clause structure, JOIN conditions, ORDER BY clauses, and approximate frequency. If you lack actual query samples, stop here—the prompt will produce unreliable, generic advice without them. After receiving the model's output, validate each recommendation against your database's specific B-tree, hash, GIN, or GiST index capabilities. For high-risk production tables, always test the recommended indexes in a staging environment with a comparable data volume and query load before applying them to production. The next step is to take the prioritized list and write a migration script, but only after an engineer has confirmed the recommendations are safe and appropriate for your specific operational context.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Indexing Strategy Recommendation Prompt fits your current task before you wire it into a pipeline.

01

Good Fit: Concrete Query Patterns

Use when: you can provide a representative sample of actual query patterns (SELECT, JOIN, WHERE, ORDER BY, GROUP BY) along with table schemas and approximate row counts. The prompt produces a prioritized index list with expected impact and migration cost estimates. Guardrail: supply at least 5-10 distinct query patterns covering both frequent and infrequent access paths to avoid overfitting to a single workload.

02

Bad Fit: Abstract or Undefined Workloads

Avoid when: the query workload is unknown, purely speculative, or described only in vague business terms without SQL-level detail. The prompt cannot reason about indexing without concrete predicates, join columns, and sort orders. Guardrail: if you cannot produce example queries, run a query log analysis first or use the Query Pattern Analysis Prompt for Schema Design instead.

03

Required Inputs: Schema, Queries, and Constraints

Risk: incomplete inputs produce generic or unsafe recommendations. The prompt needs table DDL with column types, existing indexes, primary/foreign keys, row counts, and a set of parameterized query patterns with frequency annotations. Guardrail: validate that every table referenced in a query has its schema provided, and flag any missing existing-index information before trusting the output.

04

Operational Risk: Write Amplification

Risk: the prompt may recommend indexes that improve read performance but impose unacceptable write penalties on high-throughput OLTP tables. Over-indexing is a common failure mode when only read patterns are considered. Guardrail: always include write frequency and latency sensitivity for each table in the input context, and review recommendations against insert/update/delete SLAs before applying.

05

Operational Risk: Index Interaction Blindness

Risk: the prompt may recommend indexes that overlap with existing ones or conflict with each other, leading to redundant storage and optimizer confusion. Guardrail: include the full list of existing indexes in the input and add an explicit constraint requesting the prompt to identify and flag redundant or overlapping proposals before finalizing the recommendation list.

06

Boundary: Not a Replacement for EXPLAIN

Risk: the prompt reasons from heuristics and schema metadata, not actual query planner behavior. Recommendations may not match real execution plans, especially with complex statistics, data skew, or database-specific optimizer quirks. Guardrail: treat the output as a prioritized hypothesis list. Always validate top recommendations with EXPLAIN on a representative data volume before deploying to production.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt for generating index recommendations from query patterns and table schemas.

This prompt template is designed to be pasted directly into your AI system. It instructs the model to act as a database performance engineer, analyzing provided query patterns and table schemas to produce a structured, prioritized set of index recommendations. The output is designed to be actionable, including the index definition, expected impact, and potential risks like write amplification. Replace the square-bracket placeholders with your specific database context, query logs, and constraints before execution.

text
You are a database performance engineer specializing in indexing strategy. Your task is to analyze the provided table schemas and query patterns to recommend a set of indexes. Follow the instructions precisely.

# INPUT DATA

## Table Schemas
[TABLE_SCHEMAS]

## Query Patterns
[QUERY_PATTERNS]

# CONSTRAINTS
- Target database system: [DATABASE_SYSTEM]
- Maximum recommended indexes per table: [MAX_INDEXES_PER_TABLE]
- Write-to-read ratio: [WRITE_READ_RATIO]
- Storage budget (if any): [STORAGE_BUDGET]

# OUTPUT SCHEMA
Produce a JSON object with a single key "recommendations", which is an array of objects. Each object must have the following fields:
- "table_name": (string) The name of the table.
- "proposed_index": (string) The exact DDL statement to create the index.
- "index_type": (string) e.g., "BTREE", "HASH", "GIN", "partial", "composite".
- "target_queries": (array of strings) The specific query patterns from the input that this index will improve.
- "expected_impact": (string) A concise explanation of how the index will improve performance (e.g., "Enables Index-Only Scan for query #3, avoiding full table scan").
- "concerns": (array of strings) A list of potential downsides, such as write amplification, large index size, or low selectivity.
- "priority": (string) One of "HIGH", "MEDIUM", or "LOW".

# INSTRUCTIONS
1. Analyze the `WHERE`, `JOIN`, `ORDER BY`, and `GROUP BY` clauses in the query patterns.
2. Identify columns used for filtering, sorting, and joining that are not already part of a primary key or existing index.
3. Prioritize indexes that cover the most frequent and expensive queries, as indicated by the `WRITE_READ_RATIO`.
4. Explicitly flag any recommendation that could cause significant write amplification.
5. If no beneficial indexes can be found, return an empty array for "recommendations".
6. Do not recommend redundant indexes.

To adapt this prompt, start by populating [TABLE_SCHEMAS] with the output of your database's SHOW CREATE TABLE or equivalent DDL. For [QUERY_PATTERNS], use sanitized, parameterized versions of your slow query logs or application's most critical access patterns. The [WRITE_READ_RATIO] is crucial; a write-heavy workload should result in fewer, more targeted index recommendations. After receiving the output, validate the JSON structure against the defined schema before considering implementation. For high-risk production databases, always require a human DBA to review the proposed proposed_index DDL and concerns before executing any changes.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Indexing Strategy Recommendation Prompt needs to produce a reliable, prioritized list of index recommendations. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check that the input is well-formed and sufficient.

PlaceholderPurposeExampleValidation Notes

[TABLE_SCHEMA]

Complete DDL for the table(s) under review, including all columns, existing indexes, and constraints

CREATE TABLE orders (id UUID PRIMARY KEY, customer_id INT, status VARCHAR(20), created_at TIMESTAMPTZ, total DECIMAL);

Parse check: valid DDL syntax. Must include column types and existing indexes. Reject if only column names provided.

[QUERY_PATTERNS]

List of representative queries with frequency estimates and latency targets

SELECT * FROM orders WHERE customer_id = ? AND status = ? (1000/s, p99 < 10ms)

Schema check: each query must reference columns present in [TABLE_SCHEMA]. Frequency must be numeric. Missing latency targets triggers a warning.

[DATA_VOLUME]

Current row count, growth rate, and table size in bytes

50M rows, +2M/week, 12GB table size

Type check: all three values required. Growth rate must include time unit. Null not allowed.

[WRITE_PROFILE]

INSERT, UPDATE, DELETE rates per second and whether writes are batched or single-row

INSERT 500/s single-row, UPDATE 200/s batched (100 rows/batch), DELETE 10/s

Parse check: each operation type must have a rate. Batching flag required. Reject if write rates are missing while recommending indexes.

[EXISTING_INDEXES]

List of current indexes with type, columns, and size if known

idx_orders_customer ON orders(customer_id) BTREE, 1.2GB

Cross-reference check: every index listed must exist in [TABLE_SCHEMA]. Size field optional but recommended for cost estimation.

[HARDWARE_PROFILE]

Database engine, version, instance size, memory, and storage type

PostgreSQL 15.4, db.r6g.xlarge (32GB RAM), gp3 3000 IOPS

Completeness check: engine and version required. Memory and IOPS needed for index size feasibility analysis. Null allowed for storage type if unknown.

[CONSTRAINTS]

Business rules, uniqueness requirements, and regulatory constraints affecting index design

customer_id+status must be unique per active order; GDPR requires fast deletion by user_id

Human review required: constraints often come from domain experts. Flag if [CONSTRAINTS] is empty while [QUERY_PATTERNS] includes filtered queries.

[MIGRATION_WINDOW]

Allowed downtime, maintenance window duration, and online index build capability

Online index builds supported, 2-hour maintenance window weekly, zero-downtime required

Boolean check: online build capability must be true or false. Window duration must include unit. Reject if migration window is missing and indexes are recommended on large tables.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the indexing strategy prompt into a database review pipeline with validation, safety checks, and human approval.

The indexing strategy prompt is not a standalone advisor—it is a component in a database change management workflow. Wire it into your application as a structured recommendation generator that produces machine-readable output for downstream validation, comparison, and approval. The prompt expects a DDL schema and a set of query patterns as input, and it returns a prioritized list of proposed indexes with impact estimates, migration costs, and risk flags. Treat the output as a draft recommendation, not a final execution plan.

Model choice and invocation: Use a model with strong SQL reasoning capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature to 0 or near-zero to maximize deterministic, repeatable recommendations. The prompt should be called with structured input containing [SCHEMA_DDL] and [QUERY_PATTERNS] as separate fields. Parse the JSON output into your application's index review queue. Validate that every recommended index includes a table_name, columns array, index_type, estimated_impact, and migration_cost field. Reject and retry any response that fails schema validation—do not pass incomplete recommendations downstream.

Safety and over-indexing guardrails: Before surfacing recommendations, run automated checks against the output. Count the total number of proposed indexes per table and flag any table receiving more than a configurable threshold (start with 5). Check for duplicate or prefix-redundant indexes (e.g., an index on (a, b) makes a separate index on (a) redundant for many query patterns). Cross-reference the write_amplification_risk field in each recommendation—if the prompt flags high risk but still recommends the index, escalate for human review. Log every recommendation with the input schema hash, query pattern fingerprint, model version, and timestamp for auditability.

Human-in-the-loop integration: Route all recommendations through a review queue before execution. For low-risk recommendations (low write amplification, low migration cost, clear query coverage), allow auto-approval with a notification. For high-risk or high-cost recommendations, require explicit DBA or engineering lead approval. Include a diff view showing the proposed index DDL alongside the existing schema. The prompt's covering_concerns field should be displayed to reviewers so they understand the trade-offs already considered. Never auto-execute CREATE INDEX statements directly from model output without human review in production environments.

Retry and failure handling: If the model returns malformed JSON, retry once with a repair prompt that includes the raw output and the expected schema. If the second attempt fails, log the failure and alert the engineering team—do not silently drop the recommendation request. If the model returns an empty recommendations array when query patterns clearly suggest missing indexes, flag this as a potential false negative and escalate. Monitor the rate of accepted vs. rejected recommendations over time to detect model drift or schema changes that degrade recommendation quality.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the structure and content of the generated indexing recommendation JSON before integrating it into a migration pipeline or review process.

Field or ElementType or FormatRequiredValidation Rule

recommendation_id

string (UUID v4)

Must match UUID v4 regex. Reject if missing or malformed.

generated_at

string (ISO 8601)

Must parse as valid UTC datetime. Reject if in the future.

target_table

string

Must match a table name provided in [SCHEMA_INPUT]. Reject if unknown.

proposed_indexes

array of objects

Array must contain 1-10 items. Reject if empty or exceeds limit.

proposed_indexes[].name

string

Must match pattern idx_<table>_<column_abbrev>. Reject on collision within array.

proposed_indexes[].columns

array of strings

Each column must exist in [SCHEMA_INPUT] for the target_table. Reject unknown columns.

proposed_indexes[].estimated_impact

string (enum)

Must be one of: high, medium, low. Reject on unknown value.

risk_assessment.over_indexing_warning

boolean

Must be true if proposed_indexes count > 5 and write_amplification_risk is high. Flag for human review if mismatch.

PRACTICAL GUARDRAILS

Common Failure Modes

Indexing strategy recommendations can go wrong in predictable ways. These are the most common failure modes when generating index advice from query patterns and schemas, with concrete guardrails to catch them before they reach production.

01

Over-Indexing from Unfiltered Query Logs

What to watch: The prompt recommends an index for every query in the log, including ad-hoc analyst queries, one-off debugging, and queries that run once per quarter. This produces 30+ indexes on a single table, crushing write performance and ballooning storage. Guardrail: Require the prompt to classify queries by frequency and criticality. Only recommend indexes for queries above a defined threshold (e.g., top 95% of execution time or calls). Add an explicit max_indexes_per_table constraint in the prompt harness.

02

Ignoring Write Amplification Costs

What to watch: The recommendation focuses exclusively on read performance and ignores the table's write volume. An index that speeds up a daily report by 200ms adds 40ms to every INSERT on a table receiving 10,000 writes per second. Guardrail: Require the prompt to estimate write impact for each proposed index. Include a write_amplification_risk field in the output schema and flag indexes on tables with high insert/update/delete rates for human review.

03

Recommending Indexes the Optimizer Won't Use

What to watch: The prompt suggests a theoretically correct index, but the query planner ignores it due to low cardinality, outdated statistics, function-wrapped columns, or implicit type conversions in the actual queries. Guardrail: Add a validation step that runs EXPLAIN plans for each proposed index against the provided queries. The prompt output should include expected index usage conditions and a warning when the optimizer may skip the index.

04

Missing Composite Index Column Ordering

What to watch: The prompt recommends a composite index but gets the column order wrong—placing a low-selectivity column first, or failing to align with the query's WHERE, JOIN, and ORDER BY clauses. The index exists but doesn't serve the query efficiently. Guardrail: Require the prompt to justify column order for every composite index by mapping each column to a specific clause in the target query. Include an index_column_rationale field that ties columns to predicates, joins, sorts, or covering requirements.

05

Hallucinating Index Types the Database Doesn't Support

What to watch: The prompt recommends a partial index, expression index, or index type (GIN, BRIN, columnstore) that the target database engine or version doesn't support, or recommends syntax that doesn't compile. Guardrail: Include the database engine and version as a required input field. Add a supported_index_types constraint list in the prompt harness. Validate generated DDL against the target engine's syntax before presenting recommendations.

06

Neglecting Existing Indexes and Duplication

What to watch: The prompt recommends a new index that duplicates or is a prefix subset of an existing index. The database ends up with redundant indexes that waste storage and write capacity without improving query performance. Guardrail: Require the existing index list as a mandatory input. Add a deduplication check in the prompt instructions: before proposing any new index, compare it against existing indexes and explain why it's not redundant. Flag prefix overlaps explicitly.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of the indexing strategy recommendation before shipping it to production or integrating it into a CI/CD pipeline for schema changes.

CriterionPass StandardFailure SignalTest Method

Index Justification

Every recommended index cites a specific query predicate, JOIN clause, or sort operation from [QUERY_PATTERNS].

Indexes are proposed without linking to a concrete query pattern, relying only on general column popularity.

Manual review of the recommendation against the provided [QUERY_PATTERNS] list.

Write-Amplification Risk

The output explicitly quantifies the write cost for each proposed index on high-throughput tables identified in [WRITE_PROFILES].

The recommendation suggests indexes on heavily written tables without mentioning INSERT/UPDATE overhead.

Check for a 'Write Impact' or 'Overhead' section in the output for tables with > [WRITE_THRESHOLD] ops/sec.

Over-Indexing Warning

The output identifies and warns against redundant indexes (e.g., a composite index that prefixes an existing single-column index).

The recommendation includes both a single-column index and a composite index with the same leading column without flagging the duplication.

Parse the output for a 'Redundancy Warning' or 'Existing Index Conflict' flag.

Migration Cost Estimate

Provides a rough cost estimate (e.g., 'Low', 'Medium', 'High') based on table size from [TABLE_SIZES] and index type.

Cost estimate is missing or is 'Low' for a multi-gigabyte table without justification.

Assert that the output contains a 'Migration Cost' field for each index and that the value correlates with [TABLE_SIZES].

Covering Index Logic

Recommends covering indexes only when explicitly needed for high-frequency, performance-critical queries from [QUERY_PATTERNS].

Defaults to suggesting covering indexes for all queries, ignoring the storage and write trade-offs.

Verify that the number of covering index suggestions is less than or equal to the number of queries tagged as [CRITICAL].

Output Schema Compliance

The output is a valid JSON array matching the [OUTPUT_SCHEMA] with no missing required fields.

The model returns a markdown list or a JSON object with keys that don't match the schema.

Automated schema validation check in the test harness using a JSON Schema validator.

Anti-Pattern Detection

Flags schema anti-patterns that block effective indexing, such as leading wildcards in [QUERY_PATTERNS] or indexing unselective columns.

Recommends an index on a boolean column or a column used with a leading wildcard without comment.

Scan the output for a 'Blocking Issue' or 'Anti-Pattern Warning' section.

Prioritization Logic

Indexes are sorted in a clear priority order (e.g., P1, P2, P3) based on query criticality and performance impact.

The list of indexes is unsorted or the priority seems random and doesn't correlate with [QUERY_PATTERNS] frequency.

Check that the output list is sorted by a 'Priority' field and that the top priority maps to the most frequent or slowest queries.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single representative query pattern and a simplified schema. Focus on getting a reasonable first recommendation without heavy validation. Replace [QUERY_PATTERNS] with 2-3 sample queries and [TABLE_SCHEMA] with a DDL snippet.

Watch for

  • Recommendations that ignore write volume entirely
  • Missing consideration of existing indexes
  • Overly generic advice not tied to the provided queries
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.