Natural language to SQL can make analytics more accessible, but a fluent-looking query is not automatically correct, efficient, or safe. This checklist provides reusable SQL prompt templates, a schema-context checklist, and a controlled workflow for generating, validating, testing, and approving LLM-generated queries before they reach a database.
Overview
An LLM can translate a question such as “Which product categories grew fastest last quarter?” into a first SQL draft. The difficult part is not producing keywords such as SELECT, JOIN, and GROUP BY. It is resolving ambiguity: which date column defines a quarter, whether revenue means gross or net revenue, how returns are handled, and which table contains the authoritative product category.
Use LLM SQL generation as a reviewed application workflow rather than a direct database shortcut. The model should receive only the schema context it needs, produce a structured response, and work through a read-only validation layer. A human or approved business rule should remain responsible for interpreting unclear requirements and approving queries that access sensitive or operational data.
A dependable text-to-SQL workflow has six stages:
- Clarify the user’s question and expected output.
- Retrieve relevant tables, columns, relationships, and business definitions.
- Generate SQL for one explicitly selected dialect.
- Validate syntax and database permissions without executing writes.
- Review joins, filters, aggregations, and sample results.
- Require approval before production execution or scheduled use.
For broader prompt design practices, see the prompt engineering workflow. If the feature will run as part of an application, pair this process with an LLM application release checklist.
Checklist by scenario
Before writing the SQL prompt
- Identify the dialect: PostgreSQL, MySQL, SQL Server, Snowflake, BigQuery, and other systems differ in date functions, quoting, pagination, casting, and identifier rules.
- Define the permitted scope: list approved schemas, tables, columns, row limits, and whether views are preferred over raw tables.
- Describe relationships: provide primary keys, foreign keys, join paths, and known many-to-many relationships.
- Explain business terms: define “active customer,” “completed order,” “revenue,” “churn,” and other terms that cannot be inferred reliably from column names.
- State the output contract: request SQL, a short assumption list, referenced tables, and a confidence or ambiguity flag rather than unrestricted prose.
Reusable system prompt template
You generate read-only SQL for the specified database dialect.
Rules:
- Use only the tables and columns supplied in the schema context.
- Never generate INSERT, UPDATE, DELETE, MERGE, DROP, ALTER, CREATE, GRANT, or transaction-control statements.
- Do not guess missing relationships or business definitions.
- Ask a clarification question when the request is ambiguous.
- Include a bounded result set unless the user explicitly requests an aggregate.
- Return valid JSON with: sql, assumptions, tables_used, risks, needs_clarification.
Dialect: {{SQL_DIALECT}}
Schema context:
{{RELEVANT_SCHEMA}}
Business definitions:
{{METRIC_DEFINITIONS}}
PostgreSQL and MySQL-style requests
For systems with familiar relational syntax, explicitly define identifier quoting and date behavior. Tell the model whether timestamps are stored in UTC, which time zone reports should use, and whether case-sensitive identifiers are present. Ask for parameter placeholders instead of interpolated user values.
User request: {{QUESTION}}
Required output:
1. One read-only {{SQL_DIALECT}} query.
2. Named parameters such as :start_date and :end_date.
3. A list of joins and the reason for each join.
4. Any assumption that could change the result.
5. A suggested LIMIT when the result is row-level.
BigQuery, Snowflake, or warehouse requests
Warehouse queries require additional cost and scan awareness. Include project, dataset, database, schema, partitioning, clustering, and approved table or view information where applicable. Ask the model to filter partition columns when the question includes a time range and to avoid selecting unused columns.
Warehouse requirements:
- Use only approved datasets and views.
- Select named columns; do not use SELECT *.
- Apply the partition or date filter when available.
- State the expected grain of the result.
- Flag joins that may multiply rows.
- Return an estimated review note, not an invented cost estimate.
Dashboard or analyst workflow
For an interactive analytics tool, display the generated SQL before execution. Show the assumptions, tables used, and a plain-language summary of the query. Let the user edit the question or choose among approved metrics. A SQL formatter or validator can improve readability, but formatting does not prove semantic correctness; the SQL and data formatting reference is useful for this cleanup step.
What to double-check
Use this review checklist for every generated query:
- Grain: Is the result one row per customer, order, day, or category? Does that match the question?
- Joins: Can any join duplicate facts? Confirm cardinality and use pre-aggregation when necessary.
- Filters: Check inclusive and exclusive date boundaries, null handling, status values, soft deletes, and test records.
- Metrics: Verify whether the query uses
COUNT(*),COUNT(DISTINCT ...), a sum of line items, or a precomputed metric. - Time zones: Confirm how timestamps are converted and whether the reporting period is calendar-based or business-defined.
- Dialect syntax: Run a parser or database-native dry run against a read-only connection.
- Permissions: Enforce access through database roles and application controls, not through prompt instructions alone.
- Result quality: Compare a small result with a known report, hand-written query, or test fixture.
- Privacy: Avoid exposing unnecessary personal or confidential columns in the schema context and output.
Keep generated SQL, the prompt version, schema snapshot, validation result, and approval decision together for debugging. Do not log sensitive values merely to make a failed query easier to inspect. The AI data privacy checklist covers practical controls for PII, retention, and logging.
Common mistakes
- Sending the entire database schema: Excess context can increase confusion and expose data that the task does not require. Retrieve only relevant schema fragments.
- Assuming column names explain meaning: A field called
revenuemay exclude tax, refunds, or discounts. Provide definitions explicitly. - Allowing unrestricted execution: A prompt that says “write safe SQL” is not a substitute for read-only credentials, statement inspection, timeouts, and resource limits.
- Ignoring empty results: No rows may indicate an incorrect status value, date boundary, join, or tenant filter rather than a legitimate business outcome.
- Testing only happy paths: Include ambiguous questions, missing dates, null values, duplicate relationships, and requests for unauthorized tables in evaluation cases.
- Changing models without regression tests: A new model or provider can alter formatting, assumptions, tool calls, and SQL style. Preserve a representative test set before migration; the provider migration checklist can help organize that review.
- Confusing readable SQL with correct SQL: Formatting and fluent explanations can hide an incorrect join or metric definition.
For production systems, separate query generation from execution. An application can ask the model for a structured query proposal, validate the proposal with deterministic code, and pass only approved statements to a restricted database service. This tool boundary is also relevant when designing agent actions; see the AI agent tool design checklist.
When to revisit
Review the prompt, schema retrieval logic, and evaluation set whenever the underlying inputs change. A practical schedule is to revisit the workflow before seasonal planning or reporting cycles, after a major model or provider change, and whenever a database migration adds, removes, or renames tables and columns.
Also trigger a review when a new dashboard or metric is introduced, a query produces a regression, users report inconsistent answers, permissions change, or execution time increases. Add the failure to a test case instead of fixing only the individual prompt. Useful evaluation dimensions include SQL validity, correct table selection, metric accuracy, refusal behavior, latency, and safe handling of ambiguous requests. The reusable LLM evaluation guide provides a framework for turning these checks into a repeatable test suite.
Before your next release, run this short action list:
- Refresh the schema and business-definition context.
- Confirm the selected SQL dialect and read-only database role.
- Run representative and adversarial natural-language questions.
- Inspect joins, date filters, metric definitions, and result grain.
- Compare outputs with approved reference queries.
- Record prompt, model, schema, validation, and approval versions.
- Monitor failures after release and feed confirmed cases back into evaluation.
Used this way, natural language to SQL becomes a governed AI development feature: useful for accelerating query drafts while keeping correctness, access control, and human judgment in the workflow.