Sixty Mind
Back to Articles
AI GuidesIntermediate

Prompt Patterns That Help AI Generate More Reliable SQL Queries

A request for “overdue invoices by customer” can look simple until an AI assistant returns a polished query.

Reading Time
8 min read
Published
11 Oct 2026
Total Views
4
Prompt Patterns That Help AI Generate More Reliable SQL Queries

A request for “overdue invoices by customer” can look simple until an AI assistant returns a polished query. Which invoice state counts as overdue? Should the date follow the report’s local timezone? Are credit notes excluded? Does the reader need a list of invoices, a customer total, or a weekly collection queue? A query can run without errors and still answer the wrong business question.

Reliable AI-generated SQL begins before the first SELECT statement. Give the assistant a clear question, verified schema facts, the target database dialect, a safe operating limit, and a check that a person can perform. Those details form a prompt contract. The contract tells the assistant what it may use, what it must not assume, and where uncertainty belongs.

This article uses an internal overdue-invoice report as an example. A finance analyst needs a weekly list of approved invoices that remain unpaid after their due date. The analyst wants the account name, invoice number, due date, remaining balance, and age in days. The report must not include disputed invoices, private payment notes, or records outside the analyst’s authorised region.

Begin with the decision, not the SQL request

A vague request leaves business definitions for the model to infer. A dependable prompt states the action the reader will take after seeing the result. In the invoice example, the decision is not “write a query”. The decision is “prepare a call list for invoices that require a collection follow-up this week”. That purpose determines the output columns, exclusion rules, sorting, and date logic.

Write the question in ordinary language first. Then add the expected result shape. A useful request can state: “Return one row per open invoice, ordered by the oldest due date. Show the account name, invoice number, due date, balance, and overdue days. Exclude disputed invoices and balances of zero.” This is easier to inspect than a broad request for an ageing report.

Ask the assistant to restate the decision before it proposes SQL. If the restatement changes “one row per invoice” into “one row per customer”, stop there. The problem is not a missing database function. The question needs correction. This small pause prevents a fluent draft from becoming the definition of the work.

A reliable prompt should also state what the assistant must leave open. The analyst might know that a balance below zero represents a credit, but not know whether credits should appear in the call list. Direct the assistant to mark that point as unresolved. Do not choose an interpretation. A visible question is safer than an invisible guess.

Give the assistant only verified schema facts

An AI tool can invent a plausible table or column name because databases often use familiar words such as customer, status, or amount. Plausibility does not prove that the field exists or means what the query assumes. Supply a small, current schema packet from an approved source instead.

For the invoice report, the packet could identify invoice, account, and region_access as the only relevant tables. It can state that invoice.due_on stores the due date and invoice.amount_open stores the remaining balance. The invoice state field accepts four values: approved, paid, disputed, and void. It can also state that account.region_id joins to the authorised regions for the current analyst.

Keep the packet brief and sanitised. A data dictionary entry, a tested view definition, or a field list is usually enough. Do not paste a production export, a connection string, a payment note, or a complete table dump into the prompt. Replace account names and identifiers with stable examples where the exact value has no bearing on the query design.

AWS describes text-to-SQL as a process that maps natural-language intent to database structure. Its guidance highlights clear instructions, schema detail, and examples as useful context for accurate output. [1] In practice, that means the assistant should use only the supplied fields and should label every missing join rule or status definition as an open question.

Ask for an evidence list before SQL. Ask the assistant to name the table behind each output field, join, filter, and assumption. A reviewer can then compare that list against the schema packet. That record exposes an incorrect relationship before anyone runs the query.

Name the dialect and the operating boundary

SQL is not one identical language. Date arithmetic, quoted identifiers, common table expressions, window functions, pagination, and NULL handling can differ across PostgreSQL, MySQL, SQL Server, SQLite, Snowflake, and BigQuery. Name the target dialect and version if it matters. State whether the assistant should create a SELECT statement, a parameterised application query, a migration, or an explanation only.

The invoice analyst may request read-only PostgreSQL SQL that runs through an approved reporting view. The prompt can prohibit INSERT, UPDATE, DELETE, data-definition statements, temporary tables, and vendor-specific functions that are not available in the team’s environment. These limits reduce the chance that a draft becomes an unexpected operational action.

The boundary also includes access. Do not ask an AI assistant to solve a reporting question by widening the reporting account’s permissions. The query should operate through an approved view or a database account that already has the correct limited scope. OWASP lists prepared statements with parameterised queries, allow-list validation, and least privilege among its SQL-injection defences. [2]

For an application query, keep values as parameters. Never join external input to a SQL string. For a report query, list each filter and its expected data type.

Specify the source of every time rule. CURRENT_DATE may be acceptable for a local operational report, but a finance report may use a fixed business date or an accounting calendar. State the intended timezone, the date field, and the rule for records due on the boundary date. A prompt that says “overdue this week” is incomplete until those choices are named.

Do the same for totals and missing values. State whether the report should use an invoice balance, the original amount, or a converted currency amount. State whether a missing date, NULL balance, or credit balance should be excluded, reported separately, or stop the query for review. These instructions prevent the assistant from filling a gap with a convenient but unsuitable default. A named parameter is not merely a syntax preference; it makes the boundary between SQL code and input easier to review.

Request an explanation before the final query

A single code block hides too much. Request the reasoning artefacts that a reviewer needs first. Request a plain-language plan that covers row grain, joins, filter order, aggregation, and assumptions. Then ask for the candidate SQL in a separate section.

The row grain deserves special attention. “One row per invoice” differs from “one row per account”. A join to payment activity can turn one invoice into several rows if the payment table contains partial payments. A reviewer should see that risk in the explanation, not discover it after a customer receives an incorrect collection message.

For the invoice report, an effective prompt can require the assistant to answer these questions before SQL: Which table is the source of the balance? Which state values are excluded? Does the query return invoices or customers? How is overdue age calculated? Which condition limits the rows to authorised regions? What happens when due_on is missing?

The assistant can then draft the query. A reviewer should check the names, joins, filters, and date expression against the approved packet. If a query uses an unexpected table, an invented field, or a vague expression such as “current overdue invoices”, return it for revision. Do not repair the query silently, because the next prompt will repeat the same missing context.

Test the business rule and the SQL syntax

A parser can confirm that SQL is valid. It cannot confirm that the query supports the intended decision. Test a small set of cases that challenge the stated business rule. For the invoice report, create controlled examples for an invoice due today, an invoice paid yesterday, and an approved invoice with a zero balance. Add a disputed invoice with money outstanding and an invoice from a region outside the analyst’s scope.

Write the expected result beside each case before executing the query. The expected report should include the overdue approved invoice and exclude the other examples. If the query returns a disputed invoice or hides an old unpaid invoice, investigate the rule, the schema facts, or the SQL. Do not ask the assistant to “make it work” without showing the failed case.

OpenSSF advises teams to treat AI-generated code as subject to normal review, testing, and engineering controls. [3] For SQL, that means retaining source control, peer review, approved environments, and a clear record of why a query changed. The assistant can speed up a draft, but it does not own the risk of a bad report, a slow query, or an unauthorised data result.

Run the query through a controlled evidence gate

Move from draft to execution in stages. First, review the prompt contract and schema packet. Next, inspect the query explanation and candidate SQL. Then run the query against safe sample data or an approved read-only environment. Compare the result to the written cases. Finally, record who reviewed the query and where the approved version lives.

Where the database supports it, review the execution plan before using a new query against a large reporting table. An accurate query can still create an unnecessary operational burden if it scans an unexpected volume of data or misses an existing approved view. The goal is not to turn every analyst into a database administrator. This step exposes performance risk before the query becomes routine. Record the expected row count and target run duration. Pause the rollout if either measure changes, then ask the database owner to review the execution plan. Record the decision for later review.

Keep a compact record for each useful prompt contract: the business question, schema packet version, target dialect, allowed operation, key assumptions, test cases, query location, and reviewer. This record lets a colleague recreate the report and identify the confirmed rule and source prompt.

Build a library of prompt contracts

The strongest SQL prompts are often the ones a team has already tested. Keep a small library for recurring jobs such as overdue balances, stock exceptions, weekly service levels, or access reviews. Each entry should include the verified schema source, the output rule, the dialect, the safe operating boundary, and the checks that caught earlier mistakes.

Do not collect finished queries without their context. A copied query can become dangerous after a status value changes, a view is replaced, or a reporting account receives a new scope. A prompt contract preserves the reason behind the SQL. That context makes future review quicker and more reliable.

AI can help people work through repetitive SQL drafting. It cannot decide what an overdue invoice means, which records a colleague may see, or whether a result is ready to guide a business action. Clear context, a controlled boundary, and a named reviewer turn a plausible SQL draft into evidence that a team can trust.

References

  1. AWS, Generating value from enterprise data: Best practices for Text2SQL and generative AI
  2. OWASP, SQL Injection Prevention Cheat Sheet
  3. OpenSSF, Security-Focused Guide for AI Code Assistant Instructions

Tagged Topics

Want to keep learning AI?

Explore AI courses, tool guides, and news explainers designed for practical learning and immediate application.