Evaluating text-to-SQL accuracy with promptfoo

promptfoo can run schema-aware test cases against a text-to-SQL feature, check generated queries and compare models on your own data. This page covers how to build that suite and where it needs human judgment.

On this page

Evaluating text-to-SQL accuracy with promptfoo: when your team needs it

If your team ships a natural-language query feature over its own database, you need a way to know whether a change breaks answers before customers find out. promptfoo publishes a text-to-SQL evaluation guide that compares models using automated test cases and schema validation, which is the approach this page follows. The core question is simple: when a generated query changes, does it still return the right rows, against the right tables, without touching anything it should not?

The risk shows up in three common situations. The first is a model swap, where a provider retires a model or a cheaper one looks attractive, and the new model writes different SQL for the same question. The second is a prompt edit, where a change meant to fix one class of question quietly alters how joins, date ranges or aliases are handled elsewhere. The third is a schema change, such as a renamed column or a new status code, which can leave generated queries valid in syntax but wrong in meaning. Without a fixed suite, each of these is discovered by users or by someone reading logs.

This page covers what to decide before building a suite: which schema facts the test cases must carry, how to check generated queries, how to compare candidate models on the same questions, and how to catch statements that should never run. Before you commit to a design, confirm with your database and security owners which read-only role the evaluation will use, and whether test data can come from a copy of production or must be synthetic. Those answers shape every section that follows.

Which grading approach fits which query risk

This table compares three ways to grade generated SQL: deterministic checks, execution against a test database and model-graded checks. Read each row against the query types your feature must answer, since the riskiest queries usually need the strongest check.

ApproachWhen it fitsCost and effortStability trade-off
Deterministic checksSyntax, required tables or columns, forbidden keywords such as DROP, UPDATE and DELETE, and single-statement rulesLow to run and easy to review in version control; the effort is maintaining the rule lists as the schema changesVery stable and repeatable, but a correct query written in an unexpected way can fail a string rule
Schema validationConfirming every table, column and join key the query uses exists in the schema you supplyLow per run; the schema snapshot must be refreshed when tables changeStable against the snapshot, but it cannot tell whether the joins express the question's intent
Execution against a test databaseAggregations, filters, joins and date logic where the result rows matter more than the SQL textHigher: needs a seeded, read-only copy of the data and a clean reset between runsStrong evidence of behavior, though results depend on the seed data and row ordering must be normalized
Model-graded checksBusiness intent that no string or result comparison captures, such as whether a query answers the question askedHighest per case because each judge call costs tokens and adds latency; the grader model must be chosen and budgetedLeast stable: judge output can drift between models and versions, so pin the grader and spot-check its verdicts
Unsafe statement checksAny feature that can send SQL to a live warehouse, where writes or privilege changes must never reach executionLow; a deterministic gate that runs before execution and before any model graderReliable for blocking known patterns, but parsing edge cases need a proper SQL parser, so confirm coverage against your dialect
Hybrid suitesMost production features: cheap checks gate every case and execution or judging runs on the subset that passesBalances cost and coverage; the main effort is deciding which query classes receive which checksKeeps runs cheap and stable, provided failing cases are reviewed so the gates do not hide real defects

Setting up a text-to-SQL eval suite

This sequence takes a team from a clean install of promptfoo to a repeatable comparison of models against schema-aware test cases with known correct results. Each step ends with a check so that a failing eval points to the model, not to a broken setup.

  1. Install promptfoo on a supported Node.js runtime

    The engineer installs promptfoo from npm on a machine or CI runner running Node.js 22.22.0 or newer, which is the version the current npm release requires. Run the installer, then confirm the CLI starts and reports its version. Record the Node.js and promptfoo versions in the repository so later runs can be reproduced. The step is done when a trivial config with a single echo provider runs end to end without errors.

  2. Describe the schema the model will see

    The data owner and an engineer write the schema description that the text-to-SQL feature passes to the model, covering tables, columns, types, keys, join paths and any business definitions that are not obvious from names. Pull the description from the same source the production feature uses, not from a hand-edited copy. The check is a diff between the schema text in the eval config and the schema text the production code sends, which should show no differences.

  3. Build a seed database that matches production shape

    Create a seed database with the same tables, column types and constraints as production, populated with synthetic or masked rows that include nulls, duplicates, edge dates and values that a join or filter could get wrong. Keep the data small enough to run quickly in CI. Confirm the seed database loads from a script and that the schema in the database matches the schema description from the previous step, since a mismatch would make the eval grade queries against a structure the model never saw.

  4. Write schema-aware test cases with expected results

    For each question, the team writes a natural-language prompt, the schema context it needs, and an expected result. The expected result can be a reference query whose output is compared against the output of the generated query on the seed database, or a set of expected rows. Cover simple selects, aggregations, joins, date handling and questions that should be refused or clarified. Label each case with the business question it represents. The check is that every reference query runs against the seed database and returns the expected rows when executed by hand.

  5. Configure a provider for each model under test

    The engineer adds one provider entry per model in the promptfoo configuration, with the same prompt template, schema context and output handling for all of them so the comparison is fair. Keys are read from environment variables or the CI secret store, never written into the config file. Promptfoo's documentation describes how each provider is named and configured. The check is a dry run that lists every provider and confirms each one returns a response to a single test prompt.

  6. Run the eval and record results

    The engineer runs the full suite with promptfoo eval against the seed database, so each generated query executes and its result is compared with the expected result. Store the output file or results view with the commit and model versions. The team should also confirm that the eval runs locally against the model endpoints without sending data to a third party beyond the chosen providers, as promptfoo runs on the machine that invokes it. The check is a complete run with a result recorded for every test case and provider.

  7. Review failures and sort the causes

    The team reviews each failing case and sorts it into a cause: wrong join, wrong filter, schema misunderstanding, invalid SQL syntax, or a flawed expected result. Fix test cases and schema text first when the expected result or context is wrong, then rerun. Model failures are recorded as evidence for model comparison. The check is that every failure has a written cause and that no case is left failing without a decision to fix the test or accept the model behavior.

Designing schema-aware test cases

Single-table filters are the baseline category: one table, a few predicates, and a clear projection. A good test asserts that the generated query references the correct table and columns, applies every filter the question implies, and returns the same rows as a reference query when run against a test database seeded with known data. Compare result sets rather than query text, because many valid SQL statements express the same filter.

  • Column confusion: models often pick a similarly named column, such as created_at instead of closed_at, so assert on the exact column names from your schema.
  • Dropped predicates: a question with two conditions may return a query that applies only one, so test each condition separately.
  • Wrong literal handling: enum values, casing and trailing whitespace in string filters frequently differ from the stored data.
  • Invented columns: check that every identifier in the output exists in the schema the model was given.
  • Missing limits: when the question asks for a single record, confirm the query does not return a full table.

Before relying on these tests, confirm with your database team which schema snapshot the prompt uses, since a stale snapshot produces false failures.

Catching unsafe statements before they reach the database

A text-to-SQL feature can produce statements that change data, read tables the user should not see, or return far more rows than the screen needs. Each risk gets an assertion in the eval suite that fails the build when the model produces the unsafe output. Every check here runs in the eval, so the database still needs read-only roles and query limits enforced at runtime.

Data-modifying statements

Add a check that fails any generated query whose first keyword is INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE or MERGE. A regex or JavaScript assertion is enough here, and it stays cheap enough to run on every test case. Include adversarial questions such as asking the model to clean up old rows, so the suite shows whether the model complies. An eval only reports the unsafe output; the database role must refuse the write. Confirm that the application connects with a role that has SELECT privileges only.

Tables outside the user's permissions

Give each test case the set of tables that the asking user is allowed to query, then assert that every table referenced in the generated SQL belongs to that set. A JavaScript assertion can parse the FROM and JOIN clauses against an allow list for the test's role. Cases where a question names a sensitive table directly, such as salary or patient records, show whether the model refuses or routes around the restriction. Permission checks still belong in the database and the application's authorization layer.

Unbounded result sets

Flag queries that have no LIMIT clause or aggregate, or whose limit exceeds the ceiling your product allows. Use a JavaScript assertion that checks for a LIMIT below the agreed maximum on list-style questions, and skip it for questions that expect a single aggregated value. This catches a common failure where a correct query still overloads the database or the interface. Ask your data platform team which maximum row count they will accept, and enforce it with a statement timeout and row cap in the database.

Prompt injection through the question

Users can write questions that try to override the instructions, such as asking the model to ignore its rules or to output an extra statement after the query. Build cases with injected instructions and assert that the output contains one SELECT statement and nothing after it, using a semicolon count or a parser. Add a model-graded check when the injection changes the meaning of the query. Keep the database role read-only, because a model that follows an injected instruction can only do what the connection permits.

How a text-to-SQL eval run flows

A run starts with a test case that pairs a natural-language question with the schema it targets. promptfoo sends that prompt to each model provider under comparison, and each generated SQL statement comes back to the runner. The checks then run in order: schema validation, forbidden statements, and optional execution against a test database. Each model gets a pass or fail result per test, so the report shows where the models differ. Check that the test database is a copy with no production data.

The path a text-to-SQL test takes from question to pass or fail result.

Security and data handling for the eval environment

An eval suite for text-to-SQL touches live model credentials, database schemas and generated queries, so where it runs and where its results land matter as much as the test cases. The cards below cover local execution, secret handling, database isolation, server limits and the separation from production that keeps the eval environment from becoming a new risk.

Local execution and model traffic

promptfoo's documentation states that evals run on your machine and talk directly with the LLM. For text-to-SQL, that means schema descriptions and sample questions leave your machine only when sent to the model provider you configured. Confirm which provider endpoints the runner can reach, and whether your data policy allows schema details to be sent to each one.

promptfoo introduction

Where API keys live

Model provider keys are usually read from environment variables or a secrets store on the machine or CI runner that executes the eval. Keep them out of the promptfooconfig.yaml file and out of committed test data. Treat every runner as a place where keys exist, and scope each key to the eval project with spending limits set by the provider.

Schema details and test data

Schema definitions, table names and sample rows are part of the eval input and may be sensitive even when no customer data is present. Store the schema as a reviewed file with the test cases, and decide which columns are described to the model at all. Illustrative example: a column named patient_dob may be enough context to expose a sensitive field design.

Isolated test databases

Run generated SQL against a disposable database that holds synthetic or masked rows, never a read replica of production. Give the eval account read-only grants and a separate schema so an unsafe DELETE or DROP cannot reach real data. Ask whether the test database is rebuilt before each run so results stay reproducible.

Self-hosted server limits

The self-hosted promptfoo app stores data in a local SQLite database that cannot be shared across replicas. It has no RBAC, horizontal scaling, built-in authentication or SSO, and promptfoo's documentation does not recommend it for production use. Use it for a single trusted team, and put access controls in front of it if it is reachable from a network.

Self-hosting docs

Keeping eval data apart from production

Keep the eval database, eval results and runner credentials in a separate environment from production systems and their secrets. Do not reuse production API keys or database users for evals, and check that eval reports, which may contain schema details and sample queries, are stored with the same care as other internal test records. Confirm this separation in writing before the first run.

Comparing models on your own schema

Run one promptfoo suite across every candidate model so that the comparison measures the model, not the setup. Each provider entry in the configuration should receive the same natural-language questions, the same system prompt, the same schema description and the same assertions. If one model gets a richer schema excerpt or a prompt tuned during earlier experiments, its pass rate tells you about the prompt rather than the model. Keep the schema context in a shared file, and record the provider identifiers and model versions alongside the results so that a later rerun can be traced to exactly what was tested. Confirm in the promptfoo text-to-SQL guide which provider settings and test case formats it recommends for this comparison before you copy them into your own configuration.

Read the output as a set of failure categories, not one headline number. A single pass rate hides whether a model fails on joins, aggregations, date arithmetic, filters on nullable columns or queries that touch tables outside the allowed schema. In illustrative terms, a model might score highest overall while failing most of the aggregation cases, which matters if your product answers financial reporting questions. Tag each test case with its category, then compare models category by category in the results view. Pick the model that is strongest on the categories your users actually ask for, and treat a low score on a high-risk category as a blocker even when the overall average looks good.

Expect that no model will lead every category, and plan the decision around that. A model that wins on simple single-table lookups may lose on multi-table joins, and the reverse can also be true. Before choosing, review the individual failed queries for each contender, not only the grades, because a query can pass a schema check and still return the wrong rows. Ask your data owners to validate a sample of the passing queries against known answers. Record the category results and the reviewer's notes together, so the choice can be defended to security and governance reviewers and repeated when a model version changes.

Questions teams ask before building a text-to-SQL eval suite

What makes a text-to-SQL eval suite take more or less effort to build?

The main drivers are the number of schemas, the variety of query categories, and whether the suite must execute generated SQL against a database or only check it statically. One schema with simple aggregations is a small job. Many schemas with joins, window functions, date logic and business-specific definitions multiply the number of test cases and the review time for each failure. Execution checks add a requirement for a database that behaves like production. Ask any partner to list each schema, each query category and whether results are compared by value, so the quote follows from a defined scope.

Can our internal team build a text-to-SQL eval suite with promptfoo themselves?

Yes. promptfoo is licensed under the MIT license, and its Community edition is free and includes all LLM evaluation features and all model providers and integrations. A team that already knows its schemas and SQL dialect can write test cases, schema checks and model comparisons without a license purchase. The effort then sits with your own engineers and data owners. Teams that lack spare capacity or have no one who knows the schemas well often hire a partner for the first build and then maintain the suite in-house.

What does our organization need to provide for the work?

Expect to supply four things. First, schema documentation that explains tables, keys, column meanings, units and the business rules behind them. Second, a representative test database with realistic volumes and edge cases, or an anonymized copy that keeps the same structure. Third, a set of sample questions written by the people who will use the feature. Fourth, named owners who review failures and decide whether a generated query or the expected answer is wrong. Without these owners, failing tests pile up and nobody trusts the suite.

How long does a text-to-SQL eval suite take to build?

Duration depends on scope, so no fixed figure applies. The schedule is shaped by the number of schemas, the number of query categories, the availability of schema documentation and the speed at which your reviewers can label expected answers. Delays usually come from missing documentation and slow review, not from writing the configuration. DeployOpen agrees scope, deliverables and timelines in writing before work starts, and you should ask for the same from any provider.

Should the eval run generated SQL against a real database?

It depends on the risk you are testing. Static checks, such as parsing the query, confirming that referenced tables and columns exist in the schema and blocking statements other than SELECT, are fast and need no database. Execution checks compare the returned rows with expected rows, which catches wrong joins and wrong filters that static checks miss. Run execution against a copy with read-only credentials and no production data, and confirm that the sandbox cannot reach systems it should not touch.

How do we catch unsafe statements such as DELETE or DROP in generated SQL?

Add tests that send prompts designed to produce destructive or out-of-scope statements, then check that the output contains only permitted statement types. A deterministic check on the statement type is cheaper and more stable than asking a model to judge safety. Keep the database account used by the feature read-only as well, so a test failure is not the only protection. Confirm these controls with your security team, since the database privileges and the application's own filters are your responsibility.

Which operational tasks continue after the first suite is in place?

Schemas change, new query categories appear and model versions are replaced, so the suite needs upkeep. Plan for a regular review of failing cases, updates to expected answers when the business definition changes, and a rerun whenever you switch models or change prompts. Decide who owns each step and where results are stored. Ongoing support and continuous testing can be contracted as a retainer if your team prefers not to carry that work alone.

How DeployOpen works on this

DeployOpen plans and builds the promptfoo evaluation setup for your text-to-SQL feature inside your own infrastructure, so schema-aware tests, query checks and unsafe-statement tests run where your data and models already live. Engagements are fixed-scope, with the schema, deliverables and timeline agreed in writing before work starts.

How we scope

  • Inventory the databases, schemas and query roles the text-to-SQL feature can reach, and confirm which are production and which are safe to copy
  • Agree which models and providers are compared, and whether they are hosted or self-hosted in your environment
  • Define the unsafe statement categories to test, such as writes, schema changes and cross-tenant reads, and who approves them
  • Put the scope, deliverables, environment and timeline in writing before any build work starts

How we build

  • Build the promptfoo configuration with schema-aware test cases drawn from question sets your analysts and product owners supply
  • Connect promptfoo to your models and database test copies with credentials held in your secrets store, not in config files
  • Add deterministic checks for generated SQL, such as parse validity and forbidden keywords, and result comparison against reference queries
  • Test the suite against known good and known bad queries so you can confirm it catches the failures you care about

How we hand over

  • Deliver the promptfoo configuration, test data, grading rules and run instructions in a repository your team controls
  • Document how each assertion works, what it checks, and where its limits are, so reviewers can challenge results
  • Walk your engineers through running the suite locally and in your pipeline, and reviewing pass and fail reports
  • Record the model versions, promptfoo version and test dataset version used for each baseline run

How we support

  • Update test cases when schemas change, and add tests for new unsafe patterns found in your own review
  • Plan promptfoo upgrades and rerun baselines after each upgrade, so score changes are not mistaken for model changes
  • Offer ongoing support and continuous testing as a retainer if you want the suite maintained after handover
  • Confirm with your team which self-hosted promptfoo option fits your scale before expanding beyond local runs

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.