A generated query can run cleanly and still be wrong—a dropped NULL customer, a silent inner join, an inflated sum. This guide shows how to build SQL test cases you can reproduce: a complete SQLite fixture, hand-derived expected rows, and a small Python runner that fails loudly.
Why Doesn't a Benchmark Score Tell You If a Query Is Correct?
Because it measures a model on someone else's databases. A benchmark fixes the questions, the schema, the values, and the reference answer. Your warehouse has none of those. Even a strong published result says nothing about whether a query drops rows when a customer id is NULL or quietly excludes orders that never matched a record.
So the useful question isn't "which model scores highest?" It's "what does this model do against data I control, with answers I derived by hand?" That's what a local test harness gives you. It won't prove universal correctness—more on that later—but it will catch the failures that actually reach business users, and it will do it in seconds, on every commit.
What's the Difference Between Exact Match, Execution, and Test-Suite Accuracy?
These three metrics get used interchangeably, and that's where evaluation goes wrong. They answer different questions and fail in opposite directions.
Exact SQL string match compares the generated query to a gold query character by character, usually after normalizing aliases and clauses. It's deterministic and cheap, but it rejects correct SQL that happens to be written differently and accepts nothing that isn't nearly identical in form.
Execution accuracy on one database runs both queries against a single populated database and compares the returned rows. It forgives stylistic differences, but it can pass two queries that agree here and disagree elsewhere—say, on a database where a customer is missing from the join.
Test-suite accuracy evaluates the query across a set of carefully generated database instances, including edge cases the single database omits. The official test-suite SQL evaluation repository implements this metric for Spider, SParC, CoSQL and related tasks; its own documentation notes that exact string match and single-database execution accuracy "either exaggerates or deflates the real semantic accuracy."
Here's the side-by-side:
Metric | What it compares | Typical false pass | Typical false fail |
|---|---|---|---|
Exact SQL string match | Generated SQL text vs. gold SQL after normalization | Rarely passes wrong SQL | Equivalent query written with a different join style |
Execution accuracy, one database | Result rows of both queries on one fixture | Queries agree on data that hides the bug | Non-deterministic row order |
Test-suite accuracy | Result rows across many generated database instances | All instances miss a bug the fixtures don't model | Slow, needs a generator and gold query |
Hand-derived assertions | Result rows vs. rows you computed yourself | Your fixture omits the real edge case | You mis-derived the expected answer |
Notice the fourth row. Everything you build below is a hand-derived assertion harness, not a test suite in the benchmark sense. It's closer to execution accuracy, because it runs real SQL against real data—but the expected answers come from your arithmetic, not from a gold query.
Why Can't a Toy Fixture Prove Universal Equivalence?
Query equivalence is a statement about all possible databases. A fixture is one database. Proving two queries equivalent would require reasoning over every permitted input, and a handful of rows can't do that—it can only prove that two queries can behave differently, by exhibiting one input where they do.
That makes fixtures excellent at falsification and useless at proof. If your runner says a join drops a NULL-brand customer, you've found a real bug. If it says every assertion passed, you've learned the query is right on the ~20 rows you inserted and nothing more.
This is precisely the gap test-suite accuracy tries to narrow: it generates many database instances from the gold query so that disagreements have somewhere to show up. You're doing a low-tech version of the same thing, with fixtures you can read and expectations you can defend in a code review. Keep that scope honest in your own project and in any vendor claim.
What Does a Complete SQLite Fixture Look Like?
Two tables, deliberately uneven. customers has four rows, including one with a NULL region and one that never places an order. orders has six rows, including one whose customer_id matches no customer—the orphan.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
region TEXT, -- NULL allowed on purpose
segment TEXT
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER, -- orphan allowed on purpose
order_date TEXT NOT NULL,
amount NUMERIC NOT NULL
);
INSERT INTO customers (customer_id, name, region, segment) VALUES
(1, 'Ada Lovelace', 'EMEA', 'Enterprise'),
(2, 'Grace Hopper', 'AMER', 'Enterprise'),
(3, 'Alan Turing', NULL, 'SMB'),
(4, 'Katherine J.', 'AMER', 'SMB');
INSERT INTO orders (order_id, customer_id, order_date, amount) VALUES
(101, 1, '2026-01-05', 120.00),
(102, 1, '2026-02-11', 80.50),
(103, 2, '2026-01-20', 400.00),
(104, 2, '2026-03-02', 99.99),
(105, 3, '2026-02-14', 55.25),
(106, 999, '2026-03-15', 10.00); -- no such customer
The three traps are all here. Customer 3 has a NULL region, so GROUP BY region will produce a NULL bucket that some tools silently drop. Customer 4 has no orders, so an INNER JOIN will make her vanish from a customer report. Order 106 points at a nonexistent customer, so a join to customers will make that revenue disappear while SUM over orders alone still counts it.
Which Queries Should You Test First?
Start with the ones that expose the traps, not the ones that look impressive. Also test a wrong query on purpose: a harness you've never seen fail is a harness you can't trust.
Query A — total revenue including orphans. Treats orders as the source of truth.
SELECT SUM(amount) AS total_revenue FROM orders;
Hand-derived: 120.00 + 80.50 = 200.50; + 400.00 = 600.50; + 99.99 = 700.49; + 55.25 = 755.74; + 10.00 = 765.74. Expected [(765.74,)].
Query B — revenue by region, inner join. The version most generators produce.
SELECT c.region, SUM(o.amount) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.region;
Hand-derived, walking the orders: 101 → EMEA 120.00, 102 → EMEA 200.50, 103 → AMER 400.00, 104 → AMER 499.99, 105 → NULL region 55.25. Order 106 is dropped because 999 isn't in customers. Expected [(NULL, 55.25), ('AMER', 499.99), ('EMEA', 200.50)] sorted by region ascending with NULL first. Total of the groups is 755.74—ten cents short of Query A, which is exactly the orphan leaking out.
Query C — customers with zero orders, NULL-safe left join.
SELECT c.customer_id, c.name, COALESCE(SUM(o.amount), 0) AS revenue
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
Hand-derived: 1 → 200.50, 2 → 499.99, 3 → 55.25, 4 → 0 (COALESCE fires on the NULL sum). Expected [(1, 'Ada Lovelace', 200.50), (2, 'Grace Hopper', 499.99), (3, 'Alan Turing', 55.25), (4, 'Katherine J.', 0.0)].
Query D — the deliberate failure. Counts only customers who have orders, then labels it "total customers."
SELECT COUNT(*) AS customer_count FROM customers WHERE customer_id IN (SELECT customer_id FROM orders);
Three customers own orders (1, 2, 3); 999 isn't a customer. The query returns [(3,)]—but the correct answer to "how many customers do we have" is 4. Assert the wrong value to confirm your runner fails. That negative test is worth more than another happy-path query.
Every expected row above was computed by hand from the INSERT statements. None of them were produced by running the SQL. If you change the fixture, re-derive them on paper first—otherwise you're just recording whatever the database says.
How Do You Run These Tests Deterministically?
Keep it short enough that someone reviews it. Load the fixture into an in-memory database, run each query, normalize the result, and compare to the hand-derived list.
import sqlite3
SCHEMA = open("fixture.sql").read() # the CREATE/INSERT block above
CASES = [
("A_total_revenue",
"SELECT TOTAL(amount) AS total_revenue FROM orders;",
[(765.74,)]),
("B_revenue_by_region",
"SELECT c.region, TOTAL(o.amount) AS revenue FROM customers c "
"JOIN orders o ON o.customer_id = c.customer_id GROUP BY c.region "
"ORDER BY c.region IS NOT NULL, c.region;",
[(None, 55.25), ("AMER", 499.99), ("EMEA", 200.50)]),
("C_customers_left_join",
"SELECT c.customer_id, c.name, ROUND(TOTAL(o.amount), 2) AS revenue "
"FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id "
"GROUP BY c.customer_id, c.name ORDER BY c.customer_id;",
[(1, "Ada Lovelace", 200.50), (2, "Grace Hopper", 499.99),
(3, "Alan Turing", 55.25), (4, "Katherine J.", 0.0)]),
# negative test: the "total customers" query counts only customers with orders
("D_counts_wrong_thing",
"SELECT COUNT(*) AS customer_count FROM customers "
"WHERE customer_id IN (SELECT customer_id FROM orders);",
[(4,)]),
]
def run(db, sql):
return [tuple(round(v, 2) if isinstance(v, float) else v for v in row)
for row in db.execute(sql).fetchall()]
def check():
db = sqlite3.connect(":memory:")
db.executescript(SCHEMA)
failures = []
for name, sql, expected in CASES:
actual = run(db, sql)
status = "PASS" if actual == expected else "FAIL"
print(f"{status:4} {name}")
if actual != expected:
failures.append((name, expected, actual))
db.close()
for name, exp, act in failures:
print(f"\n{name}\n expected: {exp}\n actual: {act}")
return not failures
if __name__ == "__main__":
raise SystemExit(0 if check() else 1)
Three details make this deterministic. ORDER BY appears in every multi-row query, because SQLite doesn't promise row order otherwise. The runner uses SQLite's TOTAL() rather than SUM() so an empty input returns 0.0 instead of NULL, which keeps the empty-result case a 0 comparison rather than a None one; ROUND(..., 2) then normalizes floating point, since 99.99 + 400.00 may not equal a literal 499.99 in binary. And the non-zero exit code lets CI treat a silent pass as a broken build.
Case D is the negative test: it expects [(4,)] but the query returns [(3,)], so the run exits non-zero on the first pass. That's the harness working. Keep that case in the suite—when the suite goes green, you'll know your assertions can fail, not just that the queries happen to agree.
What Should the Full Workflow Look Like?
Run the loop in this order; skipping a step is how gaps get into the suite.
Write the fixture first, and include at least one NULL in a grouped column, one unmatched foreign key, and one parent row with no children. Edge cases written after the query tend to be chosen to make the query pass.
Derive expected rows by hand, on paper or in a scratch cell, and note the arithmetic next to each one. Keep that note in the case definition.
Run the reference SQL to confirm the arithmetic, then replace the resulting values with your hand-derived ones so the assertion has an independent source of truth.
Add a deliberately wrong query and assert that it fails. A suite with no red test has no evidence it can detect anything.
Wire it into CI, so every schema, fixture, or prompt change re-runs the suite. A model that passed last week hasn't been evaluated against this week's fixture.
Log generated SQL alongside the result, so a failure shows what the model wrote, not just that numbers disagreed.
Step 5 matters more than it looks. When access policies get added—row-level filters that quietly restrict what a role can see—the correct result changes for that role, and a fixture that ignores roles will report success for a query that leaks data. If you're building those controls into a lakehouse, the pattern in Power BI RLS vs OLS: Securing Rows, Tables and Columns is a useful checklist for what "restricted" means per role.
Where Does the Harness Fit in a Real Data Platform?
The toy fixture is a unit test, not an integration test. In a platform, the same harness pattern extends along three axes: more realistic fixtures (typed dates, legacy region codes, dirty strings), one fixture per role so permission behavior gets asserted rather than assumed, and a semantic layer so the model can resolve "revenue" to your definition instead of guessing.
Auditability closes the loop. If you can't reconstruct which SQL ran, under which role, against which fixture, a passing assertion is a coincidence you can't reproduce. The correlation-id approach in AI SQL Query Audit Trails: Correlating User, Tool and Warehouse Query IDs is a practical starting point for tying a test case to the query it produced.
Semantic context is the other half. Text-to-SQL fails most often on definitions, not syntax—revenue net of returns or not, active customer for 30 or 90 days. Documenting those in a governed layer is what makes the expected values in your harness stable across teams; Why the Semantic Layer Is the Missing Link for Trustworthy AI Analytics covers how that layer changes what a model is asked to do.
One caution on any platform's configuration surface: domains, semantic contexts and permission boundaries are evaluation surfaces to test, not evidence that answers are correct. Platforms such as Singdata Analytics Agent expose those controls, and the same standard applies to them as to any other—configure, then assert.
FAQ
Do I need a benchmark to test text-to-SQL at all?
No—a benchmark is optional, not a prerequisite. You can start testing the day you have a fixture and a few queries worth asserting. Benchmarks are useful for screening candidates cheaply before you invest in your own suite, but assertions against data you control catch the failures a leaderboard can't see.
How many test cases are enough?
Enough that every trap you know about appears at least once: NULL in a grouped column, an orphan foreign key, a parent with no children, a wrong-definition aggregate. The right stopping rule is coverage of known failure modes plus one deliberately failing case, not a row count.
Can I just compare against a gold query's output instead of deriving rows by hand?
Yes. Running the candidate query and a reviewed gold query against the same fixture and comparing results is a valid, common form of execution evaluation—it's how most harnesses start. The caveat is that both queries share your assumptions: if the fixture is wrong, or your team's reading of "revenue" is wrong, both agree and the test passes. An independently reviewed or hand-derived expected row catches that, because it reintroduces a second opinion. Hand derivation is one way to get there, not a requirement.
Does a passing suite mean the generated SQL is correct?
It means it's correct on those rows. A fixture falsifies, it doesn't prove. Treat a green run as evidence about the cases you wrote, and add a case whenever production surprises you.
What about performance and cost?
Assert those separately, with an explicit ceiling. A correct query that scans everything has passed a correctness test and failed a cost test—different assertion, different threshold.
Conclusion: Test the Answer, Then Test the Answer Again
Benchmarks tell you whether a model is worth testing. Hand-derived test cases tell you whether it gets your data right. The fixture above—four customers, six orders, one NULL region, one orphan, one childless parent—is small enough to review in a minute and sharp enough to catch the three joins that break most text-to-SQL deployments.
Keep the loop honest: fixture first, expected rows by hand, one deliberately failing case, and a CI run on every change. Your suite will never prove universal equivalence, and it doesn't need to. It needs to fail before your users do.