AI-Written SQL (Stored Procedures): From “Works” to “Trusted”
Assetization = auditable + deterministic + verifiable: engineering assets that AI writes and that people can understand and audit
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.
1 Writing got cheap; reviewing did not
A 60% accuracy rate is not enough for production
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.
The real bottleneck is audit
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.”
2 Why 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 — even someone without a technical background can follow it. But the moment you need to express continuity, segmentation, or ranking, it turns counterintuitive.
Take the simplest example: 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 — say “rising” becomes “N consecutive days with a gain above x%” — you start over at the innermost CASE WHEN and re-run four levels of reasoning. Every nested layer raises a question: if I change this layer, does the layer above break?
Real-world SQL is far more complex than this. We like to say that three-line and five-line SQL exists only in textbooks and training courses; SQL in analysis and reporting is measured in KBs. And those scripts, several KB in size, are still one giant tangle of nesting. In other languages, 300 lines means 300 statements — you can read one and forget it. Complex SQL is 300 lines in a single statement: while reading and editing you must keep an extremely deep stack in your head. Calling it counterintuitive is not an exaggeration.
Sin 2: hard to debug
No visibility into intermediate state. When a 300-line report query or a complex stored procedure produces the wrong result, you do not know which section is at fault. Subqueries wrap layer upon layer, so you cannot see what the intermediate table looks like; you peel each layer apart by hand and run it separately. Inner and outer layers are coupled, so touching one thing moves everything.
Sin 3: untestable
Ad-hoc tasks have no test suite. 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. The three sins combine into an unambiguous result: almost all audit cost lands on people — and the faster AI generates, the more tired the reviewer gets.
3 SQLazy changes 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.
Three layers: AI only plans
Prompt → AI → Canonical steps → Compiler → Deterministic SQL
↑
step-by-step human review
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.
The value is that uncertainty is squeezed into one narrow slot — the planning layer. 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.
4 Key point one: make evaluation order equal reading order
The same requirement, two ways of writing it
Same longest rising streak, now as a step script:
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.
The five steps, line by line
Step one narrows the table to a single stock, and every later computation happens on that subset. Step two sorts by trading date, because “consecutive” depends on order. 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.
Step four groups by NoRisingDays and counts rows, giving the streak length of each segment; step five takes the maximum. Run any step on its own and you see an intermediate result table — if a step is wrong, open that step and you know.
The same structure holds in other domains. Take the longest run of rising monthly sales: just swap the filter for a monthly aggregation and the up/down test for a month-over-month comparison:
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; everything else stays. 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. The difference between the two styles always comes down to how many lines you touch and how many layers you re-reason about.
5 Key point two: write the script in plain language
A verb plus parameters is a compilable spec
SQLazy syntax is business verbs: filter, sort, segment, summarize, join, rank, concatenate, derive. One action per line.
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. It reads well for people and sits in AI's comfort zone; the SQL that actually runs against the database is produced by the compiler — it was never something people should write, nor something models should write.
And the third ailment cures itself along the way
Steps force names, intermediate results get names, and the flood of temporary tables disappears. People used to create piles of tmp_ tables in the database just to inspect intermediate results, and nobody ever cleaned them up. Now intermediate results exist only as step names in the script: preview them when needed, no trace when not.
6 Debugging: putting a step debugger back into SQL

In the SQLazy IDE the left pane holds the step script; click a line and the right pane shows that step's intermediate result set — no second window, no hand-editing the SQL and re-running it. In the original 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, instead of waiting for a report with absurd numbers to land in front of you.
This amounts to a native step debugger for SQL. Native SQL cannot offer it — its grammar has no concept of a “line”; a whole statement is one indivisible unit, so it can only be debugged as a whole.
7 One-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:

Figure The same logic compiled into the ClickHouse dialect (SQLazy compile dialog)
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. Look at what the compiler did with it: 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 look at what is missing: 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 point: the logic is audited once. Recompile against another database and the result is deterministically identical. It matters most for some niche databases — few people know their dialects well, brute-force translation is expensive and risky, while compiled output can be reproduced again and again.
8 The closed loop of human-machine division of labor
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. AI's efficiency, the compiler's determinism, and human business judgment — nobody oversteps.
9 Assetization: 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 then ask: 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, you have the model write SQL again from the document, and 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 it is 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 ...
After reverse translation it is a white box: reverse-engineered into a linear step script.
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
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.
The key point: 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.”
10 Stored 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.
Two capabilities deliberately given up
Give up portability. No claim of write once, run anywhere. Database syntax and capabilities differ too much — sequences, pagination, hierarchical queries, cursor syntax all vary, there is no universal mapping, and forced migration is costly and risky.
Give up debuggability. No simulating runtime debugging inside the script. A stored procedure is more than a linear flow: it has writes and consistency requirements, branches and loops. Express all of that in the script and it becomes too complex, and database differences are impossible to emulate.
Say both of these out loud first, and the design that follows can stay light.
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.
11 SPL: host language and performance backstop
SPL as the host language: flow is not bound to the database, portability and debuggability come back
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.
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, which helps complex computation, cursor scenarios in particular.
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 / stored procedures (Oracle / DB2 / …) are reverse-translated through AI + the SQLazy semantic layer into logic-preserving, auditable steps, then routed by performance. The majority (80–90%) compiles as usual into native target SQL and runs natively on ClickHouse / Snowflake / …, where performance is already sufficient; a minority (10–20%)is hand-optimized on top of the compiled result into a high-performance SPL script that runs on the SPL engine (in-memory / file / hybrid computation).
So most cases compile as usual and a few fall back to SPL; performance bottlenecks can ultimately all be solved by rewriting.
12 Compared 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 (its runtime results serve as ground truth) → AI direct translation (swap source syntax for target syntax) → target code (execute on the target database) → run both and compare (if they differ, ask AI for another round).
The problem is this feedback loop: mismatch → regenerate → compare again, potentially dozens of rounds — while the three gaps below are never filled.
Asset view: comprehension debt is only relocated; the target code still needs a human reader
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 sample data is not 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 — syntax rewriting cannot do it
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
Conventional AI approach: documents and code drift apart, comprehension debt is only relocated
The flow is: legacy code → interpret into a document → understand the document → regenerate → target code.
① First pass: read the original code plus the document, and confirm they match.
② On every change: read the updated document plus the new code, and confirm again.
Comprehension debt moves onto the document and the new code. Change once, check once.
AI + SQLazy: the script is documentation and code, comprehension debt is repaid in one go
The flow is: legacy code → reverse-translate into a script → SQLazy script → compiler → target code.
① First pass: read the original code plus the script; human verification is still required.
② Afterwards: edit the script → compile; no cross-checking needed.
The script is documentation and code; verification happens only once.
The key difference: interpret into a document and you check on every change; reverse-translate into a script and you verify once. The cost is not in the first migration — it is in every maintenance cycle after it.
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, changeable, portable — three words, three things. Understandable means the black box is reverse-translated into white-box steps, so comprehension debt is repaid rather than relocated. Changeable means logic is documentation, one line per step, and a metric-definition change touches only its step. Portable means 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.
SPL Official Website 👉 https://www.esproc.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.esproc.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/sxd59A8F2W
Youtube 👉 https://www.youtube.com/@esProc_SPL