End-to-End Text2SQL with Large Language Models: A Practical Workflow
This article explains how to turn LLM Text2SQL from a one-shot prompt into an end-to-end application for high-constraint settings such as credit risk, operations analysis, and monitoring. It covers technical paradigms, credit-risk requirements, a generate–validate–execute–repair pipeline, and engineering practices for schema retrieval, semantic metrics, permissions, evaluation, and auditability.
In tightly constrained settings such as bank risk control, business analysis, and operations monitoring, the hard part of Text2SQL is not producing SQL that merely runs. The query must be correct on business definitions, safe on permissions, stable in results, auditable in process, and recoverable on failure. A single prompt can support a demo, but end-to-end reproduction still requires schema pruning, metric injection, disambiguation of natural language, SQL validation, fallback on execution failure, result explanation, and online evaluation.
This article is not tied to a specific platform. Using generic workflow orchestration as a reference, it discusses how to expand LLM Text2SQL from a point capability into an application. The target is: given a natural-language question, the system performs intent recognition, schema retrieval, semantic parsing, SQL generation, static validation, permission review, read-only execution, result explanation, and audit logging. When confidence is low or validation fails, it should clarify or hand off to a human rather than send bad SQL to the database.
Technical paradigms: from rules to a closed workflow
Text2SQL has broadly moved through rule templates, deep sequence generation, pretrained language models, and large language models. Rules depend on templates, lexicons, and syntax trees; they are controllable and explainable but limited in coverage. Sequence models improved generalization but remained unstable on schema linking and nested queries. Pretrained models learned structured mappings from large corpora and performed better on specific datasets, still needing task adaptation. LLMs unify understanding, SQL generation, correction, and explanation in one generation framework, making end-to-end workflows feasible.
In the LLM stage, common approaches fall into three lines that can be combined with execution feedback.
First, prompt engineering. Carefully designed prompts guide SQL generation: zero-shot, few-shot, chain-of-thought, and self-correction. Zero-shot fits simple, single-table questions. Few-shot constrains style and joins via examples. Chain-of-thought splits complex questions into find tables, find columns, define filters, define aggregations, and define ordering. Self-correction has the model check table names, columns, aggregation definitions, and syntax. Cost is low and iteration is fast, but stability depends on prompt structure and schema descriptions.
Second, fine-tuning. Instruction tuning, multi-task tuning, or architecture adaptation on domain data makes the model more familiar with table structures, question distributions, and SQL dialects. Fine-tuning can improve format following in-domain, but needs high-quality labels and ongoing maintenance when schemas change. In practice it usually complements retrieval and constrained validation rather than replacing prompts.
Third, retrieval augmentation and a semantic layer. Full schemas cannot all fit in context. The system should retrieve relevant tables, columns, metric definitions, synonyms, and historical examples, then build a compact prompt. The semantic layer maps business terms such as “multi-lender application count,” “overdue customer count,” and “channel distribution” to fixed definitions, reducing unconstrained generation.
Fourth, workflow orchestration with execution feedback. Split Text2SQL into nodes: intent routing, schema retrieval, metric resolution, SQL generation, static validation, permission review, read-only execution, explanation, and audit. Execution results and errors can flow back for a limited number of repairs, forming generate–validate–execute–repair. For high-constraint settings, this is closer to production than a single prompt.
Requirements in credit risk
Credit risk has many tables, many metric definitions, complex permissions, and high compliance needs. A typical question might be: “Among customers with more than five multi-lender loan applications in the last 30 days and current overdue days over 30, report distinct customer counts by channel.” It includes a time window, business events, filters, aggregation dimensions, and distinct-count semantics. The model must correctly interpret the 30-day window, the institution scope of multi-lender activity, the definition of current overdue, the source of the channel dimension, and how distinct customers are counted.
Requirements should cover at least five areas. First, schema scale and relationships: how customer, application, loan, repayment, risk-event, and channel tables join; which fields are keys; which have slowly changing history. Second, metric definitions: the same term may have multiple calculations and must be fixed in the semantic layer. Third, permissions and compliance: row-level filters, column masking, read-only accounts, timeouts, and audit trails. Fourth, ambiguity: missing time range, customer scope, or metric definition should trigger clarification, not guessing. Fifth, explainability: results should include query definitions, filters, and tables and columns used so business users can review.
In end-to-end reproduction, put answerability first. For questions outside the data, involving sensitive fields, or missing required definitions, return a clarifying question or hand off. An extra turn can materially reduce wrong queries and compliance risk.
End-to-end workflow
A reproducible Text2SQL workflow can include the following nodes.
Input preprocessing and intent routing. Normalize the question and classify it as data query, metric explanation, definition clarification, or off-topic. Reject or hand off write, delete, or sensitive-field requests.
Schema retrieval and pruning. Retrieve related tables, columns, keys, enums, and descriptions. Keep highly relevant tables plus necessary join tables; avoid an oversized context that causes missed constraints.
Business semantics and metric resolution. Map terms to semantic-layer metrics, dimensions, filters, and synonyms. For example, map “overdue more than 30 days” to fixed status codes and time conditions, and “channel” to the channel dimension field.
Example selection and prompt construction. Retrieve similar high-quality Q&A examples and combine them with schema, metrics, permission context, and output constraints. Require read-only SQL, permission filters, and a row limit.
SQL generation and candidate reranking. Generate multiple candidates and rerank by syntax validity, schema hit rate, example similarity, and permission constraints. For complex questions, decompose then merge subqueries.
Static validation and permission review. Check table and column names, functions, aggregation definitions, joins, and dangerous operations; detect writes, missing time ranges, missing permission filters, and Cartesian products. On failure, run limited repair.
Read-only execution and result checks. Execute with a read-only account, timeout, max rows, and masking. Reassess empty results, unusually large results, and missing fields; clarify or fall back if needed.
Explanation and audit. Convert results into business language with query definitions, time range, filters, tables and columns, status, and latency. Log the question, candidate SQL, validation, execution, and any human handoff.
Illustrative pseudocode:
pipeline(question, user_context):q = normalize(question)intent = route_intent(q)if intent not in ["query", "metric"]:return handoff(q, reason="intent_not_supported")schema = retrieve_schema(q, user_context, top_k=8)metrics = resolve_metric(q)examples = retrieve_examples(q, schema)prompt = build_prompt(q, schema, metrics, examples, user_context)candidates = generate_sql(prompt, n=3)for sql in rerank(candidates):errors = validate(sql, schema, user_context)if errors:sql = repair(sql, errors, prompt)if not validate(sql, schema, user_context):continueif not authorize(sql, user_context):continueresult = execute_readonly(sql, timeout_ms=3000, max_rows=1000)if result.error:continueanswer = explain(result, q, metrics)audit(q, sql, result, user_context)return answerreturn handoff(q, reason="low_confidence_or_validation_failed")
The point is not a specific implementation, but placing generation inside a validate–authorize–execute–explain–audit loop. In production, cap repair attempts so latency and cost stay bounded.
Engineering practice and optimization
Start with a semantic layer: not a field dictionary, but metrics, dimensions, synonyms, filter templates, lineage, and permission rules. Schema descriptions should cover table purpose, field meaning, enums, keys, common joins, and forbidden fields. Maintain an example library by scenario: single-table filters, multi-table joins, window aggregations, definition explanations, permission filters, disambiguation, and unanswerable questions.
Build evaluation with the workflow. Scenario-based sets should track SQL validity, execution success, result accuracy, result consistency, human-handoff rate, average latency, and cost per query. In risk control, result accuracy should outrank raw execution success, because executable but wrong-definition SQL is more dangerous.
Security and observability are required. On the database side: read-only accounts, row-level security, column masking, timeouts, and max rows. On the application side: audit logs, alerts, and failure taxonomy. Failure types can include schema miss, missing metric, insufficient permission, syntax error, timeout, empty result, and unresolved ambiguity, each with a different fallback.
Optimization can focus on five areas: better schema linking via retrieval, reranking, and normalized descriptions; stronger decomposition of multi-step questions; execution feedback for limited repair; high-quality fine-tuning data from historical Q&A and human corrections; and cache, rate limits, and cost control, including reuse of frequent metric queries and approval or pre-aggregation for expensive ones.
Overall, end-to-end LLM Text2SQL is not reproducing a single prompt call. It is an engineering system around trustworthy query. Combining paradigms, scenario requirements, workflow nodes, safety constraints, and evaluation makes Text2SQL maintainable and auditable in credit risk and similar high-constraint environments.
