AI-Written SQL (and Stored Procedures) From “Works” to “Trusted”

Assetization = auditable + deterministic + verifiable
AI has made writing cheap; reviewing has not become any cheaper. This piece is not about how to make models write more accurate SQL. It asks a different question: can we make it impossible for the model to write the wrong thing at all — put it in the planning layer and hand generation to a deterministic compiler? The goal is not a piece of code that runs, but an asset that people can read, change, and port.
01
Auditable
Step-by-step readable,
item-by-item verifiable
02
Deterministic
Canonical steps implemented
by a compiler, always the same
03
Verifiable
Inspect intermediate results
one step at a time

01Writing got cheap; reviewing did not

Direct natural-language-to-SQL for complex queries typically lands around 60% accurate — roughly one error every three or four attempts. For throwaway scripts you read yourself, that hit rate does save time. But once the result feeds a report, a reconciliation, or a downstream batch job, every error is a rework cycle.

Worse, the error is often not an exception: the numbers look plausible while the metric definition has already drifted — and nobody catches that for you.
Even at 90% accuracy, the model will not flag which 10% is wrong; in serious settings a human still reviews every line, so the workload does not drop at all. The bottleneck, in the end, is not writing. It is review.
Figure 1
Generation speed is not the bottleneck; audit is

Generation speed stopped being the bottleneck long ago. Prompt in, final SQL out, and in between sits a black box: where did this column come from, how was this metric defined, why is there a DISTINCT here — people have to reverse-engineer all of it. Code must be traceable and the logic reviewable step by step, not merely “it runs.”

02Why SQL is uniquely hard to audit

Reports, batch jobs, data extraction, ad-hoc analysis — SQL is the largest and most unavoidable category of code for a data team, and it happens to trip all three audit traps at once.

There is a deeper layer, too: AI cannot guarantee logical consistency between input and output, and cannot spot its own mistakes. The database only catches syntax errors; whether the business logic is right still takes a human reading the code.

Sin 1 · hard to read

SQL evaluates from the innermost layer outward; people think front to back. The two orders are exactly opposite. A simple query reads like English, but add continuity, segmentation, or ranking and it turns counterintuitive.

Sin 2 · hard to debug

No visibility into intermediate state. When a 300-line query returns the wrong result you cannot tell which section is at fault; you peel layers apart by hand, and touching one thing moves everything.

Sin 3 · untestable

One-off extracts and short-lived analyses have a lifecycle too short to justify building datasets and writing assertions; correctness depends on people reading, running, and eyeballing. Almost all audit cost lands on people — and the faster AI generates, the more tired the reviewer gets.

Four levels of nesting, five steps everyone understands

Take the longest rising streak of a stock: sort, decide, segment, count, take the maximum — five steps anyone understands. Written as SQL, it becomes four levels of nesting.

Four-level nested form (read from the inside out)

select max(ContinuousDays)
from (
    select count(*) ContinuousDays
    from (
        select sum(UpDownTag) over (order by DT) NoRisingDays
        from (
            select DT,
                case when CL > lag(CL) over (order by DT) then 0 
                else 1 end UpDownTag
            from Stock
            where CODE = 100046
        )
    )
    group by NoRisingDays
)

The correct way to read this code is from the innermost layer out: the innermost layer tags each day as up or down; the second layer uses a running sum to number the “consecutive rising” intervals; the third layer groups by that number and counts rows, giving the streak length of each segment; the outermost takes the maximum. Four layers, four jobs — but the writing order inverts them, so the reader has to unroll the stack in their head.

The real cost is not writing. It is changing. The moment the definition shifts, you start over at the innermost CASE WHEN and re-run four levels of reasoning. Real-world SQL is measured in KBs: 300 lines in a single statement, and while reading and editing you must keep an extremely deep stack in your head.

03Change the division of labor: AI plans, the compiler generates

The fix is not to make AI try harder. It is to change the division of labor: demote the model from generator to planner.

Figure 2
Uncertainty is confined to the planning layer; generation is fully deterministic

AI does one thing only: break a colloquial requirement into canonical steps. It does not produce final SQL. The final SQL is compiled by SQLazy, and the compiler is not AI: the same input always yields the same output, no invented fields, no hallucinations, every step traceable. If the plan is wrong, a human sees it at a glance in the steps; the generation layer gives the model no room to improvise, and everything left is deterministic compilation.

04Key point one: make evaluation order equal reading order

Same longest rising streak, now as a step script — one line per step, read top to bottom.

Five-step script (read top to bottom)

Stock: filter CODE = 100046
sort DT asc
segment CL down as NoRisingDays
summarize count DT as ContinuousDays; group NoRisingDays
summarize max ContinuousDays as max_ContinuousDays

One line per step; the output of one step is the input of the next. Read top to bottom and you are reading the actual evaluation order — reading order and evaluation order finally line up. Step three is the heart of the matter: cutting a run of gains into segments, not with a loop but with a running sum — add one whenever the price falls, add nothing when it does not, and rows in the same rising run naturally land on the same number. This is exactly the hardest-to-read sum(UpDownTag) over (order by DT) inside the nested SQL; in the script it has a name: NoRisingDays. Run any step on its own and you see an intermediate result table — if a step is wrong, open that step and you know.

Switch to monthly semantics; the structure is unchanged

Orders: summarize sum OrderAmount as MonthlySales group ymonth(OrderDate) as YearMonth
segment MonthlySales notIncrease as SegNo
summarize count SegNo as RisingMonths group SegNo
summarize max RisingMonths as max_RisingMonths
Cost of change is the real dividing line. A requirement change touches only the step it belongs to. Want to scale to the whole market? Add “partition by symbol” — same logic, same structure. In nested SQL that means pushing the partition key into every window and every grouping, changing all four layers at once.

05Key point two: write the script in plain language

SQLazy syntax is business verbs: filter, sort, segment, summarize, join, rank, concatenate, derive. One action per line — a verb plus parameters is a compilable spec.

Verb Meaning What it usually becomes underneath
filter filter rows or columns by condition WHERE / projection
sort fix the order of rows ORDER BY, window ordering
segment cut continuous ranges at a threshold CASE marker + window running sum
summarize aggregate metrics, grouped statistics GROUP BY and aggregate functions
join relate multiple tables JOIN
rank number rows within a group ROW_NUMBER / RANK
derive derive new fields SELECT expression
… … …

This style is friendly in both directions. People read it without parsing a syntax tree in their heads; AI generates it more easily too — models are trained on plain language, and asking for linear steps (“filter first, then sort, then segment”) is far easier, and far more reliable, than asking for one deeply nested SQL statement.

The script is also a compilable spec: specification-driven development (SDD), applied to the data side. Write down what to do and in what order; the compiler decides how to implement it. Steps force names, intermediate results get names, and the flood of temporary tables disappears — preview an intermediate result when needed, no trace when not.

06Debugging: putting a step debugger back into SQL

Screenshot 1
▲ Left: the step script in plain language. Click a step and the right pane shows that step's intermediate result set

In the SQLazy IDE there is no second window and no hand-editing the SQL and re-running it. In the stock script, s1 through s5 each carry their own result: s1 is the filtered raw quotes, s4 has been reduced to two columns (the row index and the segment number), and the last step leaves a single number. The more substantive change is that errors are caught earlier: from after execution to before it. A human confirms the logic at the step level first, then the compiler generates the code — if the logic itself is wrong, you see it before anything runs. Native SQL cannot offer this: its grammar has no concept of a “line”, and a whole statement is one indivisible unit that can only be debugged as a whole.

07One-click migration: audit the logic once, leave dialects to the compiler

Write the logic once; the compiler adapts the dialect. Recompile the same script against another target database. One example: pick ClickHouse as the target, and SQLazy compiles this:

Screenshot 2
▲ “Compile to SQL” dialog: choose the target database and generate dialect-specific code in one click

The SUM(CASE ...) OVER (PARTITION BY ... ORDER BY ...) inside this WITH s2 AS clause is the equivalent implementation of the “segment” step in the script: a running sum that numbers consecutive intervals, now written in ClickHouse's dialect. The time arithmetic became addSeconds(col__2, 3600), where a DATEADD-style call would appear elsewhere; the window carries PARTITION BY account_number with ORDER BY account_number ASC, dt ASC and an explicit ROWS frame. And there is no CASE WHEN ... IS NULL THEN 1 trick in the ORDER BY, because ClickHouse puts NULLs last by itself — MySQL needs that trick spelled out. Whoever writes the script knows none of this.

The logic is audited once. Recompile against another database and the result is deterministically identical. It matters most for niche databases — few people know their dialects well, brute-force translation is expensive and risky, while compiled output can be reproduced again and again.

08The closed loop of human–machine division of labor

Figure 3
AI efficiency + compiler determinism + human business judgment — each owns one stage

Break the chain apart and three parties each own a stage: AI plans the logic (efficiency); humans review the steps (business judgment); deterministic compilation guarantees determinism; plus a small-data validation pass to confirm the results agree. The loop is: enter the query objective → AI plans and generates the script → the IDE executes and compiles. People look only where they should look — is the requirement right, is the metric definition right, do the results match the previous run. Nobody oversteps.

09Assetization: bringing legacy SQL back to life

A mechanism that can only generate new code has limited value. One that can also read old code changes what it is worth.

Before reverse translation it is a black box: hundreds of lines, several levels of nesting, the author has left, there are no comments. Nobody understands it, nobody dares change it, and any requirement change means trial and error. When the author leaves, the code dies — the classic maintenance liability.

Having AI interpret this legacy code is a good idea. But interpret it into what?
If it regenerates another SQL statement, that is just a different person rewriting it — still unreadable. If it produces only a human-readable document, that helps you understand the current code; next time the definition changes, someone has to re-read and re-verify, with no guarantee of correctness.
Interpret it into a SQLazy script and both problems disappear at once: the script is a line-by-line logical explanation that helps you understand the original code, and a spec that compiles back into SQL deterministically, so the next change is simply recompiled — no AI rewrite, no human re-read. What you read and what runs are always the same thing.

Legacy SQL (excerpt, some nesting omitted)

select ...,
       sum(case when ... then ... else 0 end) / sum(...) as ...
from (select ... from OrderDetail
      join Orders on ... join Customer on ... join Country on ...
      where ... and ... and ...) t
group by ... order by ...

The reverse-translated linear step script (abridged)

OrderDetail: filter area = "AMERICA" and OrderDate in [2022, 2026]
add Year = year(OrderDate), Amount = ..., BrazilAmount = if(...)
summarize sum BrazilAmount sum Amount as TotalAmount group Year
add BrazilAmount / TotalAmount as MarketShare
sort Year

After reverse translation it is a white box. Once it is a plain text file, it goes into Git, it can be diffed, unit-tested, and handed over. Verification does not depend on eyeballs either: the execution results of the original SQL and of the script are compared automatically, row by row — only when the logic matches do you dare replace it.

Once you get here, this compilable logic is also the documentation. Historical code turns from a maintenance liability into a reusable asset — which is more worth having than “generating faster.”

10Stored procedures: draw the boundaries first, then talk about trust

Once the SQL-layer loop works, the natural next step is to move the same division of labor onto complex stored procedures. There are two goals: make AI-generated procedures easy to audit, and turn legacy procedures into assets; both paths land on the same readable, auditable code form. But the first step is not a design — it is recognizing the boundaries.

Deliberately given up: portability

No claim of write once, run anywhere. Sequences, pagination, hierarchical queries, cursor syntax all vary across databases; there is no universal mapping, and forced migration is costly and risky.

Deliberately given up: debuggability

No simulated runtime debugging inside the script. A stored procedure has writes and consistency requirements, branches and loops; express all of that and the script becomes too complex, and database differences are impossible to emulate.

Design: embed fragments, compile to the target procedure

The host stored procedure keeps the flow, variables, and write statements; SQLazy fragments handle only SELECT and WHERE clauses; compilation produces a native procedure for the target database — the idea is close to Pro*C precompilation.

A stored procedure with an embedded SQLazy fragment (everything between \ and \\ is SQLazy code; the inner \ is SQLazy's line separator)

INSERT INTO tmp_F01
(ID_CODE,ID_TYPE,TRANS_NO,TRANS_DATE,CUST_RISK_LEVEL,INVALID_DATE)
\ods_t4:filter RISK_LEVEL <> ""
R1=rank TRANS_DATE desc, upd_time desc position top 1 partition ID_CODE, ID_TYPE, TRANS_DATE \
ods_t4_h:filter RISK_LEVEL <> "" \
R2=rank TRANS_DATE desc, upd_time desc position top 1 partition ID_CODE, ID_TYPE, TRANS_DATE \
R1:set union R2 \
derive ID_CODE, ID_TYPE, TRANS_NO, TRANS_DATE, RISK_LEVEL, INVALID_DATE  \\;
COMMIT;

Note that there is no BEGIN/END here, and no loops or branches: LOOP stays in the host as it was, and the SQLazy script handles only the computation inside it. After compilation it becomes standard CTEs plus window functions:

The compiled native procedure (excerpt)

INSERT INTO tmp_F01
(ID_CODE,ID_TYPE,TRANS_SERNO,TRANS_DATE,RISK_LEVEL,INVALID_DATE)
WITH ...
...  ROW_NUMBER() OVER ( PARTITION BY ID_CODE, …, ORDER BY … ) 
…
SELECT ... FROM … WHERE rn=1
UNION
SELECT … FROM … WHERE rn=1;
COMMIT;
Why is this a good cut? Because the audit pain in a stored procedure is concentrated exactly in SELECT computations and WHERE conditions — the parts easiest to get wrong and hardest to read — while flow code (variable assignment, branching, loops, commit and rollback) is inherently readable. The trade-off costs little and the gain is clear.

11SPL: host language and performance backstop

SPL as the host language: flow is not bound to the database

If the host need not be one database's stored procedure, there is a more radical option: use SPL as the host. Flow, branches, loops, and write actions all live in SPL; SQL queries and updates follow the host; computation fragments are embedded inside the SQL — SPL wraps SQL, and SQL embeds SQLazy fragments.

Figure 4
SPL wraps SQL; SQL embeds SQLazy fragments

SPL code embedding SQL and SQLazy fragments

……
17 if v_num==1
18     >log_message = concat("Partition ", partition_name, " already exists, start cleaning...")
……
47     $insert into tmp_F01(
         ID_CODE
         ,ID_TYPE
         ,trans_date
         ,first_flag
         )\
         ods_t4:filter RISK_LEVEL <> "" \
         rank TRANS_DATE desc, upd_time desc position top 1 partition ID_CODE, ID_TYPE \
         derive ID_CODE, ID_TYPE, TRANS_NO, TRANS_DATE, upd_time \\
48     $commit
49     $insert into fds.tmp_F02(
         ID_CODE
         ,ID_TYPE
         ,TRANS_NO
         ,TRANS_DATE
         ,upd_time
          )\
         ods_t4_h:filter RISK_LEVEL <> "" \
         rank TRANS_DATE desc, upd_time desc position top 1 partition ID_CODE, ID_TYPE \
         derive ID_CODE, ID_TYPE, TRANS_NO, TRANS_DATE, upd_time \\
50     $commit
……
68 else
69     >EndTime=now()
70     >RunTime=interval@s(StartTime,EndTime)
71     >step_context ="3-Model layer data processing failed"
……

Two benefits. First, it follows where new databases are going: many new databases simply do not support stored procedures, and with a host language not bound to the database you can still deliver the same capability — and the portability and debuggability you deliberately gave up come back, since an independent host language is far more controllable than one database's syntax. Cursors and ordered operations are stronger too. Second, deployment cost is low: SPL is pure Java and interpreted, so it fits into the Java ecosystem, works with Java frameworks, and supports hot swapping. The price is an extra runtime layer — weigh that against your team's reality, and do not treat it as the default answer.

Performance backstop: most cases compile as usual; a few are rewritten in SPL to gain 10× performance

Performance after migration does not always pass muster. Some SQL and stored procedures slow down sharply on the new database, and tuning the SQL alone cannot fix it. SPL, SQLazy's core engine, ships with high-performance algorithms built in, and these cases gain roughly 10× once rewritten. The approach: preserve fidelity first, then split by performance — legacy AP SQL and stored procedures are reverse-translated through AI + the SQLazy semantic layer into logic-preserving, auditable steps, then routed by performance.

Figure 5
Preserve fidelity first, then split by performance: most compile as usual, a few fall back to SPL

12Compared with conventional AI approaches: is comprehension debt relocated or repaid?

Conventional AI direct translation: dozens of round-trips of compare-and-repeat, three gaps left open

The assumption behind the conventional approach: with the source database's results as ground truth, AI will always converge on correct target-database code. So the loop is built in four steps: source code → AI direct translation (swap source syntax for target syntax) → target code → run both and compare (if they differ, ask AI for another round).

Figure 6
Feedback loop: mismatch → regenerate → compare

Asset view · comprehension debt is only relocated

The migrated target code still has to be changed, and it carries no comprehensible state. The debt has moved from the source database to the target database; it has not been eliminated.

Validation view · passing on samples ≠ logical equivalence

Source results only prove agreement on sample data. Dozens of rounds may still end up wrong, and in the end a human has to look.

Capability view · when capabilities diverge, the algorithm must change

Some new databases do not support stored procedures, or differ too far in capability. That is not something syntax rewriting can solve; a human has to redesign the algorithm.

So the order for AI + SQLazy is: deposit the understanding first, then talk about migration — turn business logic into a readable, auditable, verifiable asset.

The two endings of comprehension debt: with documents you check on every change; with scripts you verify once

Figure 7
The cost is not in the first migration — it is in every maintenance cycle after it
The key difference: interpret into a document and you check on every change; reverse-translate into a script and you verify once.

Conclusion: assetization = understandable + changeable + portable

However deeply AI participates, responsibility for judgment cannot be handed over. The answer is not “wait for a more accurate model” but to move uncertainty into a position where it can be audited, and let the generated logic settle into an asset.

Understandable

The black box is reverse-translated into white-box steps, so comprehension debt is repaid rather than relocated.

Changeable

Logic is documentation, one line per step; a metric-definition change touches only its step.

Portable

Dialects are generated deterministically by the compiler: one logic body, compiled many times.

Dimension Old paradigm New paradigm
Chain prompt → AI → uncertain final SQL prompt → AI → canonical steps → compiler → deterministic SQL
What humans review all the code the steps
Intermediate state black box, invisible visible at every step, runnable on its own
Traceability reverse-engineered by people one line per step, with a name
Switching databases AI translates the dialect, but every line needs human review recompile; the steps still need review, but only once
Locating errors trial and error across the whole statement pinpoint the specific step
Comprehension debt only relocated; check on every change repaid once; verify once
Legacy code maintenance liability an asset that can be reverse-translated and handed over
Requirements keep changing, and models keep changing. What can change is how deeply AI participates; what cannot change is that people must hold something they can understand, change, and re-verify.
Leave the small uncertain piece for people to look at and give the rest to determinism — AI made writing cheap, and reviewing should not stay this expensive.

Leave a Reply