Text-to-SQL With an LLM in Python: Build It, and What 1,000 Questions Cost on Six Models

Text-to-SQL takes a plain-language question plus the database schema and produces a SQL statement that the database then runs, as the SQLBench authors define it. Built as a tool, it is one model call wrapped in a schema prompt, a guard, a read-only run and an eval, and 1,000 questions cost about 28 cents ($0.275) on Claude Haiku 5.5 or GPT-6 Luna against $5.50 on Claude Sonnet 5.5 or gpt-6.1-sol. That assumes a 2,000-token prompt and a 150-token answer, at rates from Anthropic’s and OpenAI’s pricing pages and OpenAI’s GPT-6 Luna model page, as checked on November 13, 2026.

The build below is 13 steps, in a few hundred lines of Python written for a current Python 3 release against a SQLite shop database. The model decision comes before the code, because it sets the line you put in .env and what every eval run costs.

Google · Preferred Sources

Don't miss new tech stories on Google

Add Tech Insider once in the Google app and our stories appear in your news suggestions.

Add Now

One model call among five pieces: what the benchmarks grade and what they leave to you

A text-to-SQL system is a pipeline, not a prompt. The model writes the query; four other pieces decide whether that query is useful and safe.

question
   |
   v
[1] schema context  (DDL + sample rows + business rules)
   |
   v
[2] LLM generates one SELECT
   |
   v
[3] guard: parse, allow-list tables, force LIMIT
   |
   v
[4] execute on a read-only connection with a timeout
   |
   +--> error? feed the message back to [2], retry up to twice
   |
   v
[5] rows returned, logged, and scored by an eval script

The schema context does most of the work: a model cannot know that unit_price_cents is the revenue column, or that refunded orders should not count, unless you say so once in the system prompt. The guard parses the SQL into a syntax tree and rejects anything that is not a single SELECT on known tables. The read-only connection backs it up, so a flaw in the guard still cannot write data. The eval script tells you whether a later change to the prompt or the model helped. The point of the exercise, as the ACM survey of LLM-based text-to-SQL puts it, is that writing SQL takes specialized knowledge, which keeps non-experts away from their own data.

The published accuracy numbers come from the SQLBench paper. Before LLMs, the best traditional methods reached 79.9% on Spider, which the authors called “still far from being a reliable Text-to-SQL parser”. Prompted LLM methods then raised it: C3 reached 82.3%, DIN-SQL 85.3% and DAIL-SQL 86.6%, the last stated as execution accuracy on the Spider leaderboard. Execution accuracy (EX) counts a query as right when its result matches the gold result, and it is the grading the eval script in step 11 copies. The same paper calls BIRD the first benchmark built to test how efficiently SQL executes on large databases; check the live BIRD and Spider pages before quoting a current standing.

None of those scores measures your schema. A text-to-SQL survey notes that models trained on one domain may not generalize to another, and that LLM systems struggle with queries that use nested sub-queries, multi-table joins or window functions. SQLBench’s authors add that there is still no consensus on the best prompt templates. A 2026 ACL Anthology paper on text-to-SQL over OMOP clinical data shows what a narrow domain gets: its dataset holds 6,690 paraphrases from 75 OMOP-adapted templates, with splits built to resist template and SQL leakage. So the prompt choices in steps 4 and 9 are informed starting points, and the golden set in step 11 is where you find out whether they hold on your data.

Priced per question: a 2,000-token schema and 150 tokens of SQL on six models, cached and batched

Anthropic’s pricing page also lists Claude Fable 5.2 at $8 input and $40 output per million tokens, above Opus 5.5, plus Mythos 5.2 and other additional models, as checked on November 13, 2026. This build prices the three 5.5 tiers, Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5, and Anthropic introduced Claude Haiku 5.5 on October 7, 2026. OpenAI’s pricing page lists gpt-6-astra, gpt-6.1-sol, gpt-6.1-terra and gpt-6-luna, the last at $0.10 input and $0.50 output, the same as Haiku 5.5, as checked on November 13, 2026. This build prices Sol, Terra and Luna, and OpenAI’s GPT-6 Luna model page gives the same Luna rates. The rates below are per million tokens, as read on November 13, 2026.

ModelMakerInputOutputCached input read
Claude Opus 5.5Anthropic$4.00$20.00$0.20
Claude Sonnet 5.5Anthropic$2.00$10.00$0.10
Claude Haiku 5.5 (prompts up to 100,000 tokens)Anthropic$0.10$0.50$0.01
gpt-6.1-solOpenAI$2.00$10.00$0.10
gpt-6.1-terraOpenAI$1.00$5.00$0.05
GPT-6 LunaOpenAI$0.10$0.50$0.01

Above 100,000 tokens, Haiku 5.5 moves to $0.50 input and $2.50 output per million, five times its base rates, which matters only if you push a very large schema into every call. Cost per question is 2,000 times the input rate plus 150 times the output rate, divided by one million. For Haiku 5.5 that is 2,000 × $0.10 / 1,000,000 = $0.0002 for the prompt and 150 × $0.50 / 1,000,000 = $0.000075 for the answer, $0.000275 in all; GPT-6 Luna has the same two rates and so the same cost. The cached column swaps the input rate for the cached-read rate and assumes the whole prompt is a cache hit, which is the best case.

ModelPer questionPer 1,000Per 1,000, schema cachedPer 30,000Per 30,000, schema cached
Claude Haiku 5.5$0.000275$0.275$0.095$8.25$2.85
GPT-6 Luna$0.000275$0.275$0.095$8.25$2.85
gpt-6.1-terra$0.00275$2.75$0.85$82.50$25.50
gpt-6.1-sol$0.0055$5.50$1.70$165.00$51.00
Claude Sonnet 5.5$0.0055$5.50$1.70$165.00$51.00
Claude Opus 5.5$0.011$11.00$3.40$330.00$102.00

Two patterns stand out. Every model here prices output at five times input, so the 2,000 input tokens make up 73% of each question’s cost, and shrinking or caching the schema moves the bill more than trimming the answer. Caching cuts the per-question cost by between 65% and 69%, while the tier you pick moves it 40-fold: Opus 5.5 at $11.00 per 1,000 against Haiku 5.5 at $0.275.

Anthropic’s pricing page lists a Batch API for asynchronous processing that takes 50% off the input and output rates. That brings 1,000 questions to $0.1375 on Haiku 5.5, $2.75 on Sonnet 5.5 and $5.50 on Opus 5.5, which suits an overnight eval with nobody waiting but not an interactive question. Anthropic also lists a cache write rate of $2.50 per million for Sonnet 5.5, above its $2.00 fresh rate, so the call that writes the cache costs slightly more than an uncached one. For a cost ledger on another model family’s API, see the Gemini Omni Flash API cost ledger.

Retries and schema size move the figures in a different way. The loop in step 9 allows up to three model calls per question, so a question that fails twice costs up to three times the single-call price: $0.825 per 1,000 on Haiku 5.5 and $16.50 on Sonnet 5.5, a little more in practice because each retry resends the earlier reply and the error. A 10,000-token schema raises the single-call figure to $1.075 per 1,000 on Haiku 5.5 and $21.50 on Sonnet 5.5. The eight-question eval from step 11 costs 8 × $0.0055 = $0.044 on Sonnet 5.5 before retries.

Reading the tiers against the jobs: for high volume and simple questions, Haiku 5.5 and GPT-6 Luna tie as the cheapest rows, and Anthropic positions Haiku 5.5 for high-volume, latency-sensitive tasks such as classification, extraction and routing; gpt-6.1-terra costs ten times as much per question ($0.00275 against $0.000275). For a default tier, Claude Sonnet 5.5 and gpt-6.1-sol cost exactly the same here, $0.0055 per question, so the golden-set score decides between them; Anthropic describes Sonnet 5.5 as “the best combination of speed and intelligence”. Opus 5.5 costs twice Sonnet’s price, and it is worth trying only on large or tangled schemas after routing (step 13) has failed to close the gap. Price and accuracy do not move together evenly, so check one benchmark: on the BIRD Mini Dev leaderboard dated Oct 28, 2026, as checked on November 13, 2026, overall execution accuracy is 87.27 for gpt-6.1-sol and 84.20 for Sonnet 5.5, which cost $5.50 per 1,000 questions here, against 57.80 for Haiku 5.5 and 52.27 for GPT-6 Luna at $0.275, a 20-fold price gap. One benchmark is not your schema, so the pick stays a hypothesis until step 12 scores it on your questions.

Copy the model ID from your console’s model list when you fill in .env in step 2. Anthropic’s API release notes name Haiku 5.5 as claude-haiku-5-5, and OpenAI’s model page documents gpt-6.1-terra as the ID for Terra; confirm both in your console before you rely on them, and do the same lookup for any other model you target.

Steps 1 to 5: environment, shop database and a CREATE TABLE schema prompt

RequirementVersionWhy you need it
PythonA current Python 3 releaseRuns every script.
SQLiteStandard-library sqlite3 moduleThe sample database. No server needed.
sqlglotLatest release from PyPIParses SQL into a syntax tree for the guard.
anthropicLatest release from PyPIOfficial SDK for Claude models. Skip it if you only use OpenAI.
openaiLatest release from PyPIOfficial SDK for OpenAI models. Skip it if you only use Claude.
python-dotenvLatest release from PyPILoads the provider, model ID and key from a .env file.
API keyOne provider is enoughAnthropic or OpenAI, or any server with an OpenAI-compatible endpoint.
Cost$0.044 for the eight-question eval on Sonnet 5.5, before retriesArithmetic in the cost section above.

The requirements file stays unpinned so the tutorial does not date. In a team repo, commit pip freeze output beside it.

Step 1: Create the project folder and virtual environment

mkdir sqlask && cd sqlask
python3 -m venv .venv
source .venv/bin/activate
python --version

On Windows PowerShell, use py -m venv .venv and then .venv\Scripts\Activate.ps1 instead of the second and third lines. The last command should print a Python 3 version.

Step 2: Install dependencies and set your API key

# requirements.txt
anthropic
openai
sqlglot
python-dotenv
pip install -r requirements.txt
echo .env >> .gitignore

Create .env next to the scripts with the provider, the model ID from your console and the key. Use one block only.

# .env for Claude
LLM_PROVIDER=anthropic
LLM_MODEL=claude-haiku-5-5
ANTHROPIC_API_KEY=your-key-here

# .env for OpenAI: use instead of the block above
# LLM_PROVIDER=openai
# LLM_MODEL=gpt-6.1-terra
# OPENAI_API_KEY=your-key-here

The .gitignore line matters: a leaked key costs real money.

Step 3: Build the sample shop database

The data needs traps in it. The script creates customers, products, orders and order_items with 200 customers, 40 products, 1,500 orders and one to four line items per order. Customers 181 to 200 never order, so a never-ordered question has an answer, and four order statuses (completed, refunded, cancelled, pending) mean revenue questions need a rule. Save it as make_db.py.

import random
import sqlite3
from datetime import date, timedelta

random.seed(42)
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS customers;

CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT NOT NULL,
  country TEXT NOT NULL,
  signup_date TEXT NOT NULL
);
CREATE TABLE products (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  category TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  status TEXT NOT NULL,
  ordered_at TEXT NOT NULL
);
CREATE TABLE order_items (
  id INTEGER PRIMARY KEY,
  order_id INTEGER NOT NULL REFERENCES orders(id),
  product_id INTEGER NOT NULL REFERENCES products(id),
  quantity INTEGER NOT NULL,
  unit_price_cents INTEGER NOT NULL
);
""")

first = ["Ava", "Liam", "Noah", "Mia", "Emma", "Lukas", "Sofia", "Ethan", "Zoe", "Omar"]
last = ["Smith", "Meyer", "Jones", "Tan", "Brown", "Novak", "Lee", "Khan", "Rossi", "Berg"]
countries = ["US", "DE", "GB", "CA", "AU", "NL"]
categories = {"Keyboards": 8900, "Monitors": 24900, "Cables": 1200, "Headsets": 6900, "Webcams": 5900}

for i in range(1, 201):
    name = f"{random.choice(first)} {random.choice(last)}"
    signup = date(2025, 1, 1) + timedelta(days=random.randint(0, 600))
    conn.execute(
        "INSERT INTO customers VALUES (?,?,?,?,?)",
        (i, name, f"customer{i}@shop.test", random.choice(countries), signup.isoformat()),
    )

pid = 1
for cat, base in categories.items():
    for n in range(1, 9):
        price = int(base * random.uniform(0.6, 1.6))
        conn.execute("INSERT INTO products VALUES (?,?,?,?)", (pid, f"{cat[:-1]} Model {n}", cat, price))
        pid += 1

statuses = ["completed"] * 80 + ["refunded"] * 8 + ["cancelled"] * 7 + ["pending"] * 5
item_id = 1
for oid in range(1, 1501):
    customer = random.randint(1, 180)  # customers 181-200 never order
    ordered = date(2026, 1, 1) + timedelta(days=random.randint(0, 303))
    conn.execute(
        "INSERT INTO orders VALUES (?,?,?,?)",
        (oid, customer, random.choice(statuses), ordered.isoformat()),
    )
    for _ in range(random.randint(1, 4)):
        prod = random.randint(1, pid - 1)
        price = conn.execute("SELECT price_cents FROM products WHERE id=?", (prod,)).fetchone()[0]
        conn.execute(
            "INSERT INTO order_items VALUES (?,?,?,?,?)",
            (item_id, oid, prod, random.randint(1, 3), int(price * random.uniform(0.9, 1.0))),
        )
        item_id += 1

conn.commit()
for t in ("customers", "products", "orders", "order_items"):
    print(t, conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0])
conn.close()

Run python make_db.py. It prints one count per table: 200 customers, 40 products and 1500 orders follow straight from the loops, while the order_items count depends on the seeded random draws and should be identical on every run. Every later step opens shop.db read-only, and deleting the file and rerunning the script gives a fresh copy.

Step 4: Extract the schema with sample rows

Most wrong answers trace back to missing context, so steps 4 and 5 deserve the most care. The format follows the DAIL-SQL prompt study: it found that the Code Representation Prompt, which gives the schema as CREATE TABLE statements, performed best across the LLMs it tested, and that including foreign-key information improved OpenAI models’ accuracy by 0.6-2.9%. So describe() passes the raw DDL, with its REFERENCES clauses, plus two sample rows per table so the model sees date formats, the casing of categorical values and the unit of money columns. The module also exposes table_names() for the guard and connect_ro(), which opens SQLite read-only through a URI. Save it as schema.py.

import sqlite3

NOTES = {
    "orders.status": "One of completed, pending, cancelled, refunded. Revenue only counts completed orders.",
    "orders.ordered_at": "ISO date text (YYYY-MM-DD). Use strftime for month or year filters.",
    "order_items.unit_price_cents": "Price actually charged per unit, in cents. Revenue = quantity * unit_price_cents / 100.0.",
    "products.price_cents": "Current list price in cents. Do not use it for revenue.",
}


def connect_ro(db_path):
    return sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)


def table_names(db_path):
    conn = connect_ro(db_path)
    try:
        rows = conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"
        ).fetchall()
    finally:
        conn.close()
    return {r[0] for r in rows}


def describe(db_path, sample_rows=2):
    conn = connect_ro(db_path)
    parts = []
    try:
        tables = conn.execute(
            "SELECT name, sql FROM sqlite_master "
            "WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
        ).fetchall()
        for name, ddl in tables:
            parts.append(ddl.strip() + ";")
            cols = [r[1] for r in conn.execute(f'PRAGMA table_info("{name}")')]
            rows = conn.execute(f'SELECT * FROM "{name}" LIMIT {int(sample_rows)}').fetchall()
            parts.append(f"-- sample rows from {name} ({', '.join(cols)}):")
            parts.extend(f"--   {r!r}" for r in rows)
    finally:
        conn.close()
    notes = "\n".join(f"- {k}: {v}" for k, v in NOTES.items())
    return "\n".join(parts) + "\n\nBusiness rules:\n" + notes

Print describe("shop.db") to see exactly what the model receives: each CREATE TABLE statement followed by commented sample rows, then the business rules. Sample rows are the part to handle with care. On a real database they contain real emails, names and addresses, and you are about to send them to a third-party API. Mask sensitive columns, or set sample_rows=0 and rely on the notes in step 5.

Step 5: Add business rules as a mini semantic layer

Each entry in NOTES pins down one definition the DDL cannot express: revenue counts only completed orders, money columns hold cents, dates are ISO text so month filters need strftime. Without them a model has to guess, and a plausible wrong answer uses the list price and ignores order status:

-- plausible but wrong: list price, all statuses
SELECT SUM(p.price_cents * oi.quantity) / 100.0
FROM order_items oi JOIN products p ON p.id = oi.product_id;

-- right: charged price, completed orders only
SELECT ROUND(SUM(oi.quantity * oi.unit_price_cents) / 100.0, 2)
FROM order_items oi JOIN orders o ON o.id = oi.order_id
WHERE o.status = 'completed';

Both queries run and return a number; only one matches what finance calls revenue, and no syntax check catches the difference. Whenever an eval failure traces to a definition, add one line to NOTES and rerun. Keep the lines short and literal: what a column holds, what a status means, which table is the source of truth for a number. Every extra token ships on every request, at the rates in the cost section.

Published findingApplied inWhat the build does with it
The Code Representation Prompt (schema as CREATE TABLE) and the OpenAI Demonstration Prompt performed best across LLMs (DAIL-SQL study)Step 4describe() sends raw DDL, not a prose summary of the tables.
Foreign-key information improved OpenAI models’ accuracy by 0.6-2.9% (DAIL-SQL study)Step 4The REFERENCES clauses stay in the DDL; do not strip them to save tokens.
Telling the model to return a complete sqlite query with no explanation added 1.3-3% across all models (DAIL-SQL study)Step 9The system prompt demands one fenced SQL block and nothing else.
DAIL Organization, which sends question and SQL pairs without schemas, reached comparable accuracy to full-information prompts on far fewer tokensStep 13Example retrieval stores approved question and query pairs, not extra copies of the schema.
Fine-tuned models largely stopped benefiting from few-shot examples, which often hurt themStep 13If you fine-tune a model, score it with and without examples.
For open models, code-specific training mattered more than size: CodeLLaMA-34B clearly beat the larger LLaMA-2-CHAT-70BStep 13For a local model, pick a code-trained one and score it in step 12.
No consensus yet on the best prompt templates (SQLBench)Step 11Your golden set, not a paper, decides between prompt variants.
Weak spots: nested sub-queries, multi-table joins, window functions (survey)Step 11The golden set must contain all three kinds.

Steps 6 to 9: wrapper, a parser-based guard, read-only execution and a retry loop

Four small files turn the schema context into a tool that is safe and corrects itself. Two layers protect the data. The guard (step 7) parses the model’s text and refuses anything that is not a single SELECT on known tables before the database sees it. The connection (step 8) opens the file read-only with a timeout, so a hole in the guard still cannot write and a runaway query still stops. A prompt line saying “never write data” is a request, not a control, so neither layer relies on it.

Step 6: Write a thin LLM wrapper

One function, complete(system, messages), hides the difference between provider SDKs, so comparing models is a change in .env. It reads the model ID at call time, so the eval script can import everything without credentials. Save it as llm.py.

import os

from dotenv import load_dotenv

load_dotenv()


def complete(system, messages, max_tokens=800):
    provider = os.getenv("LLM_PROVIDER", "anthropic")
    model = os.environ["LLM_MODEL"]

    if provider == "anthropic":
        import anthropic

        client = anthropic.Anthropic()
        msg = client.messages.create(
            model=model, max_tokens=max_tokens, system=system, messages=messages
        )
        return "".join(b.text for b in msg.content if b.type == "text")

    if provider == "openai":
        from openai import OpenAI

        client = OpenAI()
        resp = client.chat.completions.create(
            model=model, messages=[{"role": "system", "content": system}, *messages]
        )
        return resp.choices[0].message.content

    raise ValueError(f"Unknown LLM_PROVIDER: {provider}")

The wrapper passes no sampling parameters, such as temperature. To use a local server that speaks the OpenAI protocol, pass a base_url argument to OpenAI() and set LLM_PROVIDER=openai.

Step 7: Write the SQL guard

The guard is the most important file. It uses sqlglot to parse the text into a syntax tree rather than scanning for banned words, because keyword filters miss comments, casing tricks and stacked statements. The checks run in order: the text must parse; it must hold exactly one statement; the top-level node must be a SELECT or a UNION of SELECTs; every table must be on the allow-list or be a CTE defined in the same query; and a LIMIT is added if the model left one out. Save it as guard.py; it also holds run_query(), which is step 8.

import sqlite3
import time

import sqlglot
from sqlglot import exp

from schema import connect_ro


class UnsafeSQL(ValueError):
    pass


def check(sql, allowed_tables, dialect="sqlite", max_rows=200):
    try:
        statements = [s for s in sqlglot.parse(sql, read=dialect) if s is not None]
    except sqlglot.errors.SqlglotError as e:
        raise UnsafeSQL(f"Could not parse the SQL: {e}")

    if len(statements) != 1:
        raise UnsafeSQL("Exactly one statement is allowed.")
    tree = statements[0]

    if not isinstance(tree, (exp.Select, exp.Union)):
        raise UnsafeSQL(f"Only SELECT queries are allowed, got {type(tree).__name__}.")

    cte_names = {c.alias_or_name for c in tree.find_all(exp.CTE)}
    for table in tree.find_all(exp.Table):
        if table.name not in allowed_tables and table.name not in cte_names:
            raise UnsafeSQL(f"Table not allowed: {table.name}")

    if tree.args.get("limit") is None:
        tree = tree.limit(max_rows)
    return tree.sql(dialect=dialect)


def run_query(db_path, sql, timeout_s=5):
    conn = connect_ro(db_path)
    started = time.monotonic()
    conn.set_progress_handler(
        lambda: 1 if time.monotonic() - started > timeout_s else 0, 10000
    )
    try:
        cur = conn.execute(sql)
        columns = [d[0] for d in cur.description]
        rows = cur.fetchall()
    finally:
        conn.close()
    return columns, rows

Try these inputs against check() before you trust it. Each line shows the outcome the code is written to produce:

DROP TABLE customers                        -> Only SELECT queries are allowed, got Drop.
SELECT * FROM customers; DELETE FROM orders -> Exactly one statement is allowed.
SELECT * FROM sqlite_master                 -> Table not allowed: sqlite_master
UPDATE orders SET status='x'                -> Only SELECT queries are allowed, got Update.
WITH c AS (SELECT * FROM customers) SELECT * FROM c
                                            -> allowed, rewritten with LIMIT 200
SELECT 1 UNION SELECT 2                     -> allowed, rewritten with LIMIT 200

Blocking sqlite_master matters because a user, or an instruction hidden in user text, could otherwise list every table in the file.

Step 8: Run queries read-only with a timeout

run_query() opens the database with mode=ro and installs a progress handler that aborts any statement running past five seconds. A vague question can produce a cross join, and TextQL’s documentation warns that vague questions on large tables risk long-running queries that may time out, so the timeout earns its place even without an attacker. Prove both behaviors with a throwaway script:

from guard import run_query

try:
    run_query("shop.db", "DELETE FROM orders")
except Exception as e:
    print(type(e).__name__, e)

slow = ("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x < 500000000) "
        "SELECT COUNT(*) FROM n")
try:
    run_query("shop.db", slow, timeout_s=2)
except Exception as e:
    print(type(e).__name__, e)

The first call should raise an OperationalError about writing to a readonly database.

Step 9: Write the prompt and the self-correcting ask loop

The system prompt states the task, the dialect and the rules, then appends the schema context. Two rules carry weight. The model must reply with one fenced SQL block and nothing else, which makes extraction reliable and mirrors the “SQL only, no explanation” rule the DAIL-SQL study found helpful. It must also return a harmless marker query when a question cannot be answered, so it does not invent columns to please the user. Save this as ask.py.

import re
import sqlite3
import sys

from guard import UnsafeSQL, check, run_query
from llm import complete
from schema import describe, table_names

DB = "shop.db"

SYSTEM = """You translate questions about a database into exactly one SQLite SELECT query.

Rules:
- Use only the tables and columns in the schema below.
- Never write INSERT, UPDATE, DELETE, DROP, ALTER or CREATE.
- If the question cannot be answered from the schema, return SELECT 'cannot answer' AS reason.
- Reply with the SQL inside one fenced code block marked sql and nothing else.

Schema:
{schema}
"""


def extract_sql(text):
    match = re.search(r"`{3}(?:sql)?\s*(.*?)`{3}", text, re.DOTALL | re.IGNORECASE)
    return (match.group(1) if match else text).strip()


def ask(question, db=DB, retries=2):
    system = SYSTEM.format(schema=describe(db))
    allowed = table_names(db)
    messages = [{"role": "user", "content": question}]
    last_error = None

    for attempt in range(retries + 1):
        raw = complete(system, messages)
        sql = extract_sql(raw)
        try:
            safe_sql = check(sql, allowed)
            columns, rows = run_query(db, safe_sql)
            return {"sql": safe_sql, "columns": columns, "rows": rows, "attempts": attempt + 1}
        except (UnsafeSQL, sqlite3.Error) as e:
            last_error = e
            messages += [
                {"role": "assistant", "content": raw},
                {"role": "user", "content": f"That query failed: {e}\nReturn a corrected query."},
            ]

    raise RuntimeError(f"Gave up after {retries + 1} attempts: {last_error}")


def show(result):
    print("\nSQL:", result["sql"], f"(attempts: {result['attempts']})\n")
    print(" | ".join(result["columns"]))
    for row in result["rows"][:20]:
        print(" | ".join(str(v) for v in row))
    if len(result["rows"]) > 20:
        print(f"... {len(result['rows']) - 20} more rows")


if __name__ == "__main__":
    show(ask(" ".join(sys.argv[1:]) or "How many customers are there?"))

On each attempt the code extracts the SQL, runs it through the guard and executes it. If either step raises, it appends the model’s reply and the error text, such as no such column: o.total, and asks for a correction. Two retries cap the worst case at three calls, which is the multiplier in the cost section. extract_sql() falls back to the raw text when there is no fence; if that text is prose, the guard rejects it and the retry message says why.

Steps 10 to 12: a golden set that includes the constructs models miss

Step 10: Ask your first questions

python ask.py How many customers do we have in each country?

The tool prints the SQL that ran, the attempt count and up to 20 rows. The printed SQL will differ slightly with your model. It will also carry a LIMIT 200 and uppercase function names, because the guard returns sqlglot’s normalized SQL, so exact-text comparisons against the model’s raw reply will not match. Then try harder questions: the category with the most completed-order revenue, monthly revenue for 2026, and a question the data cannot answer, where a well-behaved model returns the cannot answer marker.

Step 11: Build a golden test set and the eval script

A golden set pairs questions with reference SQL you know is correct. The eval script runs the model’s query and the reference, then compares result sets: execution accuracy, the grading SQLBench describes. Save this as run_eval.py.

import sys

from ask import DB, ask
from guard import run_query

GOLD = [
    ("How many customers are there?",
     "SELECT COUNT(*) FROM customers"),
    ("How many customers do we have in each country?",
     "SELECT country, COUNT(*) FROM customers GROUP BY country"),
    ("What was the total revenue in dollars from completed orders?",
     "SELECT ROUND(SUM(oi.quantity * oi.unit_price_cents) / 100.0, 2) FROM order_items oi "
     "JOIN orders o ON o.id = oi.order_id WHERE o.status = 'completed'"),
    ("Which product category earned the most revenue from completed orders?",
     "SELECT p.category FROM order_items oi JOIN orders o ON o.id = oi.order_id "
     "JOIN products p ON p.id = oi.product_id WHERE o.status = 'completed' "
     "GROUP BY p.category ORDER BY SUM(oi.quantity * oi.unit_price_cents) DESC LIMIT 1"),
    ("How many orders were refunded in March 2026?",
     "SELECT COUNT(*) FROM orders WHERE status = 'refunded' "
     "AND ordered_at >= '2026-03-01' AND ordered_at < '2026-04-01'"),
    ("List the names of customers who never placed an order.",
     "SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders)"),
    ("What is the monthly revenue in dollars from completed orders in 2026?",
     "SELECT strftime('%Y-%m', o.ordered_at), ROUND(SUM(oi.quantity * oi.unit_price_cents) / 100.0, 2) "
     "FROM orders o JOIN order_items oi ON oi.order_id = o.id "
     "WHERE o.status = 'completed' GROUP BY 1"),
    ("What is the average number of items per completed order?",
     "SELECT ROUND(AVG(n), 2) FROM (SELECT SUM(oi.quantity) AS n FROM orders o "
     "JOIN order_items oi ON oi.order_id = o.id WHERE o.status = 'completed' GROUP BY o.id)"),
]


def normalize(rows):
    clean = [tuple(round(v, 2) if isinstance(v, float) else v for v in r) for r in rows]
    return sorted(clean, key=repr)


def main():
    passed = 0
    for question, gold_sql in GOLD:
        _, expected = run_query(DB, gold_sql)
        try:
            got = ask(question)
            ok = normalize(got["rows"]) == normalize(expected)
            note = f"attempts={got['attempts']}"
        except RuntimeError as e:
            ok, note = False, str(e)[:80]
        passed += ok
        print(f"{'PASS' if ok else 'FAIL'}  {question}  [{note}]")
    print(f"\nExecution accuracy: {passed}/{len(GOLD)} = {passed / len(GOLD):.0%}")
    sys.exit(0 if passed == len(GOLD) else 1)


if __name__ == "__main__":
    main()

normalize() sorts rows and rounds floats to two places, so row order and float noise do not cause false failures, and the comparison ignores column names because a model may call a column revenue where your reference says total. The set already contains the constructs the survey names as weak spots, except one: the revenue-by-category question is a multi-table join, and the never-ordered and average-items questions use a nested sub-query. Add a window-function pair so all three are covered:

    ("Rank customers by total completed-order spend (rank 1 is highest) and return only "
     "the customer id and rank for ranks 1 to 3.",
     "SELECT customer_id, rnk FROM (SELECT o.customer_id AS customer_id, "
     "RANK() OVER (ORDER BY SUM(oi.quantity * oi.unit_price_cents) DESC) AS rnk "
     "FROM orders o JOIN order_items oi ON oi.order_id = o.id "
     "WHERE o.status = 'completed' GROUP BY o.customer_id) WHERE rnk <= 3"),

Paste it as a ninth entry in GOLD. In a real project, draw dozens of questions from what users actually ask, and keep a few that are known to trip models. Score result rows, never SQL text, because two very different queries can return identical rows.

Before you spend any API money, test the test. This script swaps in an oracle that returns the reference SQL, so the scoring must give full marks; if it does not, the grading is broken and no model score would mean anything. Save it as oracle_check.py.

import ask
import run_eval

GOLD = dict(run_eval.GOLD)


def oracle(system, messages, max_tokens=800):
    fence = "`" * 3
    return fence + "sql\n" + GOLD[messages[0]["content"]] + "\n" + fence


ask.complete = oracle
run_eval.main()

Run python oracle_check.py.

Step 12: Run the eval on two or three models and read the failures

This script takes provider:model pairs and prints one summary line per model.

#!/usr/bin/env bash
set -u
for pair in "$@"; do
  echo "== $pair"
  LLM_PROVIDER="${pair%%:*}" LLM_MODEL="${pair#*:}" python run_eval.py | tail -1
done
chmod +x compare.sh
./compare.sh anthropic:claude-haiku-5-5 anthropic:your-sonnet-id openai:gpt-6.1-terra

On Windows, set the two variables in PowerShell and run python run_eval.py once per model. Run the cheapest model first: if it scores full marks, your next job is a harder golden set, not a bigger model. If it misses questions, sort each failure into one of four buckets before paying for more:

  • Definition errors. The query ran but used the wrong column or status. Add a line to NOTES.
  • Dialect errors. The query used a function your database lacks. State the dialect in the system prompt and add a note on date functions.
  • Join errors. A one-to-many join double-counted rows. Add a note about grain, such as one row per order item.
  • Reasoning errors. The question needed several steps and the model lost the thread. Try a larger model or let it write a CTE first.

Model output varies between runs, so run the eval three times and compare, or keep only questions that are stable. Record pass count, average attempts and cost for each model. For a large golden set, the Batch API’s 50% discount makes an overnight run cheap. The accuracy figures you get are yours alone; the studies cited earlier cannot stand in for them.

Step 13 and beyond: a real database, then retrieval, cached prefixes and routing

Step 13: Harden the tool for a real database

  1. Use a least-privilege database role. SQLite’s read-only mode has no direct equivalent in a server database, so create a role that can only read the tables you list and cap its query time on the server.
  2. Switch the dialect. Pass the target dialect name to check(), name the engine in the system prompt, replace the connection code in connect_ro() and run_query(), and replace the sqlite_master queries in schema.py with your engine’s catalog queries. TextQL’s tool, for comparison, builds queries in the connected warehouse’s specific dialect.
  3. Log every request. Write the question, final SQL, attempt count, row count and latency to a JSON lines file. It seeds your next golden set.
  4. Decide what leaves the building. Strip or mask personal data before it reaches the model and check your provider’s retention terms before sending customer rows. If you pass query results back to a model for a summary, treat the values as untrusted text and do the summary in a separate call with no tools.
CREATE ROLE sqlask_ro LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE shop TO sqlask_ro;
GRANT USAGE ON SCHEMA public TO sqlask_ro;
GRANT SELECT ON customers, products, orders, order_items TO sqlask_ro;
ALTER ROLE sqlask_ro SET default_transaction_read_only = on;
ALTER ROLE sqlask_ro SET statement_timeout = '5s';

That role gives the database itself the final say: it has no write grants and runs read-only transactions, whatever the prompt contains. For the logging helper, add a start time at the top of ask() and replace the success return as shown.

import json
import time


def log_query(question, result, started):
    record = {
        "question": question,
        "sql": result["sql"],
        "attempts": result["attempts"],
        "rows": len(result["rows"]),
        "seconds": round(time.monotonic() - started, 2),
    }
    with open("queries.jsonl", "a") as f:
        f.write(json.dumps(record) + "\n")


# in ask(): add `started = time.monotonic()` before the loop, then on success:
#     result = {"sql": safe_sql, "columns": columns, "rows": rows, "attempts": attempt + 1}
#     log_query(question, result, started)
#     return result

After step 13: shrink the prompt, then route

Retrieve tables instead of sending them all. Prompt cost scales with schema size, and a 10,000-token schema costs $21.50 per 1,000 questions on Sonnet 5.5 against $5.50 at 2,000 tokens. Write a one-line description per table, embed the descriptions, and pass only the best matches plus the tables linked to them by foreign keys. Rerun the golden set after adding it, since retrieval can also drop a table the question needed.

Cache the schema prefix. The system prompt is identical on every call, so put the stable text first and the user’s question last. That is where the cached columns in the cost table come from: $5.50 falls to $1.70 per 1,000 on Sonnet 5.5 and $2.75 to $0.85 on gpt-6.1-terra.

Route by difficulty. Send every question to the cheap model, and escalate to a larger one if it needs more than one attempt or the guard rejects its output twice; the attempt counter already gives you the signal. If one question in five escalated from Haiku 5.5 to Sonnet 5.5, the blended cost would be $0.275 + 0.2 × $5.50 = $1.375 per 1,000, a quarter of the all-Sonnet price. The one-in-five share is an illustration; your attempt log tells you the real one.

Teach by example. Keep a table of user questions and human-approved queries, retrieve the most similar few, and add them to the prompt. The findings table above explains why pairs without schemas are the cheap way to add examples, and why a fine-tuned model should be scored with and without them.

Verify and show your work. Show users the SQL next to the answer, as TextQL’s documentation advises: “Check the generated SQL to ensure it matches your intent and doesn’t miss any important filters.” For numbers that feed decisions, recompute with a second, independently written query and compare.

Local models and libraries. The wrapper works with any OpenAI-compatible local server through base_url. The DAIL-SQL study found code-specific training mattered more than parameter count for open models, so score a code-trained model in step 12. Hosted tools such as TextQL cover parts of this loop, and building it once by hand gives you a baseline score to beat before adopting one.

Eleven failures this build produces, by symptom

SymptomLikely causeFix
KeyError: ‘LLM_MODEL’The .env file is missing or sits in another folder.Create .env next to the scripts, or export the variables in your shell.
Authentication error from the SDKWrong or empty API key variable name.Use ANTHROPIC_API_KEY for Claude and OPENAI_API_KEY for OpenAI, with no quotes or spaces.
Model not found errorThe model ID is misspelled or not enabled for your account.Copy the exact ID from your console’s model list. Anthropic’s release notes name claude-haiku-5-5 for Haiku 5.5, and OpenAI documents gpt-6.1-terra for Terra.
unable to open database fileshop.db does not exist, and read-only mode will not create it.Run python make_db.py from the project folder first.
Table not allowed: sqlite_masterThe model or a user asked about system tables.This is the guard working. Rephrase the question around business tables.
Could not parse the SQL, or Only SELECT queries are allowed with an odd node nameThe model replied with prose, so the fallback text was not SQL.Check the system prompt still demands a fenced sql block. The retry usually fixes it.
OperationalError: interruptedThe query ran past the five-second timeout.Ask a narrower question, add an index, or raise timeout_s deliberately.
no such column on every retryThe model cannot see the column it needs.Check the describe() output, and add the column or a note about where the data lives.
Eval passes sometimes and fails sometimesModel output varies between runs.Run the eval three times and compare, or keep only questions that are stable.
Rate limit errors during the evalThe provider is throttling how fast you send requests.Add a short sleep between questions. Separately, Anthropic’s Batch API is 50% cheaper for large sets.
Result looks right but the number is wrongA definition error, not a syntax error.Compare against the reference SQL and add a line to NOTES.

The files in run order: make_db.py builds shop.db; schema.py, llm.py and guard.py are imported modules with nothing to run; oracle_check.py proves the grader and must end in full marks before you spend API money; ask.py answers one question; run_eval.py scores the golden set; compare.sh repeats that per model. After any change to NOTES, the system prompt or the model ID, rerun the golden set; it exits with a non-zero status if any question fails.

python run_eval.py
Nadia Dubois

Nadia Dubois

AI, software and the business of tech

Nadia Dubois covers AI, software and the business of tech for Tech Insider: AI models and the products built on them, developer and productivity software, pricing, and the company decisions and regulation that shape the industry.

View all articles