T5QL: Taming language models for SQL generation
Paper · 2022 · Samuel David Arcadinho, David Aparicio, Hugo Veiga et al.
Summary
A request such as asking for users sorted by country sounds complete to the person making it. A database needs more detail. The SQL query must identify the table that contains the users, find the relevant country column, and express the requested order. A system can get the wording of SQL right and still refer to a column that the chosen table lacks. T5QL addresses both problems by bringing SQL grammar and the database schema into the process that generates the query. Translating an ordinary-language request into a formal expression of its meaning is a task in semantic parsing.
T5QL uses T5-Base to write a query one token at a time. At each step, a parser determines what can legally follow the text written so far. The generator writes the FROM clause before the SELECT clause in its working representation. That order gives the parser the names of the source tables before it needs to decide which columns can be selected. A search procedure keeps several candidate queries in play, and a separate scorer based on CodeBERT can reassess the finished candidates against the original request. The final choice combines the two scores.
On the Spider development set, the constrained generator reaches roughly 65.7% exact-match accuracy with a single beam, compared with approximately 55.1% for unconstrained T5-Base. At a beam size of 4, the paper reports 69.3% for T5QL, 66.6% for PICARD-Base, and 75.5% for PICARD-3B. The authors also find that putting tables before columns improves accuracy on Spider-SSP even without the decoder's restrictions, and that adding those restrictions improves both reported measures on the conversational CoSQL development set. On the Spider test set, T5QL records 65.9% exact match and 66.8% execution match.
The results distinguish generating a plausible query from recognizing the right query among several plausible ones. At a beam size of 8, the constrained generator's shortlist contains an exact match frequently enough that a selector with access to the reference answer could reach 78.2% on Spider development. The trained scorer recovers only part of that opportunity, and it performs worse on its own than when combined with the generator. The validity claim also has a specific boundary. The parser guards each continuation, but the authors show that repeated, individually legal continuations can hit a length limit and leave the query unfinished.
Deep dive: T5QL: Taming language models for SQL generation
T5QL turns plain-language questions into SQL by constraining what T5 can generate and reranking candidates to improve accuracy with T5-Base. · about 34 minutes to read
The problem and its context
What a plain-language request leaves implicit
The practical goal of text-to-SQL is to let people describe the data they need in ordinary language and receive a query they can use to retrieve it. The paper motivates this partly through software development. A developer can know how to write the application code that needs a result and have less experience with the SQL required to obtain it. The need arises again when people are exploring data and want to ask successive questions without writing a fresh query each time. In both situations, the request expresses an intent that has to be mapped onto a particular database.
The schema is the part of the database description that tells the system what tables and columns exist. It gives the same question a different interpretation in different databases. A name such as country can appear in more than one table, and the fact that the name appears somewhere in a schema does little to resolve which use is appropriate. The generator has to pick a source, decide whether it needs information from additional tables, and refer to columns available through those choices. With a wider schema, more interpretations can look superficially plausible. More complex requests can also require longer SQL, giving the generator more decisions to make.
This creates several distinct requirements for a successful answer. SQL has rules about which clauses and expressions can appear together. The schema places another set of conditions on those expressions, such as whether a qualified column belongs to the table being referenced. The user's intent adds a further requirement. A query can obey the language rules and use only available columns while choosing the wrong grouping or ordering. T5QL lets the decoder enforce some of these requirements directly and leaves the choice among permitted queries to learned scores.
Getting suitable training examples is another difficulty identified in the paper. Each example needs a natural-language request paired with its SQL interpretation. Creating and checking those pairs takes time and requires people who can write SQL. A method can therefore benefit from starting with a system already trained on a broader text task, but it still needs benchmark data that tests whether its SQL predictions transfer. The paper considers transfer across databases, across combinations of query structures, and into conversations. Each setting places a different burden on the mapping from a request to a query.
What earlier approaches supplied
The authors situate text-to-SQL alongside earlier forms of automatic program generation. Some SQL synthesis methods take fragments of code as input. Others search for a program that agrees with examples of inputs and outputs. Both approaches ask the user to prepare material that can be difficult to supply. Code fragments may be unavailable, and a collection of examples can take considerable effort to assemble. A natural-language interface asks the user for a different kind of specification, closer to how they would describe a database request to another person.
The paper describes neural code generation as a way to avoid some of the computational complexity associated with traditional synthesis at generation time. It also distinguishes code completion from generation based on natural language. A completion system can rely on program text already written by a developer. A text-to-SQL system receives a request whose connection to code is largely implicit. It has to recover the intended decision about tables, columns, and clauses before the output has anything resembling the structure of the final program. The paper cites earlier work on combining learned prediction with program structure, including Neuro-Symbolic Program Synthesis.
An alternative discussed in the paper is to have the system predict an intermediate representation closer to the user's wording and translate that representation into SQL afterwards. The authors discuss this direction in connection with RAT-SQL and derivatives of it. An intermediate language can simplify the prediction problem, but its coverage matters. When a reference query requires a construction outside that language, no prediction in the intermediate language can yield it. The authors also point out that a custom decoder can make it harder to inherit the generation capabilities of a pretrained text generator. Their discussion places these concerns alongside work on RAT-SQL and UnifiedSKG.
T5 provides a way to use the same text-to-text framework for different tasks. A question and its schema can be represented as input text, and a query can be represented as output text. The paper describes Shaw and colleagues as early adopters of this approach on Spider. Their work examined how a parser copes with unfamiliar combinations of structures and variations in the input. The T5 approach could generate promising queries and could also produce syntactically incorrect ones, which motivated stronger control over generation. The paper draws on the original work on T5 and on compositional generalization in semantic parsing.
A general text generator assigns scores to possible next tokens using the text it has received and produced so far. As the authors put the problem, those scores on their own do not establish that the next token has any legal role in the target language. Training can make SQL-like continuations likely without turning the generator into a parser. T5QL is concerned with this gap between a statistical preference and a rule the output has to satisfy. The paper relates that broader issue to Provable Limitations of Acquiring Meaning from Ungrounded Form.
Constraining the search and reconsidering its winner
The paper describes earlier approaches that intervene during decoding. Xiao and colleagues applied grammatical restrictions and investigated using them at inference. Poesia and colleagues coupled constrained generation with example selection for few-shot prediction. PICARD, the strongest Spider system cited by the authors at the time, used incremental checks during T5 decoding. It could remove branches whose continuations failed those checks. T5QL asks what happens when the decoder works forward from a description of the possible continuations at each step. This distinction matters when the generator's preferred continuations fall outside the allowed set.
The authors also ask whether the strongest candidate according to the generator should automatically become the answer. They draw on code-generation work that reported gains from reassessing candidates and on semantic-parsing work that used a scorer to select candidates in question answering over knowledge graphs. The paper also discusses a text-generation study that scored entire continuations for their fit with an input prefix. This prior work motivates using a second view of a candidate after its full structure is available. The code-generation precedent is discussed in Evaluating Large Language Models Trained on Code.
These ideas address different sources of error. The parser can keep an invalid column choice out of the search. It has no direct evidence that a choice from the remaining columns captures the question. A separate scorer can see a complete candidate and assess its correspondence to the request, but it depends on the generator to offer that candidate in the first place. The paper uses this division to investigate whether specialized components can improve the results of T5-Base without requiring the much larger generator used by the leading comparison system.
The method, step by step
From the question and schema to a shortlist
T5QL receives a natural-language question and the schema of the database being queried. The schema identifies the tables and the columns belonging to them. For the input to T5, the authors serialize this information as text and append it to the request. The generator can therefore use both the phrasing of the question and the names available in the schema. The constrained decoder also uses the schema in another form, as a source of rules about which identifiers it may permit.
The example in the architecture diagram asks for users in country order. The toy schema includes User and Account. The generator starts with empty output and extends it a token at a time. If the current output is from User, the decoder can allow a continuation that starts a selection, introduces an alias, or adds a join. It can rule out a fresh FROM immediately after the table in that same position. The example shows what the decoder needs from the grammar at any moment. It needs to know what can follow the current text while still leaving a path toward a complete query.
T5 supplies preferences among those permitted continuations. Beam search keeps a limited set of partial candidates alive as the query grows. The beam size controls how many alternatives the search can retain. A narrow search can commit early to a table or clause that looks promising at the time. A wider search can preserve an alternative long enough for later parts of the query to make it competitive. The finished candidates form the shortlist that the ranker receives.
How T5QL generates and selects a SQL query
The steps in order.
The middle steps repeat for the partial queries under consideration. A branch that chooses User has a different set of eligible column references from a branch that chooses Account or brings both tables into the query. The decoder updates those choices as each partial query develops. The ranker enters once generation has produced candidates. Its role is to order the candidates it receives.
Why the table comes before the column
Ordinary SQL places SELECT before FROM. In T5QL's generation order, FROM comes first. This is a practical change to the order in which the generator commits to decisions. When the parser reaches a selected expression, it can already know which tables supply the available columns. The system can use that knowledge to limit the next token as it generates the expression.
Consider a partial query that has chosen only User and is about to specify what to return. The grammar and the schema together can now admit references such as user.id and user.name. They can withhold account.country at that point because the source clause has introduced no account table. The user and account columns can both be present in the schema as a whole. The partial query determines which of those columns are available in the current context.
The inversion also changes what T5 has to predict first. Under conventional order, it has to propose a selected expression while the corresponding table is still absent from the output prefix. It can draw on the input schema, but a choice of source has yet to become part of the generated sequence. With FROM first, the output itself carries that decision when T5 begins writing the selected expressions. The experiments on Spider-SSP examine the effect of this order even when the decoder is free to generate continuations without the parser's filter. The paper relates the representation to earlier work on bridging textual and tabular data for text-to-SQL.
Aliases introduce another dependency. When a query assigns a short name to a table, later references can use that short name as a qualifier. The decoder maintains the link between the alias and its original table so that it can check which columns the alias can name. The authors describe adding an expression for the alias-qualified column and an expression using the original table name. As generation proceeds, the filter uses the parser state to determine which references are admissible.
This division lets the rules for the language and the rules for the database do different jobs. A general rule can say that a column can occur in a certain expression. A rule built for the current schema can enumerate actual column names. The decoder can then narrow the schema-wide list using the tables introduced within the current query. The example of account.country illustrates why each step matters. The name exists and fits grammatically in a selected expression, yet the particular FROM clause gives the parser a reason to exclude it.
The grammar and the next-token decision
The authors express the supported SQL structures as a context-free grammar. A grammar of this kind describes how larger expressions can be constructed from smaller ones. In T5QL, the top-level SQL expression can be a query, or expressions can be joined using UNION, INTERSECT, or EXCEPT. A query in the generation format begins with a source clause and a selection. The grammar shown in the paper also allows optional filtering, grouping, conditions on groups, ordering, and a result limit.
The general grammar covers retrieval queries. For a particular question and database, the authors augment it with productions for valid table names and valid column names. A production lists forms that a named part of the grammar can take. The table-name production can offer the table identifiers in the current schema. The column-name production provides qualified identifiers from the same schema. The context-sensitive filtering step then uses the tables and aliases found in the query so far. The grammar is context-free in its formulation, while the decoder also consults facts specific to the current partial query.
T5QL passes the grammar to Lark. The paper chooses this parser partly for its lookahead capability, which provides a way to ask what kinds of SQL symbols can follow a parsable prefix. That question arises during each generation step. The decoder has to answer it even when the text produced so far ends partway through a SQL keyword or identifier. This is where the units used by the grammar and those used by T5 need to be reconciled.
A parser reasons with units such as keywords and identifiers. The generator chooses tokens from its own vocabulary, so a sequence of its tokens can spell a single parser-level item. If the partial output has stopped within such an item, the parser cannot simply treat the entire current string as a completed sequence of SQL symbols. The decoder works from the longest part it can parse and uses the rest of the generated text to narrow which token-level continuations fit. This alignment is the function of tokenization in the algorithm.
The procedure in the paper calls the current generated text P and its longest parsable prefix P∗. It obtains the parser state S for that prefix. Using lookahead, it gets N, the SQL-level symbols that the grammar allows next in that state. It then applies its context checks to obtain the filtered set N∗. At this stage, a symbol that would fit the grammatical structure can be removed because it refers to a column outside the tables available to the query.
For each item n in N∗, the decoder appends the item to P∗, making a candidate extension the algorithm calls C. It tokenizes C as Cₜ and adds the resulting token sequence to T, the trie. A trie stores sequences by sharing their common beginnings, which lets the decoder query the continuations of a token prefix. The algorithm tokenizes the full current output P as Pₜ, looks up that sequence in the trie, and retrieves the immediate children of its position. Those children are the tokens the generator can choose next.
Tokenizing the complete candidate extension keeps the parser's advice aligned with the actual sequence on which T5 is operating. Suppose the grammar allows a qualified column name and the generator has emitted part of it. The continuation must fit both the set of whole column names allowed by the parser and the partial spelling already present. The trie lookup combines those conditions. An eligible next token lies on a path consistent with the previously emitted tokens and at least one of the proposed parser-level extensions.
At the next decoding step, the output is longer and the procedure runs again. Once a grammatical item has been completed, the longest parsable prefix can extend farther. Its parser state can then expose a new set of possibilities. Branches in the beam can reach different parser states and carry different table selections. This is how the decoder applies structural constraints throughout the search rather than inspecting only the finished query.
How the second scorer learns what to prefer
The ranker is trained to recognize whether a complete candidate SQL query corresponds to a natural-language request. The authors use a trained T5 generator to prepare examples of the mistakes the ranker is likely to encounter. For each training question and schema, they run beam search to produce 16 queries. They retain the 12 closest to the reference according to tree edit distance, a structural measure explained below. The idea is to show the ranker plausible mistakes that resemble the right query and hence may require attention to the specific request.
Some generated sets omit the correct SQL. When it is missing from the retained group, the authors replace the member with the greatest tree edit distance with the reference query. The result gives the ranker a positive example even for an input where generation missed it. The authors also select additional queries from the training data for the same database, again using tree edit distance. This yields 14 SQL candidates per training input. Sharing the database makes those added queries relevant to the vocabulary and schema of the request, while structural proximity makes them useful candidates to discriminate.
The scorer is a fine-tuned CodeBERT cross-encoder. A cross-encoder receives the request and a candidate query together and produces a score for that pair. The full candidate can thus inform how the scorer reads the question, and the question can inform how it interprets a particular clause or literal in the candidate. The training task asks whether the members of the pair correspond. CodeBERT supplies the starting point for this fine-tuning.
The paper also appends identified terminal values to the natural-language input seen by the ranker. In its example, the request concerns people from France, and France is appended after a separator. A terminal value is a literal the SQL can use, such as a country name in a filter. The appended value makes that part of the request readily visible when the scorer compares it with a query. This matters because a query can get its source, projection, and filter structure right while using the wrong value in the condition.
At inference, the ranker receives a generator shortlist for a new question. The reference query is unavailable, so the training-time step of inserting it has no counterpart in prediction. The ranker has to make its decision using the candidates the generator actually reached. This dependence is central to the paper's evaluation. A shortlist can provide the right answer and still produce a wrong prediction if the scorer selects poorly. When the shortlist omits a matching candidate, changing its order leaves that omission in place.
Scoring complete candidates
T5QL combines a length-normalized generator score with the ranker's score in log space. The equation gives the score used to compare completed candidates.
(1 ÷ t) × log p(y | x) + λ × log p(x, y)
Here x is the input associated with the question and y is a candidate SQL query. In p(y | x), the vertical bar means that the generator assigns a probability to y given x, including the schema supplied with the request. In p(x, y), the comma denotes the pairing assessed by the ranker, whose output is the estimated probability that the SQL corresponds to the request. The paper uses t for the length of the SQL, and 1 ÷ t is the factor that normalizes the generator's log probability by length. log takes the logarithm of its probability argument. λ is the tunable weight on the ranker term, × denotes multiplication, and + adds the terms to produce the final score.
Length normalization matters because the generator accumulates its score while producing a sequence. The ranker assigns its probability to a complete pair. Scaling the generator's log probability by query length makes the terms more suitable for combination when comparing queries of different lengths. The weight then controls how much a change in the ranker's judgment affects the final ordering. A candidate favored by the generator can keep its advantage, or an alternative can move ahead when its ranker score is strong enough under the chosen weight.
How query comparisons inform training and evaluation
The paper distinguishes structural agreement from agreement on the data returned. Exact match, abbreviated EM, compares a generated query with the reference for SQL-form equivalence under the evaluation procedure. Execution match, abbreviated EX, compares the results of running the queries. The distinction matters for both interpretation and cost. An evaluator can compare forms without querying a database, while execution requires access to the data. A result-based comparison can also recognize agreement where the reference and the prediction express the operation in different ways.
The paper discusses partial matches as another way to inspect an error. A partial comparison can credit agreement on the source clause even when a selection or filter is wrong. That identifies the part of the query where the error lies. For sampling ranker examples, the authors need a more graded structural comparison. A candidate with the right clauses and a wrong column is a different kind of near miss from a candidate that would require rewriting much of the query. Tree edit distance gives a way to order candidates by this sort of structural proximity.
To compute the distance, the authors first normalize the queries into a canonical representation. The examples include standardizing a list's order and rewriting join direction into a consistent form. They represent the normalized queries as trees and compare those trees using APTED. Tree edit distance reflects the cost of edits needed to turn one tree into the other. The authors adjust the comparison costs so that operations they view as comparable receive comparable costs. Their example assigns the same removal cost to a literal and a column name. This metric guides the choice of near misses during training, while the ranker learns to score question–query pairs directly.
Experiments and results
What the benchmarks ask the system to do
Spider tests cross-database generation. The paper gives its size as 10,181 pairs of requests and schemas across 200 schemas. The split holds out schemas from training, so the test of generalization includes working with databases whose structure the generator did not see during training. The schema still accompanies the request at prediction time. The experiment asks whether the system can use that information to transfer what it has learned about SQL generation.
For Spider, the paper distinguishes an exact-match track that leaves out terminal values and an execution track that includes them. T5QL generates complete queries, including literal values, so these metrics expose different aspects of the output. A structural match can give credit for finding the correct form of a condition. The execution comparison with values included asks whether the resulting query returns the reference result on the database. The paper's development-set comparisons focus chiefly on exact match, and it reports both measures for its final Spider test run.
Spider-SSP rearranges Spider examples to put more emphasis on compositional generalization. A system may recognize the ingredients of a query and still have trouble putting them together in a combination that was uncommon or absent during training. The paper presents four partitioning methods in a table: random, by template, by source length, and by Target Maximum Compound Divergence (TMCD). The random split provides a reference point for the more deliberately challenging arrangements. The length split tests a change in the length distribution of the source questions. TMCD is designed around the divergence of combinations in the target, making it relevant to whether familiar ingredients transfer to unfamiliar combinations.
CoSQL changes the unit of use. A conversation represents a person exploring data through a succession of questions about the same database. The paper describes 4,298 interactions on the same 200 schemas as Spider. It reports exact-match measures with terminal values omitted. Question match, or QM, scores individual questions. Interaction match, or IM, requires the questions associated with a whole interaction to be answered correctly. A system can answer much of a conversation correctly and still lose credit under the interaction measure because a turn went wrong.
Training conditions and comparisons
The main constrained-decoding comparison uses T5-Base on both sides. The authors describe using the same training configuration for the unconstrained baseline and the constrained generator without the ranker. They append a text serialization of the schema to the input in both cases. This gives each generator the schema to read, while the constrained system also uses it to restrict what the search may emit. The authors evaluate beam sizes of 1, 2, 4, and 8.
The generator runs use a maximum of 512 training epochs, a mini-batch size of 5, and 205 gradient accumulation steps. Accumulation lets updates use gradients gathered across successive mini-batches. The authors report a learning rate of 1e −4 and use Adafactor with epsilon set to 1e −6. They give a batch size of 1025 for their configuration and say this worked better in their experiments than the 2048 setting reported for the comparison they followed. They ran the experiments on an AWS G4DN Extra Large machine with an NVIDIA T4 Tensor Core GPU and 4 CPU cores. The paper made the code available through its public CodaLab worksheet.
The CodeBERT ranker has a separate training procedure. The authors fine-tune it for 50,000 training steps with a batch size of 32 and 1 gradient accumulation step. They report a learning rate of 1e −3, use AdamW with weight decay of 1e −2, and use a linear schedule with warmup over 1% of the steps. Their weight search selects λ = 2e −2 for combining the scores. These settings apply to the scorer trained on candidate pairs, while the generator settings apply to the production of SQL sequences.
PICARD provides external points of comparison. Where the paper compares development-set results using database content, the cited PICARD numbers are for a beam size of 4. The paper draws horizontal reference lines for those settings in plots that vary T5QL's beam width. Those lines refer back to the same reported PICARD runs. They give a reference level against which T5QL's curve can be read, while the comparison at a common reported beam width is the one at 4.
Spider exact match and execution match
The single-beam experiment gives a direct view of the constrained generator. With T5-Base and unrestricted decoding, the paper reports approximately 55.1% EM on Spider development. With constrained decoding and the ranker omitted, T5QL reaches roughly 65.7% EM under the same beam setting. The authors report a gain of approximately 10.6pp for this comparison. As they widen the beam for the unconstrained baseline, they report no improvement. The constrained generator reaches roughly 67.6% with 2 beams and approximately 68% with 4 beams. Its selected answer declines in accuracy at the widest tested setting when the ranker is omitted.
The paper's main comparison at the common beam width puts T5QL alongside both sizes of PICARD. The T5-Base comparison is particularly informative because it holds the named generator size fixed across the methods. PICARD-3B shows the accuracy the cited larger system achieves in the same reported beam setting. These are development-set exact-match results.
Spider development exact-match accuracy with a beam size of 4
T5QL leads the comparison between systems using T5-Base, while PICARD-3B achieves the highest accuracy overall.
The numbers
| System or setting | exact match % |
|---|---|
| PICARD-Base | 66.6 |
| T5QL using T5-Base (this paper) | 69.3 |
| PICARD-3B | 75.5 |
The 69.3% result shows that the authors can improve the reported outcome with T5-Base in this comparison. The highest exact match in the chart belongs to PICARD-3B. The question posed by the paper is whether a small generator can recover some of that performance through the choice of output representation, constrained generation, and a separate ranker. The comparison gives an observed accuracy for that design. It does not isolate a contribution from each component, which is the purpose of the controlled comparisons.
Spider's test set provides a final check on a different split. The paper reports 66.8% execution match and 65.9% exact match for a run of T5QL. The execution result refers to the returned data and the exact-match result to the query comparison. The paper places these results among the top-10 at the time for execution match and at 22nd for exact match. These rankings describe two leaderboard views with different criteria. Accuracy from the development plot and these test outcomes belong to their respective splits.
Spider-SSP and changes in query composition
The Spider-SSP comparison includes T5-Base and T5-3B in conventional SELECT-first order. The T5QL variants generate FROM first, and one variant does so with constrained decoding disabled. The additional variant matters because reversing clause order is itself a change to the learning and generation problem. The comparison can ask how much the representation achieves before the decoder begins enforcing it.
On the random split, exact-match accuracy is 76.5 for conventional T5-Base, 84.7 for the unconstrained FROM-first variant, 85.7 for T5QL-Base, and 85.6 for conventional T5-3B. On the template split, the scores in that same system order are 45.3, 58.3, 61.1, and 64.8. The length split gives 42.5, 50.6, 54.4, and 56.7. These are the paper's Spider-SSP split results. The table identifies each by split instead of giving a separate development or test designation for the values.
On TMCD, the gap between the conventional and FROM-first variants of the base generator is especially evident. T5QL-Base with constraints also improves on the unconstrained FROM-first variant. T5-3B remains ahead on this split. The four results put the effects of output order, constraints, and generator size in view, although the larger generator uses its own conventional-order configuration.
Exact-match accuracy on the Spider-SSP TMCD split
Putting sources first improves the base generator's score, and applying constraints brings it closer to T5-3B.
The numbers
| System or setting | exact match % |
|---|---|
| T5-Base, SELECT first | 42.3 |
| T5QL-Base without constrained decoding, FROM first | 64.4 |
| T5QL-Base with constrained decoding, FROM first (this paper) | 65.9 |
| T5-3B, SELECT first | 69.6 |
The strongest configuration depends on the split. T5QL-Base has the highest value in the random column, while the T5-3B baseline is ahead on template, length, and TMCD. The relative positions show why a single split gives an incomplete picture of performance. The same choice of representation and decoder can improve a base generator consistently while leaving a substantial challenge in the splits designed to demand more generalization.
CoSQL questions and interactions
On the CoSQL development set, the unconstrained T5QL-Base variant obtains 42.8 QM and 14.8 IM. Adding constrained decoding raises the scores to 50.7 QM and 20.3 IM. PICARD-3B obtains 56.9 QM and 24.2 IM. The comparison with the unconstrained variant shows improvement at the question and interaction levels. The comparison with PICARD-3B places that improvement in the context of the stronger reported system.
Interaction match on the CoSQL development set
Constrained decoding improves the share of conversations with every query correct, with PICARD-3B still leading.
The numbers
| System or setting | interaction match % |
|---|---|
| T5QL-Base without constrained decoding | 14.8 |
| T5QL-Base with constrained decoding (this paper) | 20.3 |
| PICARD-3B | 24.2 |
A full-interaction score is especially relevant to exploration over successive turns. A user can receive several correct answers and still be led away from the intended line of inquiry by a wrong SQL query. The interaction numbers show how often the system meets the stricter benchmark condition across the conversation. Together with question match, they demonstrate that the improvement from constraints appears under both ways of scoring the conversational task.
How much the shortlist contains
The Spider development experiments also ask what the generator has found before its final choice is made. The authors use accuracy at beam width to count an example as successful when any candidate in the shortlist is an exact match. They interpret this measure as an oracle ranker. An oracle in this experiment knows which candidate matches the reference and selects it whenever it is available. This measures the potential of the shortlist under perfect selection with the same exact-match criterion.
At 8 beams, the oracle reaches 78.2% EM. It exceeds the reported PICARD-3B development result, but it uses knowledge unavailable to a real selector and is assessed at a different beam width from the cited PICARD run. The useful reading of this number is that T5-Base with constrained search already generates a matching candidate for many questions its scoring procedure gets wrong. The practical system then has room to improve even with the generator held fixed.
The trained ranker is substantially below that ceiling. The ranking results discussion reports an improvement from 67.9% to 69.3% EM when the generator's score is combined with the added score. The introduction separately gives 67.9% to 69.6% as its example at 8 beams. Those are the paper's two presentations of the ranking gain. The 69.3% value is also the explicit result attached to 4 beams in the main comparison. The direction of the reported benefit is consistent, while the two passages give different endpoints for the ranking comparison.
What the ablations show
The decoder changes the outcome early in search
The single-beam comparison removes the separate ranker and uses T5-Base with the same reported training configuration. At that width, the system retains only its leading continuation at each step. The larger score for the constrained version therefore reflects an intervention before candidate selection by CodeBERT. The decoder has ruled out some continuations and allowed the learned score to choose among the remaining ones. This is evidence that the gain does not depend on asking a second scorer to repair the ordering of a long candidate list.
The wider-beam results show why retaining more alternatives is a separate issue. The unconstrained T5-Base baseline does not gain from additional beams in the reported comparison. The constrained generator improves at the intermediate widths, then loses some top-choice accuracy at the widest width. At that same wide setting, the oracle can recover an exact match much more often than the learned scores can put it first. Search width affects what is available for selection, and the score determines whether the system takes advantage of that availability.
This comparison treats constrained decoding as a package. The package uses the grammar's lookahead, the schema-dependent filtering, and the alignment to the generator's token vocabulary. A gain in exact match under that configuration establishes the effect of using the package in the reported setup. To understand why a particular query improves, the appendix examines an identifier error that the schema filter can prevent.
Clause order helps even without enforcement
On Spider-SSP, the authors compare conventional T5-Base with the FROM-first T5QL variant that omits constrained decoding and ranking. The FROM-first variant scores higher across the reported splits. The TMCD comparison is especially telling because it tests unfamiliar combinations of target structures. The gain there shows that the order of the output sequence can matter even when the generator can still make a grammatically illegal choice or refer to an unavailable column. In this experiment, the sequence itself gives the generator an earlier representation of its source-table decision.
The next comparison holds FROM-first order in place and adds constrained decoding. Accuracy improves again on every reported Spider-SSP split. The part attributed to decoding is additional to the improvement already seen from the changed order. It is also smaller than the order change on TMCD. These results give distinct empirical roles to decisions that work together in the method. The representation arranges the SQL decisions in a sequence that makes the source available earlier. The filter uses the source to enforce a subset of the consequences of that decision.
The conventional T5-3B comparison provides another reference for the effect of scale. T5QL-Base exceeds it on the random split and remains below it on the targeted splits. The order and the restrictions thus improve the base generator's performance on the compositional tests, while the more demanding splits also retain a measurable challenge for the smaller configuration. The paper presents this as a narrowing of the gap on those tasks.
The ranker helps when its score is combined with the generator's
The authors compare selection by the generator score, selection by the ranker score, and selection by their weighted combination. The combination is the strongest of these choices in the reported Spider development experiment. The ranker alone falls below the generator-only configuration, with the problem becoming more visible when the search retains more candidates. The training data uses near misses to teach the scorer fine distinctions, but the score comparison shows that it still has difficulty identifying the correct SQL among the alternatives.
Each scorer sees the candidate from a different position. The generator has estimated the sequence while extending it in the context of the request and schema. The ranker sees the whole candidate with the request and can judge the pairing directly. A candidate can be plausible as a generated sequence and still miss a condition that becomes conspicuous in a full comparison. Conversely, a structurally plausible near miss can look compelling to the ranker even though the generator has stronger evidence for another query. The combined score can preserve information from both judgments.
The oracle makes the remaining ranking error visible. If a candidate list contains a matching query, the oracle always finds it. A learned scorer serving a new question has to infer which differences matter. A choice between two valid queries can turn on a join condition, the column used for grouping, or the relation between the literal and the question. The gap between trained selection and the oracle measures how often the system could have succeeded with its existing candidates under the benchmark's rule for a match.
The larger-generator comparison in the appendix tests whether the same benefit carries over to T5-Large. On Spider development, the paper reports that a fully configured T5QL-Base is ahead of unconstrained T5-Large at the middle beam widths of 2 and 4. Constraining T5-Large improves its performance substantially. Adding the ranker to the constrained larger generator yields no observed improvement in that comparison. Thus the paper has examples of decoding gains at both generator sizes, while its evidence for a ranking gain comes from the base setting.
Parsing failures reveal what the constraints enforce
The appendix checks parsability directly on Spider development. For T5QL-Base, the authors examine beams of 1, 2, 4, and 8 and report that the leading beam is always parsable in their checks when the beam width exceeds 1. They also observe unfinished, invalid candidates, particularly among lower-scored beams at wider search. These observations refer to which candidates are returned or examined at particular positions. Considering only the leading beam yields a stronger empirical validity result than considering the entire set of generated candidates.
The failure case comes from a query over a stadium table. While constructing its ordering expression, the generator repeatedly opens nested aggregation calls. Each local continuation can satisfy the grammar's expectations. The stopping limit eventually truncates the unfinished expression, leaving a query the parser cannot accept as complete. The example locates the problem at the transition from valid partial output to a valid final output. Permission to extend a prefix conveys that it has a possible completion. It does not ensure the generator will take that path before hitting its length limit.
The authors also compare base and large variants with the same beam width of 4, looking at the leading beam on Spider development. Without constrained decoding, T5QL-Base produces approximately 20% invalid queries and T5QL-Large approximately 5%. With the decoder enabled, the leading outputs in both configurations are parsable in that evaluation. Increasing the size of the unconstrained generator helps with parsability on these examples. The parser supplies another way to improve it, using explicit rules rather than depending entirely on patterns the generator has learned.
The identifier example from the appendix shows a different failure. An unconstrained query joining singer and singer_in_concert refers to song_id, which the schema does not provide in the relevant context. It then uses that reference again for grouping. With the schema constraints enabled, the prediction uses singer_id in the join and the grouping, and the resulting query is correct for that example. The example shows a concrete route from schema checking to better exact match. Preventing an unavailable identifier from entering a partial query can change several clauses by changing the candidate the search follows. The appendix provides an illustration of that mechanism instead of a count of how frequently the same correction happens.
Limitations
Limits identified by the authors
The grammar covers queries that retrieve data through SELECT, including the forms of combination and subordinate queries supported by the grammar. The paper's evidence therefore concerns this portion of SQL. The decoder checks syntax and selected relationships between identifiers and the current source tables. The authors also identify checks that they could add, including foreign-key restrictions for joins and type restrictions on conditions. For instance, the grammar and identifier checks can permit a condition involving an existing column even when the comparison is unsuitable for the column's type.
The paper sometimes states the validity claim broadly, while its introduction and appendix supply an exception. The repeated aggregate expression can remain compatible with the grammar at each step and still be returned incomplete after it reaches the length cap. The positive empirical claim is that the leading output was parsable in the reported Spider development checks at the specified beam settings. The strongest claim supported by the algorithm itself concerns the restrictions it applies at each next-token step. A complete valid answer additionally depends on how generation terminates.
The authors emphasize the gap between the learned ranker and the oracle. The ranker's improvement with T5-Base leaves many examples where the right query is present and the system chooses another. The larger-generator comparison yields no observed improvement from its ranker. They also omit a T5QL configuration using T5-3B, citing the paper's emphasis on smaller components and the time and expense of running the larger generator. Accordingly, their experiments leave open how much the full architecture would change the results of that generator.
The motivation for using smaller components is partly practical. The authors choose a ranker comparable in size to the generator so that it can fit on the same class of hardware in their setting. The paper reports the machine used, but its benchmark results measure prediction, parsing, and candidate selection. They do not quantify end-to-end inference cost, training cost, or latency at different beam widths. The time spent checking prefixes and scoring multiple candidates also belongs to the cost of the system, so the hardware and generator-size descriptions do not establish the size of any deployment savings.
Limits visible in the evaluation
The comparisons separate different kinds of success only to the extent allowed by the metrics. A parsable query can use the wrong valid column or return the wrong grouping. Exact match compares the query to a particular reference under the benchmark's equivalence rules. Execution match compares returned results on the database used for evaluation. Agreement on that data leaves open how the queries would behave on other contents. The paper's exact-match comparisons without values also leave the full reliability of literal selection to other evidence, such as the reported test execution match.
The oracle ceiling has a narrow interpretation. It depends on the generator, beam width, dataset split, candidate lists, and criterion used to count a match. It quantifies how much an ideal selector could recover from those lists. It cannot say whether those successful candidates are distinguishable with the features available to CodeBERT. At the same time, a query absent from the list represents a generation failure for any selector limited to that list. A future increase in shortlist accuracy and a future increase in final prediction accuracy would establish different improvements.
The controlled comparisons also leave some ingredients unresolved. Spider-SSP provides a comparison of clause order with constraints disabled and a further comparison with constraints applied. The appendix describes a schema check's effect on a particular query. There is no aggregate breakdown that assigns a share of the Spider improvement to lookahead, alias bookkeeping, column filtering, or another part of the decoder. Likewise, the ranking experiment compares scoring rules, but it does not vary the near-miss sampling procedure independently. The decoding and ranking packages have measured effects, and the effects of many of their internal choices remain undetermined.
The benchmark scope bounds the generalization claims. Spider holds out database schemas. Spider-SSP reorganizes examples from Spider to examine other kinds of generalization. CoSQL uses conversations on the same schema collection as Spider. These are distinct evaluation conditions, though they do not establish coverage of arbitrary SQL forms, conversational behavior, or database environments. In CoSQL, improved question and interaction matches establish gains under those scoring conditions. An analysis of particular conversational dependencies would be needed to say which kinds of follow-up the system handles better.
Finally, the paper gives accuracy comparisons with several different denominators and settings for its introductory claims. The abstract describes an improvement of approximately 13pp without tying that number there to a specific split, beam width, and baseline. The body provides more precisely labeled comparisons, including the Spider development results against unconstrained T5-Base and PICARD-Base. The introduction and the ranking results discussion also give different endpoints for the reranking example. Those differences in reporting make the named settings and the individually stated results more informative than a single headline gain.
What came after
PExA: Parallel Exploration Agent for Complex Text-to-SQL cites T5QL and takes up complex text-to-SQL through parallel exploration. Its title places exploration within an agent. In T5QL, the documented source of alternatives is beam search over one generator's constrained token predictions. A separate scorer then chooses among the finished queries. Both descriptions concern exploring alternatives in text-to-SQL, at different levels of the process.
The citation establishes a connection between the papers. It leaves open whether PExA reuses the FROM-first query representation, grammar-guided token filtering, or the CodeBERT reranker. The documented connection is the question of what to do when a request admits several plausible routes to SQL. T5QL measures the value of keeping alternatives available by comparing the query its scores actually choose with the best answer its shortlist contains. PExA's title places parallel exploration at the center of that later work on complex queries.
Cite
Cite as Samuel David Arcadinho, David Aparicio, Hugo Veiga and Antonio Alegria. 2022. T5QL: Taming language models for SQL generation. Proceedings of the Second Workshop on Natural Language Generation, Evaluation, and Metrics (GEM).
@inproceedings{arcadinho2022t5ql,
title = {{T5QL: Taming language models for SQL generation}},
author = {Samuel David Arcadinho, David Aparicio, Hugo Veiga and Antonio Alegria},
booktitle = {Proceedings of the Second Workshop on Natural Language Generation, Evaluation, and Metrics (GEM)},
year = {2022},
doi = {10.18653/v1/2022.gem-1.23},
url = {https://doi.org/10.18653/v1/2022.gem-1.23}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/arcadinho-2022-t5ql-taming-language-models-sql/