Project 03 · Applied AI for data engineering

AI-Assisted SQL Optimizer

A CLI that parses Spark and Snowflake SQL with sqlglot, flags anti-patterns with six heuristic rules, and sends the SQL plus structured findings to Claude for a rewrite. Everything below is the real corpus and real analyzer output — no simulated results.

$ make benchmark
Benchmark over 5 queries (dry_run=True)                  
┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
┃ Category            ┃ Queries ┃ Avg keyword overlap ┃ Findings hit rate ┃
┡━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━┩
│ join_optimization   │       1 │                1.00 │              1.00 │
│ aggregation_rewrite │       1 │                0.33 │              1.00 │
│ cte_flattening      │       1 │                0.00 │              1.00 │
│ partition_pruning   │       1 │                0.00 │              0.00 │
│ broadcast_join      │       1 │                0.33 │              1.00 │
└─────────────────────┴─────────┴─────────────────────┴───────────────────┘
EXPLAIN step not run: no engine (pass --explain spark|snowflake).
Captured by scripts/measure.py · Oct 2026 · sqlglot 30.21.0

At a glance

At a glance

Problem
Closes the gap between 'a query that runs' and 'a query a senior would ship' for Spark SQL and Snowflake workloads.
Approach
sqlglot AST + six heuristic rules produce structured findings; a versioned prompt sends them to Claude; a 5-query corpus with ground truth scores the analyzer.
Run it
cd project-ai-sql-optimizer && make install && make benchmark
Tests
45 passing · CI on every push
Docs
README (opens in new tab) Methodology (opens in new tab)

What exists — honestly

Status key →
  • sqlglot parse + 6 heuristic rules

    4 of 6 rules fire on the corpus

    Measured
  • 5-query corpus with ground truth

    make benchmark (dry run)

    Measured
  • Claude rewrite via versioned prompt

    needs ANTHROPIC_API_KEY; not benchmarked

    Implemented
  • Cloudflare Worker proxy for live mode

    wrangler.toml placeholders

    Stub
  • Claude in the benchmark (--no-dry-run)

    needs ANTHROPIC_API_KEY; no live run recorded

    Implemented
  • EXPLAIN cost verification

    --explain spark|snowflake; needs an engine with the corpus tables

    Needs infra
  • Human acceptance study

    Planned
Measured Caveat

4 / 5

queries with ≥1 analyzer finding

real corpus · heuristics only, no API

How this was measured
Method
make benchmark (dry run)
Date
2026-10-05
Env
4 vCPU · Python 3.11.15 · seed 42

Caveat · Any finding counts as a hit; whether the finding is the right one is not scored.

Evidence ledger
Measured

0.33

benchmark keyword overlap

analyzer findings only · heuristics, no API

How this was measured
Method
make benchmark (dry run)
Date
2026-10-05
Env
4 vCPU · Python 3.11.15 · seed 42
Evidence ledger
Measured

0.9 ms

analyzer latency per query

in-process median, warm · n=200

How this was measured
Method
scripts/artifacts/sqlopt.py times analyze() over the 5 corpus queries ×40
Date
2026-10-05
Env
4 vCPU · Python 3.11.15 · seed 42
Evidence ledger
Test run

45

unit tests passing

analyzer, benchmark, CLI, client, EXPLAIN

How this was measured
Method
make test
Date
2026-10-05
Env
4 vCPU · Python 3.11.15 · seed 42
Evidence ledger

Re-measured Oct 2026 from the project's own make targets on synthetic data (seed 42) — full ledger and transcripts.

Query workbench

Five real queries, one anti-pattern each

Pick a query to see what the analyzer actually reports, which ground-truth keywords it earns, a reference rewrite with its assumptions, and the exact message the CLI would send to Claude. Tabs deep-link (#q1–#q5).

corpus/queries/01_join_optimization.sql

Join optimization

An order-line join against a small dim_product table. The query selects everything and joins without a broadcast hint - the optimizer may pick a shuffled hash join even though dim_product is well under the 8MB broadcast threshold.

tables
2
ctes
0
joins
1
lines
5

tagged: spark parsed as: spark

Original

SELECT *
FROM bronze.fct_order_lines fol
JOIN bronze.dim_product dp
  ON fol.product_id = dp.product_id
WHERE fol.order_date >= '2026-01-01';

Analyzer findings · real output

  • warn select_star

    SELECT * fans out columns and disables column pruning. List columns explicitly.

  • info consider_broadcast

    Join detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.

4 rules didn't fire
  • cross_join
  • missing_partition_predicate
  • correlated_subquery
  • many_ctes

Ground truth · keyword matches

  • "broadcast" in findings
  • "select" in findings

benchmark score 1.00 (2/2 keywords in findings)

Reference rewrite

Project the columns, broadcast the dimension

Replace SELECT * with the columns a consumer needs and hint the small dim_product side for a broadcast hash join instead of a shuffle.

Hand-written · not Claude output · not EXPLAIN-verified

Line diff, original to rewrite

SELECT *SELECT /*+ BROADCAST(dp) */    fol.order_id,    fol.order_date,    fol.product_id,    fol.quantity,    fol.amount_usd,    dp.product_name,    dp.categoryFROM bronze.fct_order_lines folJOIN bronze.dim_product dp  ON fol.product_id = dp.product_idWHERE fol.order_date >= '2026-01-01';
  • Parses (spark) yes
  • Analyzer findings 2 → 0
  • Ground-truth keywords in SQL 2/2

Assumptions

  • The column list is illustrative; the real consumer's needs decide it.
  • dim_product stays under the broadcast threshold. With AQE on Spark 3.x the planner may already convert this join at runtime when statistics are fresh.
What Claude would receive for this query client._build_user_message()
## Dialect
spark
## SQL
```sql
-- engine: spark
-- category: join_optimization
-- An order-line join against a small dim_product table. The query selects
-- everything and joins without a broadcast hint - the optimizer may pick a
-- shuffled hash join even though dim_product is well under the 8MB
-- broadcast threshold.

SELECT *
FROM bronze.fct_order_lines fol
JOIN bronze.dim_product dp
  ON fol.product_id = dp.product_id
WHERE fol.order_date >= '2026-01-01';

```
## Heuristic findings
- (warn) select_star: SELECT * fans out columns and disables column pruning. List columns explicitly.
- (info) consider_broadcast: Join detected without BROADCAST hint. If one side is small (< ~8MB), broadcast it.
Return your answer as a JSON object with keys `rewrite`, `reasoning`, `confidence`.

Benchmark

What the score does and doesn't measure

The dry-run benchmark scores keyword overlap with ground truth and whether any finding fired. Both charts below come straight from the analyzer's output over the corpus, so the score's blind spots are visible rather than footnoted.

Ground-truth keywords: earned by findings vs. already in the query

Each bar is one corpus query; segments count its expected keywords.

Real corpus · make benchmark. Computed from the real corpus, ground_truth.yaml, and analyze() output by scripts/artifacts/sqlopt.py.
Keyword attribution per corpus query
QueryIn findingsQuery text onlyMissed
01 join optimization200
02 aggregation rewrite111
03 cte flattening003
04 partition pruning021
05 broadcast join120
Takeaway4 of 14 expected keywords appear in analyzer findings, the only place the scorer looks. 5 more appear only in the query's own text, which it does not count.

Ground-truth keywords: earned by findings vs. already in the query

Each bar is one corpus query; segments count its expected keywords.

4 of 14 expected keywords appear in analyzer findings, the only place the scorer looks. 5 more appear only in the query's own text, which it does not count.

Rule coverage across the corpus

Which heuristic fires on which query, from analyze() run exactly as the benchmark runs it.

Real analyzer output
Rule 01 Join optimization 02 Aggregation rewrite 03 CTE flattening 04 Partition pruning 05 Broadcast join Fires
warn select_star · · · · 1
high cross_join · · · · · never
high missing_partition_predicate · · · · · never
info consider_broadcast · · 3
warn correlated_subquery · · · · 1
info many_ctes · · · · 1

Takeaway cross_join and missing_partition_predicate never fire here — the corpus needs a cross-join case, and the benchmark needs to pass partition columns.

Evaluation status · not measured

  • Built · not run

    Claude rewrite quality

    --no-dry-run scores Claude's rewrites with the same scorer, but it needs an API key and no live run is recorded yet.

  • Needs an engine

    EXPLAIN cost delta

    --explain spark|snowflake records estimated bytes scanned before and after; it needs an engine holding the corpus tables.

  • Planned

    Human acceptance

    Reviewer accept/reject with rationale per suggestion, as the corpus grows.

Architecture

What runs where

Each lane is a path through the system, colour-coded by status. Every node names the file that implements it — click through to the source.

Analyze

Measured

sql-optimizer analyze --dry-run — no API key needed

  1. Query file

    Spark SQL or Snowflake

    queries/ — corpus/queries/ (opens in new tab)
  2. sqlglot parse

    dialect-aware AST

    analyzer.py — src/sql_optimizer/analyzer.py (opens in new tab)
  3. 6 heuristic rules

    select *, cross join, partition, broadcast, correlated, CTEs

    analyzer.py — src/sql_optimizer/analyzer.py (opens in new tab)
  4. Findings

    rule · severity · message

Suggest

Implemented

needs ANTHROPIC_API_KEY — benchmark --no-dry-run scores it; no live run recorded

  1. SQL + findings

    structured user message

    client.py — src/sql_optimizer/client.py (opens in new tab)
  2. Optimizer prompt

    versioned in the repo

    optimizer_prompt.md — src/sql_optimizer/prompts/optimizer_prompt.md (opens in new tab)
  3. Claude

    Messages API, retries on 429/5xx

    client.py — src/sql_optimizer/client.py (opens in new tab)
  4. Rewrite + reasoning

    JSON: rewrite · reasoning · confidence

Benchmark

Measured

make benchmark — dry run over the corpus

  1. 5-query corpus

    one per category

    queries/ — corpus/queries/ (opens in new tab)
  2. Ground truth

    expected keywords + cost direction

    ground_truth.yaml — corpus/ground_truth.yaml (opens in new tab)
  3. Scorer

    keyword overlap · findings hit

    benchmark.py — src/sql_optimizer/benchmark.py (opens in new tab)

Verify

Needs infra

benchmark --explain spark|snowflake — needs an engine holding the corpus tables

  1. EXPLAIN original

    Spark EXPLAIN COST · Snowflake EXPLAIN USING JSON

    explain.py — src/sql_optimizer/explain.py (opens in new tab)
  2. EXPLAIN rewrite

    same engine, same statistics

    explain.py — src/sql_optimizer/explain.py (opens in new tab)
  3. Cost delta

    estimated bytes scanned, before → after

    benchmark.py — src/sql_optimizer/benchmark.py (opens in new tab)

Engineering narrative

Problem, judgment calls, and results

Problem

There is a real gap between “a query that runs” and “a query a senior would ship”: knowing when to broadcast, prune partitions, flatten repeated scans, or replace correlated subqueries. This tool parses Spark SQL and Snowflake queries with sqlglot, runs a small set of heuristic rules over the AST, and sends the SQL plus structured findings to Claude with a versioned optimizer prompt. Without an API key it runs in a heuristics-only dry-run mode, which is what the published benchmark measures.

Judgment calls

Heuristics + LLM, not LLM only. Sent raw SQL, a model spends its budget re-deriving facts a parser already knows: which columns are projected, which joins lack hints, whether a subquery is correlated. A sqlglot pass extracts those cheaply and ships them as structured findings, leaving the model to decide what to do about them.

EXPLAIN is a tiebreaker, not ground truth. benchmark --explain spark|snowflake explains the original and the rewritten query and records the engine’s estimated bytes scanned before and after. Those estimates reflect the planner’s statistics, so the runner refuses Spark’s 8.0 EiB “unknown” default and leaves a side blank when the engine cannot estimate it. It also has blind spots: on a local Spark session a broadcast hint or an explicit column list leaves the estimate unchanged. No EXPLAIN run is recorded yet, so the site shows no cost numbers.

Prompt sensitivity is a real risk. Small prompt edits change suggestion quality, so the prompt lives in version control (prompts/optimizer_prompt.md) next to the code that sends it. Regression tests that pin model output against the corpus are the next step.

A corpus designed to grow. Five categories, one fully specified query each, with expected keywords and cost direction in corpus/ground_truth.yaml. Adding a case is one .sql file plus one ground-truth entry.

Measured results

make benchmark (dry run) finds at least one issue in 4 / 5 queries and averages 0.33 keyword overlap against ground truth, with the analyzer taking 0.9 ms per query in process. The score counts only what the findings say, never the query text, so partition_pruning, which gets no finding, scores 0.00. The partition rule never fires in the benchmark because it needs partition columns passed in; with --partition-columns ingest_date it flags query 04 at high severity. Two of six rules (cross_join and missing_partition_predicate) are never exercised by the corpus — the obvious next corpus additions.

Honest limitations

  • benchmark --no-dry-run asks Claude for every rewrite, but no live run is recorded, so model rewrite quality is still unmeasured.
  • Claude can hallucinate plausible column or table names that are not in the schema.
  • The benchmark ignores each query’s -- engine: header, so Snowflake queries are parsed as Spark.
  • EXPLAIN cost deltas are implemented but not run here (they need an engine holding the corpus tables); human acceptance rate is planned.

Stack

What it uses, and why

Python 3.11
CLI runtime; typed dataclasses for findings and results.
sqlglot
Dialect-aware SQL parser — the heuristics walk its AST instead of regexes.
Typer + Rich
Ergonomic CLI with readable findings tables.
Anthropic SDK
Claude Messages API with retry/backoff on rate limits and 5xx.
PyYAML
Ground truth for the benchmark lives in reviewable YAML.
pytest
45 tests across analyzer, benchmark, CLI, client and EXPLAIN (API and engines mocked).
esc