Skip to content

SQL-BLEU

SqlBleu (load("sql_bleu"), compute_sql_bleu, sentence_sql_bleu) measures syntactic and structural similarity between predicted and reference SQL queries using AST-canonicalized n-gram overlap, adapting Chen et al. (EMNLP-IJCNLP 2019) onto sqlglot ASTs.

Reference: Fuxiang Chen, Seung-won Hwang, Jaegul Choo, Jung-Woo Ha, and Sunghun Kim (2019). NL2pSQL: Generating Pseudo-SQL Queries from Under-Specified Natural Language Questions. EMNLP-IJCNLP 2019, pages 2603–2613. DOI: 10.18653/v1/D19-1262.


Mathematical Formulation

Given tokenized canonical predictions and reference queries up to order \(K\) (max_order, default 4), SQL-BLEU computes clipped n-gram precision \(p_n\) aggregated across all scored examples, where \(\text{Count}_{\text{clip}}(i, n)\) is the number of clipped \(n\)-gram matches and \(\text{Count}(i, n)\) is the total number of candidate \(n\)-grams on example \(i\):

\[ p_n = \begin{cases} \dfrac{\sum_i \text{Count}_{\text{clip}}(i, n)}{\sum_i \text{Count}(i, n)} & \text{if } \text{smooth} = \text{False} \\[1em] \dfrac{1 + \sum_i \text{Count}_{\text{clip}}(i, n)}{1 + \sum_i \text{Count}(i, n)} & \text{if } \text{smooth} = \text{True} \end{cases} \]

Let \(C = \sum_i |\text{pred}_i|\) (translation_length) and \(R = \sum_i |\text{ref}^*_i|\) (reference_length, using the closest-length valid reference per example, breaking ties toward the shortest reference). The brevity penalty \(\text{BP}\) and final score are:

\[ \text{BP} = \begin{cases} 1.0 & \text{if } C > R \\ \exp\!\left(1 - \dfrac{R}{C}\right) & \text{otherwise} \end{cases} \qquad \text{SQL-BLEU} = \text{BP} \cdot \exp\!\left(\sum_{n=1}^{K} \frac{1}{K} \log p_n\right) \]
  • When min(p_n) == 0 (common on unsmoothed short batches with zero 4-gram overlap), the geometric mean collapses to 0.0.
  • sentence_sql_bleu and per_example_bleu: Single-example BLEU always uses add-1 smoothing (smooth=True by default on sentence_sql_bleu, and unconditionally for each non-None entry in per_example_bleu) so individual short queries retain graded signal even without exact 4-gram matches.

For explicit step-by-step SQL-BLEU calculations on real BIRD-dev predictions vs. golden queries—covering missing and extra clauses, count clipping, add-1 smoothing, non-canonical functions, and corpus aggregation—see Worked Examples at the end of this page.


Adaptations to sqlglot ASTs

Raw text BLEU penalizes harmless SQL formatting differences—casing, indentation, comment noise, or reordered associative clauses. Before tokenization, SqlBleu normalizes both predictions and references through canonicalize.py (source):

  1. Dialect-aware AST parsing (parse_sql): Parses each SQL string under the configured sqlglot dialect, rejecting empty strings, multi-statement batches, and exp.Command parser fallbacks.
  2. Identifier normalization (normalize_identifiers=True): Folds unquoted exp.Identifier names to lowercase while preserving exact casing on quoted identifiers (for example "MixedCase" or "Order Date"); quote delimiters normalize to the target dialect's primary identifier quote (so `Order Date` and [Order Date] under "sqlite" both render "Order Date").
  3. Bottom-up commutative predicate sorting (sort_commutative=True):
    • Normalizes binary = (exp.EQ) and != / <> (exp.NEQ) operands lexicographically by rendered SQL (id = 1 becomes 1 = id).
    • Sorts literal-list IN (...) expressions (status IN ('b', 'a') becomes status IN ('a', 'b')) while leaving IN (SELECT ...) subqueries intact.
    • Flattens associative AND / OR trees and sorts their operands lexicographically while preserving parentheses around mixed logical operators ((a OR b) AND c never loses precedence).
  4. Comment and semicolon normalization (strip_comments=True, include_semicolons=False): Drops -- and /* ... */ comments and trailing ; delimiters before sqlglot AST rendering and tokenization.
  5. Quote-preserving tokenization (sqlglot.tokenize): Produces dialect-aware syntactic tokens (re-quoting TokenType.STRING literals cleanly, falling back to a bounded linear regex tokenizer on tokenization edge cases).

SQL-BLEU vs. Component/Exact Matching

Unlike ComponentMatching and ExactMatching, SqlBleu does not mask literal values ('active' vs. 'inactive') or collapse foreign keys—it stays faithful to Chen et al. (2019)'s token-level n-gram comparison over canonicalized SQL.


Unparseable Query Handling

Unparseable predictions or references are excluded from n-gram accumulators (scored_count), while parsed_count, unparseable_count, parse_success_rate, and reference_parse_success_rate are always reported explicitly alongside bleu so silent survivorship bias is immediately visible. If scored_count == 0 or reference_length == 0, bleu, precisions, brevity_penalty, and length_ratio return None.


API Reference

Class & Stateless Signatures

  • gbv.load("sql_bleu", **kwargs) -> SqlBleu / SqlBleu(...)
  • compute_sql_bleu(predictions, references, *, ...)
  • sentence_sql_bleu(prediction, reference, *, smooth=True, ...)
Parameter Type Default Description
dialect str "postgres" Target sqlglot dialect (or "postgresql", "sqlite3", ANSI "").
max_order int 4 Maximum n-gram order (>= 1).
smooth bool False (True on sentence_sql_bleu) Apply add-1 smoothing; on SqlBleu, pass to compute(smooth=...).
canonicalize bool True Parse and canonicalize ASTs before tokenization; if False, tokenizes raw SQL text directly.
sort_commutative bool True Sort operands of =, !=, literal IN (...), AND, and OR.
normalize_identifiers bool True Lowercase unquoted identifiers while preserving quoted identifier case.
strip_comments bool True Strip SQL comments before tokenization.
include_semicolons bool False Retain ; tokens during canonical rendering and tokenization.
extractor ExtractorLike None Optional extractor run on predictions only (extract_fenced_or_last_sql, regex, or callable).
max_query_chars int \| None 65_536 Maximum character length per SQL query before rejecting/failing parse.
max_input_chars int \| None 131_072 Maximum raw completion character length accepted by extractor.
include_per_example bool False Include per_example_bleu: list[float \| None] (add-1 smoothed) in compute() output (not accepted by sentence_sql_bleu).

compute() Output Schema

Key Type Semantics
bleu float \| None Corpus SQL-BLEU score in [0.0, 1.0], or None when scored_count == 0 / reference_length == 0.
precisions list[float] \| None Clipped n-gram precision for orders 1..max_order (length max_order), or None.
brevity_penalty float \| None Corpus brevity penalty in (0.0, 1.0] (or 0.0 if translation_length == 0), or None.
length_ratio float \| None translation_length / reference_length, or None.
translation_length int Total canonical prediction tokens across scored_count pairs.
reference_length int Sum of closest reference token lengths across scored_count pairs.
scored_count int Number of rows where the prediction and at least one reference parsed cleanly.
parsed_count int Number of predictions passing extraction, char bounds, and AST parsing.
unparseable_count int Number of predictions failing extraction, char bounds, or AST parsing.
parse_success_rate float parsed_count / num_examples.
reference_parse_success_rate float Parsed reference queries divided by total supplied reference queries.
num_examples int Total rows passed via add() / add_batch().
dialect str Normalized sqlglot dialect name.
max_order int Configured maximum n-gram order.
smooth bool Whether add-1 smoothing was applied to corpus precisions.
per_example_bleu list[float \| None] (Only when include_per_example=True) Per-row add-1 smoothed BLEU, or None if unparseable.

Code Examples

Corpus, Commutative Canonicalization & Multi-Reference Scoring

import group_by_vibes as gbv

metric = gbv.load("sql_bleu", dialect="postgres", include_per_example=True)
metric.add_batch(
    predictions=[
        "SELECT name, age FROM users WHERE status = 'active' AND 1 = role",
        "SELECT name FROM users WHERE id IN (3, 1, 2)",
    ],
    references=[
        ["SELECT name, age FROM users WHERE role = 1 AND status = 'active'"],
        [
            "SELECT email FROM accounts",
            "SELECT name FROM users WHERE id IN (1, 2, 3)",
        ],
    ],
)
res = metric.compute()
assert res["bleu"] == 1.0
assert res["parse_success_rate"] == 1.0
assert res["per_example_bleu"] == [1.0, 1.0]

Single-Pair sentence_sql_bleu With Raw LLM Completions

import group_by_vibes as gbv

raw_completion = (
    "<think>\nUse active status filter.\n</think>\n"
    "```sql\nSELECT name FROM users WHERE status = 'active';\n```"
)

score = gbv.sentence_sql_bleu(
    raw_completion,
    "SELECT name FROM users WHERE status = 'active'",
    dialect="sqlite",
    extractor=gbv.extract_fenced_or_last_sql,
)
assert score == 1.0

Worked Examples

The worked examples below use real BIRD-dev predictions (including rows from bird_qwen_3b.jsonl) alongside targeted minimal queries, all scored with max_order=4 (dialect="sqlite" unless noted). Each thematic subsection isolates a distinct behavior of SQL-BLEU.

Length Mismatches: Missing vs. Extra Clauses

Missing and extra clauses are penalized by different terms in the SQL-BLEU formula: missing tokens trigger the brevity penalty (\(\text{BP} < 1\)), whereas extra tokens leave \(\text{BP} = 1.0\) and instead dilute n-gram precisions.

Missing Clauses (C < R — Brevity Penalty)

Real BIRD question_id=297 (student_club)

  • Prediction: SELECT notes FROM income WHERE date_received = '2019-09-14'
  • Golden: SELECT notes FROM income WHERE source = 'Fundraising' AND date_received = '2019-09-14'

After AST canonicalization (see Adaptations to sqlglot ASTs), commutative = and AND sorting places '2019-09-14' = date_received first in both queries:

  • Canonical prediction (\(C = 8\)): SELECT notes FROM income WHERE '2019-09-14' = date_received
  • Canonical golden (\(R = 12\)): SELECT notes FROM income WHERE '2019-09-14' = date_received AND 'Fundraising' = source

Every predicted 1-, 2-, 3-, and 4-gram appears verbatim as a prefix of the golden query, so all four precisions equal 1:

\[ p_1 = \frac{8}{8}, \quad p_2 = \frac{7}{7}, \quad p_3 = \frac{6}{6}, \quad p_4 = \frac{5}{5} \]
\[ \text{BP} = \exp\!\left(1 - \frac{12}{8}\right) = e^{-0.5} \approx 0.6065, \qquad \text{SQL-BLEU} = 0.6065 \times (1 \cdot 1 \cdot 1 \cdot 1)^{1/4} \approx \mathbf{0.6065} \]

Precision alone would score this 1.0000 (identical under smooth=False and smooth=True); the brevity penalty is what catches the omitted source = 'Fundraising' filter.

Extra Unexpected Clauses (C > R — Precision Dilution)

Now consider the reverse: the prediction includes the full golden query plus an unrequested ORDER BY amount DESC LIMIT 5:

  • Prediction (\(C = 13\)): SELECT notes FROM income WHERE date_received = '2019-09-14' ORDER BY amount DESC LIMIT 5
  • Golden (\(R = 8\)): SELECT notes FROM income WHERE date_received = '2019-09-14'

Because \(C > R\), the brevity penalty does not fire (\(\text{BP} = 1.0\)). Instead, the five extra tokens remain unmatched while inflating every denominator \(\text{Count}(i, n) = C - n + 1\):

\[ p_1 = \frac{8}{13} \approx 0.6154, \quad p_2 = \frac{7}{12} \approx 0.5833, \quad p_3 = \frac{6}{11} \approx 0.5455, \quad p_4 = \frac{5}{10} = 0.5000 \]
\[ \text{SQL-BLEU}_{\text{unsmoothed}} = 1.0 \times (0.6154 \cdot 0.5833 \cdot 0.5455 \cdot 0.5000)^{1/4} \approx \mathbf{0.5594}, \qquad \text{SQL-BLEU}_{\text{smoothed}} \approx \mathbf{0.5956} \]

The same mechanism applies to even minor extra tokens in real benchmark outputs: on BIRD question_id=92 (card_games, Qwen-3B), adding two redundant ASC keywords (ORDER BY cardKingdomFoilId ASC, cardKingdomId ASC vs. ORDER BY cardKingdomFoilId, cardKingdomId) gives \(C = 28 > R = 26\) (\(\text{BP} = 1.0\)), yet dilutes precisions to \(\left[\frac{26}{28}, \frac{23}{27}, \frac{20}{26}, \frac{19}{25}\right]\) and drops SQL-BLEU from 1.0000 to 0.8246 (0.8313 smoothed).

Structural & Literal Errors: Count Clipping and n-Gram Decay

Real BIRD question_id=49 (card_games)

  • Prediction: SELECT id FROM cards WHERE borderColor = 'white' AND cardKingdomId IS NULL AND cardKingdomFoilId IS NULL
  • Golden: SELECT id FROM cards WHERE borderColor = 'borderless' AND (cardKingdomId IS NULL OR cardKingdomFoilId IS NULL) ORDER BY id

After AST canonicalization:

  • Canonical prediction (\(C = 16\)): SELECT id FROM cards WHERE 'white' = bordercolor AND cardkingdomfoilid IS NULL AND cardkingdomid IS NULL
  • Canonical golden (\(R = 20\)): SELECT id FROM cards WHERE 'borderless' = bordercolor AND (cardkingdomfoilid IS NULL OR cardkingdomid IS NULL) ORDER BY id

At the unigram level, 'white' does not appear in the golden query, and AND appears twice in the prediction but only once in the golden query, so count clipping caps AND at 1—leaving \(14\) clipped unigram matches out of \(16\). As \(n\) increases, the structural mismatch (AND vs. (... OR ...)) breaks contiguous spans until only two 4-grams (SELECT id FROM cards and id FROM cards WHERE) survive:

\[ p_1 = \frac{14}{16} = 0.8750, \quad p_2 = \frac{10}{15} \approx 0.6667, \quad p_3 = \frac{6}{14} \approx 0.4286, \quad p_4 = \frac{2}{13} \approx 0.1538 \]

Combining the geometric mean \((0.8750 \cdot 0.6667 \cdot 0.4286 \cdot 0.1538)^{1/4} \approx 0.4429\) with \(\text{BP} = \exp(1 - \frac{20}{16}) = e^{-0.25} \approx 0.7788\):

\[ \text{SQL-BLEU}_{\text{unsmoothed}} = 0.7788 \times 0.4429 \approx \mathbf{0.3449}, \qquad \text{SQL-BLEU}_{\text{smoothed}} = 0.7788 \times \left(\frac{15}{17} \cdot \frac{11}{16} \cdot \frac{7}{15} \cdot \frac{3}{14}\right)^{1/4} \approx \mathbf{0.3865} \]

Zero 4-Gram Overlap: Unsmoothed Collapse vs. Add-1 Smoothing

Real BIRD question_id=96 (card_games)

  • Prediction: SELECT COUNT(id) FROM cards WHERE frameVersion >= '2015'
  • Golden: SELECT COUNT(DISTINCT name) AS number_of_cards FROM cards WHERE isTextless = 0 AND CAST(frameVersion AS INTEGER) >= 2015

After AST canonicalization:

  • Canonical prediction (\(C = 11\)): SELECT COUNT(id) FROM cards WHERE frameversion >= '2015'
  • Canonical golden (\(R = 23\)): SELECT COUNT(DISTINCT name) AS number_of_cards FROM cards WHERE 0 = istextless AND CAST(frameversion AS INTEGER) >= 2015

Only two predicted unigrams (id and '2015') miss the golden query (\(p_1 = \frac{9}{11}\)), and some bigrams and trigrams still match (\(p_2 = \frac{4}{10}\), \(p_3 = \frac{2}{9}\)), but zero 4-grams match (\(p_4 = \frac{0}{8}\)). With \(\text{BP} = \exp(1 - \frac{23}{11}) = e^{-12/11} \approx 0.3359\):

  • Unsmoothed (smooth=False): \(p_4 = 0 \implies \text{SQL-BLEU} = \mathbf{0.0000}\) (the geometric mean collapses to zero despite \(81.8\%\) unigram overlap).
  • Add-1 smoothed (smooth=True, default for sentence_sql_bleu): adding 1 to every numerator and denominator recovers graded signal:
\[ p_1 = \frac{10}{12}, \quad p_2 = \frac{5}{11}, \quad p_3 = \frac{3}{10}, \quad p_4 = \frac{1}{9} \implies \text{SQL-BLEU}_{\text{smoothed}} = 0.3359 \times \left(\frac{10}{12} \cdot \frac{5}{11} \cdot \frac{3}{10} \cdot \frac{1}{9}\right)^{1/4} \approx \mathbf{0.1126} \]

Non-Canonical Functions & Unknown Operators

What happens when a model emits a function or word outside the expected SQL operators depends on how sqlglot parses it under the configured dialect—there are three distinct outcomes.

Dialect-Known Function Rewritten by sqlglot (MEDIAN)

sqlglot recognizes MEDIAN as a first-class AST node (exp.Median) and canonicalizes it into the target dialect's representation.

Against a different aggregate (dialect="sqlite"):

  • Prediction: SELECT MEDIAN(amount) FROM income WHERE source = 'Fundraising'
  • Canonical prediction (\(C = 13\)): SELECT PERCENTILE_CONT(amount, 0.5) FROM income WHERE 'Fundraising' = source
  • Canonical golden (\(R = 11\)): SELECT AVG(amount) FROM income WHERE 'Fundraising' = source

Because MEDIAN(amount) expands to PERCENTILE_CONT(amount, 0.5), it introduces three mismatched tokens (PERCENTILE_CONT, ,, 0.5) with \(\text{BP} = 1.0\):

\[ p_1 = \frac{10}{13}, \quad p_2 = \frac{7}{12}, \quad p_3 = \frac{5}{11}, \quad p_4 = \frac{4}{10} \implies \text{SQL-BLEU}_{\text{unsmoothed}} \approx \mathbf{0.5344}, \qquad \text{SQL-BLEU}_{\text{smoothed}} \approx \mathbf{0.5758} \]

Against an equivalent dialect form (dialect="postgres"): SELECT MEDIAN(amount) ... canonicalizes to SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY amount) ... (\(C = R = 17\)), so against a PostgreSQL golden query using PERCENTILE_CONT, SQL-BLEU scores 1.0000.

Unknown or Hallucinated Function Call (GEOMEAN)

Because SQL grammar permits user-defined functions (UDFs), any syntactically valid unknown function call parses as exp.Anonymous and passes through verbatim as a single token:

  • Canonical prediction (\(C = 11\)): SELECT GEOMEAN(amount) FROM income WHERE 'Fundraising' = source
  • Canonical golden (\(R = 11\)): SELECT AVG(amount) FROM income WHERE 'Fundraising' = source

Only the n-grams spanning the single GEOMEAN token break (\(\text{BP} = 1.0\)):

\[ p_1 = \frac{10}{11}, \quad p_2 = \frac{8}{10}, \quad p_3 = \frac{7}{9}, \quad p_4 = \frac{6}{8} \implies \text{SQL-BLEU}_{\text{unsmoothed}} \approx \mathbf{0.8071}, \qquad \text{SQL-BLEU}_{\text{smoothed}} \approx \mathbf{0.8265} \]

SqlBleu is purely syntactic and does not verify whether a UDF exists in your database engine—a hallucinated function name still receives high n-gram overlap.

Invalid Non-SQL Operator (NEARLY)

  • Prediction: SELECT notes FROM income WHERE amount NEARLY 100

parse_sql rejects this query (syntax_error), so it is excluded from n-gram accumulators (unparseable_count += 1, parse_success_rate decreases, and per_example_bleu records None; see Unparseable Query Handling).

(Edge case: if an unknown bare word happens to occupy a valid SQL alias slot—such as FROM income APPROXIMATELY WHERE ...—the parser interprets it as a table alias FROM income AS approximately, turning it into an extra-token precision penalty rather than a parse error.)

Corpus Micro-Aggregation vs. Sentence Averages

Corpus SqlBleu sums clipped matches, candidate counts, and token lengths across all scored examples before dividing—it does not average per-example scores. Aggregating the three real BIRD-dev examples above (#297, #49, #96) pools their lengths to \(C = 35\), \(R = 55\) and their n-gram counts to \(\left[\frac{31}{35}, \frac{21}{32}, \frac{14}{29}, \frac{7}{26}\right]\):

\[ \text{BP}_{\text{corpus}} = \exp\!\left(1 - \frac{55}{35}\right) = e^{-4/7} \approx 0.5647, \qquad \text{SQL-BLEU}_{\text{corpus}} = 0.5647 \times \left(\frac{31}{35} \cdot \frac{21}{32} \cdot \frac{14}{29} \cdot \frac{7}{26}\right)^{1/4} \approx \mathbf{0.2961} \]

Two key takeaways: (1) even though BIRD #96 had zero 4-gram overlap, unsmoothed corpus SQL-BLEU stays non-zero because 4-gram counts pool to \(7/26\); and (2) corpus SQL-BLEU (0.2961) differs from the arithmetic mean of the three unsmoothed (0.3171) or smoothed (0.3685) per-example scores.

Example \(C_i / R_i\) \(n=1\) \(n=2\) \(n=3\) \(n=4\) \(\text{BP}\) Unsmoothed Smoothed
BIRD #297 (missing clause) 8 / 12 8 / 8 7 / 7 6 / 6 5 / 5 0.6065 0.6065 0.6065
BIRD #49 (clipping & decay) 16 / 20 14 / 16 10 / 15 6 / 14 2 / 13 0.7788 0.3449 0.3865
BIRD #96 (zero 4-grams) 11 / 23 9 / 11 4 / 10 2 / 9 0 / 8 0.3359 0.0000 0.1126
Corpus sum 35 / 55 31 / 35 21 / 32 14 / 29 7 / 26 0.5647 0.2961 0.3074