Building an End-to-End Text2SQL System with LLMs: Lessons from Credit Risk Analytics
Text2SQL powered by large language models can turn natural-language questions into reliable, executable queries—but only when retrieval, validation, permissions, and controlled execution are combined into a closed loop. This article presents an end-to-end approach for credit and risk teams, covering the three main engineering paradigms (prompt engineering, task-oriented fine-tuning, and retrieval-augmented generation), a seven-stage workflow from question normalization to result interpretation, and practical guidance on evaluation, knowledge base management, and security boundaries.
Credit and risk teams rely heavily on structured data for underwriting decisions, credit limits, delinquency monitoring, and strategy review. Business users can clearly describe questions like “approval rates for a product line over the past 90 days, rejection reason breakdown, and period-over-period change”—but they can rarely write reliable SQL themselves. The value of Text2SQL lies in reliably converting these natural-language questions into executable queries, and, when needed, handing results to analysis scripts for aggregation, comparison, and pre-visualization computation. This article is not a one-off prompt demo. Instead, it lays out a reproducible end-to-end solution: understanding the question, aligning it with data schemas, generating and validating queries, optionally executing controlled scripts, and interpreting results back into business language.
Technical Evolution and Three Common Paradigms
Text2SQL has roughly evolved through four stages: rule-based templates, specialized deep learning models, pretrained language models, and general-purpose large language models. Rule-based methods relied on synonym tables, slot filling, and fixed sentence patterns. They covered narrow cases and had high maintenance costs, but they’re still useful as reference for strongly constrained fields. Specialized and early pretrained models proved the feasibility of “schema encoding plus decode generation” on public benchmarks, but often suffered from training distribution constraints, cross-database generalization issues, and annotation costs. In the LLM era, the goal is no longer correctly generating a query in one shot. Instead, systems combine retrieval, reasoning, execution feedback, and permission control into a closed loop.
Three engineering approaches are common today. They can be used individually or layered together.
The first is prompt engineering. The system provides table descriptions, field meanings, metric definitions, and the user’s question to the LLM, which writes the query directly. Zero-shot prompting is fast to implement and suits exploration over schemas with few fields and stable definitions. Few-shot prompting, which includes example question–query pairs in the prompt, significantly reduces arbitrary choices around join conditions and aggregate functions. Step-by-step reasoning asks the model to first identify metrics, time windows, filter dimensions, and grouping granularity before assembling the query—well suited to multi-table joins. Self-correction adds a post-generation review pass, checking the query against the schema, null semantics, time granularity, and business restrictions. Prompt engineering ships quickly, but is sensitive to prompt length, example quality, and model stability. Complex metric definitions can still end up “looking plausible but wrong.”
The second is task-oriented model adaptation. When you have high-quality annotations or can automatically construct question–query pairs, you can use task instructions, auxiliary tasks, or training objective designs targeted at query generation. Adaptation raises consistency and format compliance in specific scenarios. However, data preparation, evaluation set maintenance, and version rollback are costly. When the domain changes fast and schemas are frequently adjusted, a single round of training can’t easily cover new metric definitions, so fine-tuning works better as a generating backbone than the sole knowledge source.
The third is retrieval augmentation. Rather than stuffing every schema description into context, relevant tables, fields, metric definitions, historical Q&As, and metric documentation are retrieved per question, and the model generates within a bounded context. Schema retrieval answers “which tables to look at,” example retrieval answers “how such questions are usually written,” document retrieval covers business definitions such as approval rate, first delinquency, observation period, and history retrieval serves multi-turn follow-ups. For lending scenarios, retrieval augmentation is usually more controllable than simply extending prompts, and makes syncing metric changes to the knowledge base easier than retraining.
A robust combination is: retrieval supplies the correct context, prompts constrain reasoning steps and output format, execution feedback catches syntax and result anomalies, and small-scale adaptation is used where needed to improve format stability and domain-term understanding. These are not mutually exclusive.
What Credit Risk Users Are Actually Asking
Risk analytics questions are rarely “dump everything from one table.” Typical requests involve strategy effectiveness, channel quality, rejection reasons, limit utilization, post-disbursement performance, and observation-window comparisons. These share several constraints.
Metric definitions must be unique. “Approval rate” might mean application approved, credit approved, or drawdown approved; the denominator might be number of applications or deduplicated customers. The applicable date might be the application date, decision date, or disbursement date. If the knowledge base doesn’t pin down definitions, the model guesses from the wording and reports diverge from the official warehouse.
Schemas must be linkable. Terms like “product line,” “channel,” and “rejection code” must map to real fields, enums, and dimension tables—not same-named columns with different meanings. Multi-table joins must also respect primary/foreign keys and grain: avoid multiplying customer-level metrics against loan-contract-level metrics.
Permissions must come first. Lending data often contains identities, contact information, and account identifiers. Even when a user’s question is legitimate, the system can only expose the databases, tables, columns, and row ranges visible to that user’s role. Access trimming should happen at generation time—if you trim the schema used for generation himself will remove sensitive columns afterward. Permission checks should also be re-run each round of a multi-turn conversation; you can’t carry over data from a previous turn the user couldn’t see.
If a query fails validation, truncated feedback should be fed back to the model for a bounded number of corrections, logging each diff to avoid infinite retries.
Results must be explainable and auditable. The business side needs to see which table was used, which date field, which filters, and whether these match the metric documentation. Returning only a number cannot support strategy review.
Many requirements exceed the comfort zone of a single query: binning, period-over-period change, quantiles, simple strategy simulations, or reshaping query results into analysis tables. A reasonable boundary here: queries handle data retrieval, controlled scripts handle in-memory secondary computation, and both are audit-logged. Scripts should never have arbitrary write access, outbound network calls, or access to environment secrets.
The End-to-End Workflow
The full pipeline can be summed up as seven steps: Understand → Retrieve → Plan → Generate → Validate → Execute → Explain. Every step has well-defined inputs and outputs, so each can be evaluated independently.
Understand. Normalize the colloquial question: extract metrics, dimensions, time ranges, comparison modes, ordering, and row limits. Vague words like “recent” or “performing poorly” should be converted to configurable defaults or sent back to the user for clarification. We can’t silently guess critical (or security-critical) definitions.
Retrieve. Use the normalized question as the query to fetch table cards, field cards, metric definitions, and similar Q&As. A table card must include purpose, grain, primary keys, date fields, refresh frequency, and any restrictions. Field cards include type, enums, null meaning, and sensitivity level. Results should be deduplicated and truncated by relevance so extraneous tables don’t confuse the model.
Plan. Emit a structured analysis plan before writing any SQL. It might include: referenced metric definitions, candidate tables, join paths, filter conditions, aggregation grain, and whether script post-processing is needed. The plan makes it easy to spot-check by hand, and to determine whether a generation failure is a definition or schema problem.
Generate. Only use objects that appear in the plan, and emit a single read-only query. Ideally have the justification nearby: heard for choosing a date field, dedup approach, and denominator definition. Use fixed output format so the pipeline can parse the response.
Validate. Split between static and dynamic checks. Static checks flag: read-only restrictions, object whitelists, sensitive columns, missing time-bound predicates, joins that cause grain blowup, and aggregates that don’t match group-by clauses. Dynamic runs do a trial execution in a read-only, resource-limited, timeout environment and inspect error messages. Failed error feedback should be fed back to the model for a limited number of retries, and each retry diff must be logged to prevent infinite loops.
Execute. Return the result set for validated queries. If the plan declares post-processing, hand results to a sandboxed analysis script that only has the agreed computational libraries and can’t do file or network I/O of its own.
Explain. Restate the metric definitions, sample size, and key findings in business terms, and include the auditable query and plan. Explanations should align with the actual results and never fabricate comparisons that weren’t in the query.
Below is an illustrative intermediate representation for pipeline orchestration. It describes structure, not a specific platform’s interface:
plan:metric: application approval rategrain: dailytime_field: apply_datefilters: [product = specified product, window = last 90 days]tables: [application, decision]postprocess: aggregate by day and compute period-over-period changesql: <read-only query>checks: [readonly, whitelist, row_limit, explain_ok]
Engineering Practice and Optimization Direction
**Evaluate on business slices,棒“没rarely just string equality. The same question often has multiple valid queries. Track: correct schema linking, execution success, result matching against the benchmark, sensitive-object leakage, average retries, and latency. For lending scenarios, separately track three failure classes—wrong date field, wrong dedup, and wrong denominator—since they most commonly produce “runs fine but unusable” results.
Keep the knowledge base well maintained. Schema changes, enum updates, and definition revisions should all be versioned. Retrieval documents should be written in business language, not a pile of column names. Sample Q&As must be human-reviewed before entering the knowledge base—one bad example can badly mislead the model. For high-frequency questions, cache a mapping from question intent to an already-validated query, but cache keys should include the metric-definition version and permission scope.
Hardcode the security boundary in the executor, not the prompt. Read-only accounts, table whitelists, row and scan limits, timeouts, sensitive column masking, audit logs—all are enforced by the runtime. Model output is just a candidate; the model never grants execution authorization.
Balance cost and experience. Simple questions should use compact prompts and few-shot examples; enable multi-step reasoning and second-pass correction only for complex ones. When retrieval fails or key slots are missing, ask clarifying questions rather than forcing a generation. For high-risk queries, offer a “confirm before execute” flow with a human checkpoint.
Optimization typically starts with codifying metric definitions and table cards, then hardening static validation and execution feedback, then curating high-quality examples, and only then considering model adaptation. The first three set the ceiling; adaptation mostly improves stability and marginal accuracy. If results are still霭unstable, the user probably needs to look back at the grain modeling and metric conflicts, not stack more prompts.
Final Thoughts
Modern LLM-driven Text2SQL changes the problem from “translate one sentence” to “organize an analysis around metric definitions, permissions, and evidence.” Credit and risk analytics makes a good worked example because it stresses schema linking, date-field semantics, sensitive data access, and lightweight post-query computation. By chaining retrieval, planning, read-only generation, automatic validation, and controlled execution into a closed loop—and insisting on auditable results—a system can go beyond one-off demos to a truly reusable natural-language analytics capability. With cloud platforms offering vector retrieval, read-only compute, sandboxed execution, and audit logging, this pipeline can be assembled from existing building blocks—without betting correctness on any single prompt.
