Maps to: Stanford CS 257 Introduction to Automated Reasoning (Winter 2026), Lecture 19 · Tue 03/10/2026 · Using Formal Verification for Text-to-SQL (guest lecture by Nina Narodytska). Reading: none listed. Basis: The guest lecture’s slides are not public. Its title is also that of Narodytska’s LPAR-26 invited talk. This lecture is written from:
- Klopfenstein, He, Tremante, Wang, Narodytska and Wu, “SpotIt: Evaluating Text-to-SQL Evaluation with Formal Verification” (ICLR 2026), and its follow-up SpotIt+ (2026);
- He, Zhao, Wang and Wang, VeriEQL (OOPSLA 2024), the bounded equivalence checker SpotIt builds on;
- Chu, Weitz, Cheung and Suciu, Cosette (CIDR 2017);
- Zhong, Yu and Klein, distilled test suites (EMNLP 2020);
- the Spider and BIRD benchmark papers;
- classic results on query containment (Chandra and Merlin 1977; Trakhtenbrot).
These notes add one module,
sqlcheck.py, with:
- a SQL subset and a reference evaluator, cross-checked against SQLite;
- symbolic tables encoded with Lecture 16’s bit-vectors;
- bounded equivalence checking with validated counterexamples and DRUP certificates;
- the evaluation of text-to-SQL candidates.
The candidate queries are hand-written to reproduce mistakes reported in the literature; no language model is run. The experiments were designed for these notes and do not reflect what was said in class. Code:
code/lecture19/(3 scripts + 1 module; Python standard library only, includingsqlite3; about 1 to 5 seconds of CPU time each) Reading time: 2 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain how text-to-SQL systems are evaluated (execution accuracy on a test database) and why that is optimistic.
- Give SQL’s semantics precisely enough to reason about it: bags, NULL and three-valued logic, aggregates on empty input, unordered ties.
- Define query equivalence (on all databases satisfying the integrity constraints, as bags or as sets). Say what is known about deciding it.
- Encode symbolic tables and a query’s execution into a solver. Read a model as a counterexample database, and validate it on a real engine.
- Interpret “equivalent up to rows”: what it certifies and what it misses (row bound, value range, unsupported features).
- Compare the three ways of judging a generated query, and recognize when the gold query is the one that is wrong.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| FOL, structures, finite models (Lectures 6–7); undecidability (Lecture 8) | SQL as first-order queries over finite structures; bags | — |
| bit-vectors, bit-blasting, DRUP (Lectures 5, 16) | symbolic tables, bounded equivalence | — |
| symbolic execution (Lecture 14) | symbolic execution of queries | — |
| combination of theories (Lecture 18) | — | synthesis with a verifier in the loop (Lecture 20) |
0.3 Map
§1 text-to-SQL, and how it is judged
§2 what a SQL query means ← code 01
§3 query equivalence: definitions and decidability
§4 bounded equivalence with symbolic tables ← code 02
§5 evaluating generated queries ← code 03
§6 verification in the generation loop (overview)
§7 summary §8 common pitfalls §9 exercises §10 further reading §11 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| the result of query on database : a bag (multiset) of rows | |
| as bags for every valid ; : as sets | |
| equal on every valid database with at most rows per table (and values in range) | |
| NULL, UNKNOWN | SQL’s missing value; the third truth value |
| EX | execution accuracy: same result (as a set of rows) on the test database |
0.5 The code of this lecture
One module, sqlcheck.py:
- schemas:
Schema,Table,Column,without_constraints; - SQL:
parse,Query; - the reference evaluator:
eval_query,eval_bool,same_result;run_sqlite,random_database; - the symbolic encoding:
SymDB,Encoder,results_differ; - checking:
check_equivalence; - evaluation:
execution_match,test_suite_match,equivalence_classes; - the benchmark:
HR,TEST_DB,QUESTIONS.
The solver is Lecture 16’s bit-blaster with Lecture 5’s CDCL. Python’s built-in sqlite3 is the independent referee.
1. Text-to-SQL, and how it is judged
1.1 The task and the benchmarks
The task. A text-to-SQL system turns a question about a database into a query:
What is the name of the employee with the highest salary?
SELECT name FROM emp WHERE salary = (SELECT MAX(salary) FROM emp)
Large language models now do this well enough to be used in practice. The benchmarks that measure progress are Spider and BIRD. Each pairs questions with a gold query written by an annotator and a test database.
How a prediction is judged. The standard measure, execution accuracy (EX), runs the generated query and the gold query on the test database. The prediction counts as correct if the two results agree; BIRD compares the sets of result rows.
1.2 Why this is optimistic
Agreement on one database is not equivalence. Two different queries can return the same rows on the test database by luck. They then differ on another database: one with a tie, an empty table, a NULL, or a duplicate. The question that matters is equivalence: do the two queries agree on every database?
Why this is the course’s kind of question. It is a question about all finite structures of a signature (Lecture 7), so a solver can help:
- it can search for a small database on which the queries differ (a counterexample);
- or it can show that none exists up to a bound.
SpotIt. Narodytska and colleagues’ SpotIt does exactly this for BIRD. It builds on the VeriEQL checker and validates every counterexample on SQLite. It reports two findings:
- execution accuracy accepts many generated queries that are not equivalent to the gold query, enough to reorder the published ranking of methods;
- remarkably often, the counterexamples reveal a wrong gold query or an ambiguous question.
This lecture rebuilds that pipeline on the course’s own solvers.
1.3 The benchmark of these notes
The schema.
CREATE TABLE dept (id INTEGER PRIMARY KEY, name TEXT NOT NULL)
CREATE TABLE emp (id INTEGER PRIMARY KEY, name TEXT NOT NULL, dept INTEGER, salary INTEGER NOT NULL,
bonus INTEGER, grade TEXT, FOREIGN KEY (dept) REFERENCES dept(id))
The test database. Three departments (Sales, Lab, Ops) and five employees. Bob’s bonus and Eve’s grade are NULL.
The questions. Five questions, each with a gold query and 12 candidates in total. The candidates reproduce the typical mistakes reported for generated SQL:
ORDER BY … LIMIT 1for “the highest”;COUNT(*)after a LEFT JOIN;- an inner join that drops empty groups;
- grouping by a non-key;
SUM(condition);- forgetting NULLs;
- forgetting DISTINCT.
Script 01, Part 1, prints them with the gold results.
2. What a SQL query means
To compare queries we need their meaning exactly. eval_query implements the subset’s semantics directly. The symbolic encoding of §4 mirrors it operator by operator.
2.1 Bags, and how a query computes
Tables and results are bags. They are multisets of rows: duplicates count, and order does not, unless ORDER BY asks for it. A query is evaluated in this order:
- FROM: the product of the tables, filtered by each JOIN’s ON condition. A LEFT JOIN keeps unmatched left rows, padded with NULLs.
- WHERE: keep the rows whose condition is TRUE.
- GROUP BY: group the rows by key value; NULL keys form one group. Compute the aggregates per group.
- HAVING: keep the groups whose condition is TRUE.
- SELECT: compute the output columns; DISTINCT removes duplicate rows.
- ORDER BY and LIMIT: sort, then keep the first rows.
DISTINCT, and set comparison. A join repeats a row once per match, and only DISTINCT removes the duplicates. Script 01, Part 5, takes one department with two employees earning more than 5. Without DISTINCT, the query returns the department twice:
- as bags the results differ;
- as sets they are equal, so BIRD’s set comparison accepts the query.
“Correct” depends on which comparison the evaluation chooses.
2.2 NULL and three-valued logic
NULL means “missing”. A comparison with NULL is neither true nor false but UNKNOWN. The connectives follow Kleene’s three-valued logic. Script 01, Part 3, computes the tables:
| AND / OR TRUE | AND / OR FALSE | AND / OR UNKNOWN | NOT | |
|---|---|---|---|---|
| TRUE | TRUE / TRUE | FALSE / TRUE | UNKNOWN / TRUE | FALSE |
| FALSE | FALSE / TRUE | FALSE / FALSE | FALSE / UNKNOWN | TRUE |
| UNKNOWN | UNKNOWN / TRUE | FALSE / UNKNOWN | UNKNOWN / UNKNOWN | UNKNOWN |
WHERE keeps only TRUE rows, so UNKNOWN rows vanish silently. On the test database:
| query | result |
|---|---|
SELECT COUNT(*) FROM emp | 5 |
... WHERE bonus > 3 OR bonus <= 3 | 4 (Bob’s NULL bonus fails both) |
... WHERE bonus = NULL | 0 (never TRUE; use IS NULL) |
... WHERE bonus IS NULL | 1 |
... WHERE grade NOT IN ('-', NULL) | 0 (a NULL in the list makes every non-member UNKNOWN) |
... WHERE NOT (grade = '-') | 2 (Eve’s NULL grade is dropped) |
Two laws survive: De Morgan’s laws, and double negation. Exercise 2 checks one with the solver. The law of the excluded middle () does not survive.
2.3 Aggregates on empty and all-NULL input
Script 01, Part 4:
| database | COUNT(*), COUNT(bonus), SUM(bonus), MAX(bonus) | GROUP BY dept with COUNT(*) |
|---|---|---|
| test database | (5, 4, 12, 5) | (1, 2) (2, 1) (3, 2) |
| all bonuses NULL | (5, 0, NULL, NULL) | (1, 2) (2, 1) (3, 2) |
| no employees | (0, 0, NULL, NULL) | no rows |
What the table shows.
- COUNT and SUM differ on no values.
COUNT(e)counts non-NULL values. SUM, MIN and MAX of no values are NULL, not 0. SoCOUNT(*) ... WHERE bonus > 3andSUM(bonus > 3)agree except on the empty table, or when every bonus is NULL. - Empty input. Without GROUP BY an aggregate query returns one row even on an empty table; with GROUP BY it returns one row per group, hence none.
2.4 The evaluator, checked against SQLite
The reference semantics must itself be right. Script 01, Part 2, runs all 17 queries of the benchmark on 300 random databases and compares the results with SQLite’s:
| queries | comparisons | identical results (as bags) | differences with a tie |
|---|---|---|---|
| without LIMIT | 4,800 | 4,800/4,800 | — |
| with ORDER BY … LIMIT | 300 | 289/300 | 11/11 |
Every disagreement is a tie on the sort key. SQL leaves the order of tied rows unspecified. Our evaluator keeps ties in input order (a stable sort), and SQLite returned another tied employee. Neither is wrong. This freedom is why ORDER BY salary DESC LIMIT 1 is a dangerous translation of “the highest”: with a tie it returns one of the top earners, and which one is unspecified.
3. Query equivalence
3.1 Definitions
Equivalence. Two queries over a schema with integrity constraints are equivalent, , if for every finite database that satisfies . The equality is taken as bags (SQL’s own semantics), as sets (BIRD’s comparison), or as lists (when order matters).
Two remarks.
- The constraints are part of the question.
COUNT(DISTINCT id)equalsCOUNT(*)becauseidis a primary key: unique and never NULL (§4.4). - Only finite databases count. SQL’s databases are finite structures. Equivalence quantifies over finite models: finite model theory, not the general FOL of Lectures 6–8.
3.2 What can be decided
Conjunctive queries. These are SELECT-FROM-WHERE with equality conditions, read as sets.
- Containment is decidable. Chandra and Merlin (1977) reduce it to finding a homomorphism, and showed it NP-complete.
- Equivalence is containment both ways.
Under bag semantics. Equivalence of conjunctive queries reduces to isomorphism. Containment is a long-standing open problem.
Full SQL. Its first-order core expresses every first-order sentence: a query is empty on all databases exactly when the sentence has no finite model. Trakhtenbrot’s theorem says finite satisfiability is undecidable, so equivalence of SQL queries is undecidable.
The two practical responses.
- Unbounded provers prove equivalence for fragments, by rewriting and normalization. Examples are Cosette’s proofs in Coq, and systems such as SQLSolver and QED.
- Bounded checkers search all databases up to a size. VeriEQL and SpotIt work this way, as does this lecture’s code. They are complete for finding small counterexamples, but cannot prove equivalence in general.
4. Bounded equivalence with symbolic tables
4.1 Symbolic tables
A symbolic table has unknown size and unknown contents. SymDB(schema, k) gives every table slots. Slot of table has:
- a presence bit (does this row exist?);
- per column, a value: an 8-bit vector ;
- per nullable column, a NULL bit .
The constraints form a formula over these unknowns:
- cell domains: integers . Text cells are codes, one per string literal of the queries plus two other strings. Text supports only , and IN, which codes preserve.
- PRIMARY KEY: present rows have different keys.
- FOREIGN KEY: a present row’s non-NULL reference equals the key of a present parent row.
- symmetry breaking: present slots come first ().
One satisfying assignment is one database. For a single emp row can take 31,104 values. Four rows give about combinations, before keys and symmetry are taken into account.
4.2 Symbolic execution of a query
Symbolic values. Encoder executes a query over the slots, producing formulas instead of values (Lecture 14’s symbolic execution, for queries). A symbolic value is a pair (bit-vector, NULL bit), and a truth value is a pair (is-TRUE, is-FALSE). Each operator mirrors the evaluator:
| operator | symbolic version |
|---|---|
| FROM / JOIN | candidate rows; present iff both are present and ON is TRUE |
| LEFT JOIN | plus, per left row, a NULL-padded row, present iff no right row matches |
| WHERE | presence ∧ (condition is TRUE) |
| comparisons | TRUE iff both sides are non-NULL and the comparison holds; FALSE iff both are non-NULL and it fails |
| GROUP BY | row represents a group if present and no earlier present row has the same key (NULL-safe); the aggregates run over the rows with that key |
| COUNT, SUM | ; SUM is NULL if no member is non-NULL |
| MIN, MAX | a fold of if-then-else |
| DISTINCT | a row survives if no earlier present row is equal (NULL-safe) |
| ORDER BY … LIMIT | = number of present rows before (by key; ties by position); keep |
Comparing the results. The formula “the two results differ” (results_differ) depends on the comparison:
- as bags: some present row occurs a different number of times in the two results;
- as sets: some present row of one result has no equal row in the other.
The question to the solver. It is asked: constraints ∧ results differ. The CNF of the two Q2 queries grows from 376 clauses at to 12,390 at (script 02, Part 1).
4.3 The checking loop, and validation
check_equivalence tries :
- SAT at some . The model is decoded into a concrete database. It is then validated: the reference evaluator and SQLite are both run on it, and both must see different results. A model that fails validation is reported as spurious: it would reveal an encoding bug. None occurs here. The first that works gives a counterexample that is minimal in rows per table.
- UNSAT for every . The answer is “equivalent up to rows”. Every UNSAT answer carries a DRUP proof, checked independently (Lecture 5).
Script 02, Part 2, compares every candidate with its gold query (as bags, ):
| candidate | verdict | rows | counterexample |
|---|---|---|---|
Q1.1 ORDER BY salary DESC LIMIT 1 | different | 2 | two employees with the same top salary |
Q1.2 salary >= (SELECT MAX(salary) ...) | equivalent up to 3 | — | |
Q2.1 LEFT JOIN with COUNT(*) | different | 1 | a department without employees: 1 instead of 0 |
| Q2.2 inner JOIN | different | 1 | the same department disappears |
Q2.3 GROUP BY d.name | different | 2 | two departments with the same name merge |
Q3.1 COUNT(bonus) ... WHERE bonus > 3 | equivalent up to 3 | — | |
Q3.2 SUM(bonus > 3) | different | 1 | the empty table: 0 vs NULL |
Q3.3 WHERE NOT bonus <= 3 | equivalent up to 3 | — | |
Q3.4 ... OR bonus IS NULL | different | 1 | one employee with a NULL bonus |
| Q4.1 no DISTINCT | different (bags) | 2 | two high earners in one department |
Q4.2 GROUP BY d.name instead of DISTINCT | equivalent up to 3 | — | |
Q5.1 grade NOT IN ('-', '+-') | different | 1 | an employee with grade ’+-’ |
What the table shows.
- Every counterexample is tiny and explains itself. The Q1.1 database is two employees with salary 0. The gold query returns both names, and the LIMIT query only the first; SQLite agrees.
- Q5.1 is the gold query’s fault (§5.3).
4.4 Certificates, constraints and costs
Certified equivalence. Script 02, Part 3, certifies five equivalent pairs up to 4 rows. The table shows clauses and conflicts per bound:
| pair | ||||
|---|---|---|---|---|
| Q1 gold vs Q1.2 | 556/7 | 1,660/70 | 3,155/223 | 5,026/551 |
| Q3 gold vs Q3.1 | 408/2 | 1,085/4 | 2,018/9 | 3,192/21 |
| Q3 gold vs Q3.3 | 398/0 | 1,058/0 | 1,967/0 | 3,121/0 |
| Q4 gold vs Q4.2 | 414/0 | 1,266/0 | 2,807/0 | 5,152/0 |
| BETWEEN 3 AND 4 vs | 608/7 | 1,578/31 | 2,939/84 | 4,673/217 |
All DRUP proofs check.
Where the effort goes. Conflicts grow where the queries compare values (the scalar subquery with ). Where unit propagation already shows the results equal, there are none.
What the certificate does not cover. It certifies the solver’s answer, not the encoding. A wrong encoding of SQL would be certified too. Counterexamples are re-validated on SQLite, but an UNSAT answer has no witness to re-run. That is why the evaluator was cross-checked so carefully (§2.4).
Integrity constraints. Script 02, Part 4:
| query 1 | query 2 | with keys | without |
|---|---|---|---|
COUNT(DISTINCT id) | COUNT(*) | equivalent up to 3 | different: one row with id NULL |
COUNT(*) of emp JOIN dept | COUNT(dept) | equivalent up to 3 | different: an employee whose department does not exist |
Constraints are part of the question. This is SpotIt’s COUNT vs COUNT(DISTINCT) example: whether it is a bug depends on whether the column is a key. A counterexample that violates the real database’s constraints is not a counterexample. SpotIt+ therefore mines constraints from example databases with rules, and has a language model check them, so that counterexamples stay realistic.
4.5 What a bound cannot see
Script 02, Part 5:
| query 1 | query 2 | verdict |
|---|---|---|
... GROUP BY dept HAVING COUNT(*) > 3 | ... WHERE 1 = 0 | equivalent up to 3 rows, different at |
... WHERE salary > 10 | ... WHERE 1 = 0 | “equivalent up to 4 rows”, wrongly: cells only range over 0..7 |
... WHERE dept IN (SELECT id FROM dept) | SELECT id FROM emp | unsupported: IN with a subquery |
There are two kinds of bound: rows and values. “Equivalent up to ” always means “no counterexample within the bounds”, never “equivalent”. SpotIt reports that on BIRD few new differences appear beyond 3 rows. In the benchmark here, every difference appears at , but nothing guarantees that in general. Unsupported SQL is reported as such; approximating it silently would make answers wrong.
5. Evaluating generated queries
5.1 Three judges
Script 03, Part 1, compares three judges, all comparing results as sets, as BIRD does:
- EX: the test database;
- suite: 100 random databases that satisfy the constraints and use the queries’ literals;
- verify: bounded verification with .
| candidate | EX | suite | verify |
|---|---|---|---|
Q1.1 ORDER BY ... LIMIT 1 | = | = | ≠ () |
| Q1.2 | = | = | = |
Q2.1 COUNT(*) | = | ≠ | ≠ () |
| Q2.2 inner JOIN | = | ≠ | ≠ () |
Q2.3 GROUP BY d.name | = | ≠ | ≠ () |
| Q3.1 | = | = | = |
Q3.2 SUM(bonus > 3) | = | ≠ | ≠ () |
| Q3.3 | = | = | = |
Q3.4 OR bonus IS NULL | ≠ | ≠ | ≠ () |
| Q4.1 no DISTINCT | = | = | = (as sets) |
| Q4.2 | = | = | = |
Q5.1 NOT IN | = | ≠ | ≠ () |
The judges accept 11, 6 and 5 of the 12 candidates.
The test database is reasonable but shows only one mistake. It has no tie for the top salary, no department without employees, no duplicate department name, and no grade ’+-’.
Random testing does better (Part 2), but needs luck for coincidences. A tie for the top salary appeared in the 27th random database (a bag difference). Tied employees with different names, which a set comparison needs, appeared only in the 128th. Compared as sets, every other difference appeared within the first 4 databases, because the random databases are small and reuse the queries’ literals, as distilled test suites do. Compared as bags, Q4.1 (two high earners in one department) also needed 27.
Verification constructs the coincidence instead of waiting for it. When it finds nothing, it certifies the bounded claim, whereas a test suite that finds nothing proves nothing.
5.2 Bags or sets?
Q4.1 (no DISTINCT) is wrong as a bag and right as a set; under BIRD’s comparison it is correct on every database. Neither choice is “the” truth:
- the question (“which departments…”) suggests a set;
- SQL returns a bag.
An evaluation must state its semantics, and a verifier makes the choice explicit.
5.3 When the gold query is wrong
Q5 asks for employees whose grade is “neither ’-’ nor ’+-’”. The gold query is WHERE grade <> '-' OR '+-', which parses as (grade <> '-') OR ('+-'). SQLite reads the string ’+-’ in a Boolean context as the number 0, that is, FALSE. So the gold query keeps ’+-’ employees.
The counterexample is one employee with grade ’+-’. The gold query returns them and the candidate NOT IN ('-', '+-') does not; SQLite agrees. A person reading this database sees in seconds that the candidate is right and the gold query is wrong. Execution accuracy called the candidate correct only because the test database happens to have no ’+-’.
This is SpotIt’s first example, transplanted. Their manual analysis found that a large share of the differences on BIRD come from problematic gold queries or ambiguous questions rather than from the generated queries. They also suggest that the best published scores may be close to a ceiling imposed by the gold queries themselves.
5.4 Without a gold query
Grouping candidates by equivalence. A system that samples several candidate queries can group them by (bounded) equivalence and prefer the largest class. This is a semantic self-consistency check that needs neither a gold query nor a test database. Script 03, Part 4, pools each question’s candidates with its gold query:
| question | classes (as bags, ) |
|---|---|
| Q1 | {Q1.2, gold} {Q1.1} |
| Q2 | {Q2.1} {Q2.2} {Q2.3} {gold} |
| Q3 | {Q3.1, Q3.3, gold} {Q3.2} {Q3.4} |
| Q4 | {Q4.2, gold} {Q4.1} |
| Q5 | {Q5.1} {gold} |
What the classes show.
- Rewrites of the right query cluster (Q1, Q3).
- When every candidate makes a different mistake (Q2), the vote abstains.
- Q5 is a tie between the right query and the wrong gold query.
Equivalence says which queries mean the same; deciding which meaning was intended still needs the question, and a person or a specification.
6. Verification in the generation loop (overview)
These notes use verification to judge queries. The same machinery can sit inside generation:
- Filtering. Discard candidates that are equivalent to a known-wrong query, or that violate a specification such as “the result has one row per department”.
- Ranking. Rank candidates by equivalence class, as in §5.4.
- Repair with counterexamples. Show the model the counterexample database and the two results, and ask for a corrected query. A counterexample is a far more precise hint than “wrong”.
- Asking the user. Show the user a tiny database on which two plausible readings differ (ties, empty groups, NULLs), and let them choose. This turns ambiguity into a concrete question.
The loop is CEGIS. Repair with counterexamples is the counterexample-guided inductive synthesis loop of Lecture 20, with a language model as the generator and the bounded checker as the verifier.
7. Summary
-
Execution accuracy compares a generated query with a gold query on one test database. It is optimistic: on this lecture’s benchmark it accepts 11 of 12 candidates, of which only 5 are equivalent (as sets) up to the bound.
-
SQL’s semantics is subtle:
- bags;
- NULL and three-valued logic, where WHERE keeps only TRUE;
- aggregates of no values are NULL;
- unordered ties under ORDER BY … LIMIT.
The reference evaluator matches SQLite on 4,800/4,800 comparisons, and all 11 LIMIT disagreements are ties.
-
Query equivalence is decidable for conjunctive queries under set semantics (NP-complete). It is open for bag containment, and undecidable for full SQL (Trakhtenbrot).
-
Bounded equivalence:
- symbolic tables (presence bits, values, NULL bits, constraints);
- symbolic execution of each operator;
- a “results differ” formula for the solver.
Counterexamples are minimal in rows and validated on SQLite; “equivalent up to ” comes with DRUP proofs.
-
Constraints and bounds shape the answer:
- keys and foreign keys can make queries equivalent;
- row and value bounds can hide differences;
- unsupported SQL must be reported, not approximated.
-
Counterexamples are explanations. They expose wrong generated queries, wrong gold queries, and ambiguous questions, and they can drive repair and ranking.
8. Common pitfalls
- Trusting one test database. Agreement on it is evidence, not equivalence.
- Forgetting NULL.
x > 3 OR x <= 3is not a tautology,= NULLis never TRUE, and a NULL in a NOT IN list empties the result. - ORDER BY … LIMIT 1 for “the maximum”. Ties make it return one arbitrary row.
- COUNT(*) after a LEFT JOIN. Padded rows count as 1; count a column of the right table instead.
- Comparing as sets when the question needs counts, or as bags when it does not. State the semantics.
- Ignoring constraints. Counterexamples that violate keys are not counterexamples; equivalences that rely on keys break without them.
- Reading “equivalent up to ” as “equivalent”. Rows and values are bounded.
9. Exercises
1. (three-valued logic) For a row with bonus NULL and grade ’-’, evaluate NOT (bonus > 3 AND grade = '-'). Is the row returned?
Answer
The evaluation. bonus > 3 is UNKNOWN and grade = '-' is TRUE. UNKNOWN AND TRUE is UNKNOWN, and NOT UNKNOWN is UNKNOWN.
The row is not returned. Both the evaluator and SQLite return no rows.
2. (De Morgan) Are WHERE NOT (bonus > 3 AND grade = '-') and WHERE bonus <= 3 OR grade <> '-' equivalent? Argue in three-valued logic, then check.
Answer
The argument. In Kleene’s logic NOT swaps TRUE and FALSE and keeps UNKNOWN, so still holds. Also, is exactly on non-NULL values, and UNKNOWN on NULL in both forms.
The check. check_equivalence reports “equivalent up to 3 rows”, with and without the schema’s constraints.
3. (a counterexample by hand) Find the smallest database on which SELECT name FROM emp WHERE dept = 1 OR dept <> 1 differs from SELECT name FROM emp.
Answer
The database. One employee with dept NULL. Both comparisons are UNKNOWN, so the first query drops the row. The solver finds exactly this at (dept NULL, everything else 0), and SQLite confirms it.
4. (DISTINCT vs GROUP BY) Are SELECT DISTINCT dept FROM emp and SELECT dept FROM emp GROUP BY dept equivalent as bags? What happens with NULL departments?
Answer
Yes, they are equivalent. DISTINCT treats NULLs as equal for duplicate removal, and GROUP BY puts all NULL keys in one group. Both return one row per distinct value, NULL included.
The check. “Equivalent up to 3 rows”, with and without constraints.
5. (empty input) Do SELECT MAX(salary) FROM emp and SELECT salary FROM emp ORDER BY salary DESC LIMIT 1 differ? Give the counterexample.
Answer
Yes: on the empty table. MAX returns one row containing NULL, and the LIMIT query returns no rows. The solver finds it at , with both tables empty.
Ties do not matter here. Both return the same value, not different rows.
6. (constraints) Show that SELECT COUNT(*) FROM dept d JOIN emp e ON e.dept = d.id equals SELECT COUNT(*) FROM emp WHERE dept IS NOT NULL under the schema’s keys, and give a counterexample without them.
Answer
With the keys. The foreign key makes every non-NULL emp.dept match some department. The primary key makes it match exactly one. So the join has one row per employee with a non-NULL department: “equivalent up to 3 rows”.
Without them. An employee with department 0 and no department 0 is a counterexample: the counts are 0 and 1.
7. (encoding size) With slots per table, how many candidate rows does dept d LEFT JOIN emp e produce in the encoding? How many key comparisons does a GROUP BY over them need?
Answer
The rows. joined rows plus padded rows, in total.
The comparisons. GROUP BY compares every pair: NULL-safe key comparisons, which is for the representatives and memberships. With the bag comparison of two results of rows each, another row comparisons follow. This is why formulas grow polynomially in (376 to 12,390 clauses for on Q2) and why bounded checkers keep small.
8. (programming) Add IN (SELECT ...) for uncorrelated single-column subqueries. Evaluator: membership with SQL’s NULL rules. Encoder: TRUE if some present row of the subquery equals the value, UNKNOWN if none does but some present row is NULL. Check SELECT id FROM emp WHERE dept IN (SELECT id FROM dept) against SELECT id FROM emp WHERE dept IS NOT NULL.
Answer sketch
The encoding. For value and subquery rows :
- TRUE ;
- FALSE .
What to expect. With the foreign key, the two queries are equivalent. Without it, the counterexample is an employee pointing to a missing department.
9. (programming) Implement counterexample-guided repair for Q2. Start from the inner-join candidate. When verification returns a counterexample, apply the first edit from a small list (“JOIN → LEFT JOIN”, “COUNT(*) → COUNT(e.id)”, “GROUP BY d.name → GROUP BY d.id, d.name”) that makes the candidate agree with the gold query on all counterexamples so far. Repeat until equivalent up to 3 rows.
Answer sketch
The loop. Keep the list of counterexample databases. Each candidate edit is first tested on them, which is cheap, then verified.
What to expect. The inner join fails on an empty department. Switching to a LEFT JOIN fixes that, and COUNT(e.id) is already there. Two verification calls suffice. This is CEGIS (Lecture 20) with a fixed space of repairs.
10. Further reading
- R. Klopfenstein, Y. He, A. Tremante, Y. Wang, N. Narodytska, H. Wu, “SpotIt: Evaluating Text-to-SQL Evaluation with Formal Verification”, ICLR 2026 (arXiv:2510.26840).
- R. Klopfenstein, Y. He, A. Tremante, Y. Wang, N. Narodytska, H. Wu, “SpotIt+: Verification-based Text-to-SQL Evaluation with Database Constraints”, arXiv:2603.04334, 2026.
- Y. He, P. Zhao, X. Wang, Y. Wang, “VeriEQL: Bounded Equivalence Verification for Complex SQL Queries with Integrity Constraints”, OOPSLA 2024.
- S. Chu, K. Weitz, A. Cheung, D. Suciu, “Cosette: An Automated Prover for SQL”, CIDR 2017.
- R. Zhong, T. Yu, D. Klein, “Semantic Evaluation for Text-to-SQL with Distilled Test Suites”, EMNLP 2020.
- T. Yu et al., “Spider: A Large-Scale Human-Labeled Dataset for Complex and Cross-Domain Semantic Parsing and Text-to-SQL Task”, EMNLP 2018.
- J. Li et al., “Can LLM Already Serve as a Database Interface? A BIg Bench for Large-Scale Database Grounded Text-to-SQLs” (BIRD), NeurIPS 2023.
- A. K. Chandra, P. M. Merlin, “Optimal Implementation of Conjunctive Queries in Relational Data Bases”, STOC 1977.
- S. Chaudhuri, M. Y. Vardi, “Optimization of Real Conjunctive Queries”, PODS 1993 (bag semantics).
- L. Libkin, Elements of Finite Model Theory, Springer 2004 (Trakhtenbrot’s theorem, query languages).
11. Next lecture
Lecture 20: program synthesis, and the course in review.
- From verifier to synthesizer. Today’s checker answered “do these two queries agree?”. Turned around, a verifier can drive a search: propose a program, ask the solver for a counterexample, learn from it, repeat.
- What the lecture covers. Synthesis as an problem, syntax-guided synthesis, enumeration with observational equivalence, and CEGIS.
- The review. The course ends with a table of every solver built along the way.
See Lecture 20.