LLM Text-to-SQL: An End-to-End Engineering Reproduction Guide
This article provides a comprehensive guide to building an end-to-end Large Language Model (LLM) text-to-query system. Moving beyond simple SQL generation, it details a controlled data analysis pipeline that includes requirement clarification, metadata retrieval, security validation, and result interpretation. The guide covers technological evolution, implementation routes, and delves into a specific engineering workflow for credit risk control to ensure verifiable, executable, and explainable analytical processes.
1. From “Generating Queries” to “Completing Analysis”
Using Large Language Models (LLMs) to convert natural language into database query statements is merely the starting point of a text-to-query system. What enterprises truly need is a system that, upon receiving a business question, can understand the meaning of metrics, locate the correct data, securely perform calculations, and provide traceable analytical conclusions.
Taking credit risk control as an example, a user might ask:
Compare the loan performance across different customer acquisition channels in the second quarter of this year, identify the channels with significantly higher delinquency rates, and explain the possible reasons.
Behind this statement lie several issues that must be explicitly clarified:
- Does “loan performance” refer to the loan disbursement scale, delinquency rate, or loss rate?
- What is the threshold (in days) for defining a loan as “overdue”?
- Is the denominator calculated based on the number of loans, the number of customers, or the outstanding loan balance?
- Does “second quarter” refer to the disbursement period or the scheduled repayment period?
- Should loans that have not yet passed their complete observation period be included in the comparison?
- Does “significantly higher” mean higher relative to the overall level, or does it reach a specific business threshold?
If the question is handed directly to the model to generate a query, the resulting statement might be syntactically correct but yield business-wise erroneous results. Therefore, the core of an end-to-end system is not to generate a query in one shot, but to establish a controlled data analysis pipeline:
Natural Language Question → Requirement Clarification → Metadata Retrieval → Analysis Plan → Query Generation → Security Validation → Data Execution → Programmatic Calculation → Result Interpretation.
In this pipeline, the LLM is responsible for understanding and organizing information, the database handles deterministic queries, the program ensures reproducible calculations, and permission and audit mechanisms define the boundaries of execution.
2. Technological Evolution and Three Implementation Routes
2.1 Four Stages of Technological Development
From a technological perspective, text-to-query has roughly evolved through four stages. This division helps understand the shifts in primary methodologies, though there are no strict chronological boundaries between them.
Stage 1: Rules and Templates.
Systems generate queries through keyword matching, syntax rules, and predefined templates. For fixed reports, fixed metrics, and limited question phrasing, these solutions are easy to control and audit. However, their coverage is limited. Slight variations in business phrasing may require new rules, and maintenance costs escalate when dealing with complex joins, nested queries, or new metrics.
Stage 2: Task-Specific Deep Learning Models.
Models learn the mapping between natural language and query structures, reducing the need for manual rules. However, their effectiveness heavily relies on the scale and quality of the training data, as well as its alignment with the actual database schema.
Stage 3: Pre-trained Language Models.
Pre-trained models offer stronger language understanding capabilities, which are then adapted for query generation through task-specific training. At this stage, database schema representation, field association, and query structure prediction remain critical engineering challenges.
Stage 4: LLM-Driven Composite Systems.
LLMs can combine natural language, table structures, metric descriptions, and examples to generate queries, while also participating in requirement clarification and error correction. However, model capabilities do not replace data governance; actual performance is still constrained by metadata quality, business definitions, and execution boundaries.
2.2 Prompt-Driven: Suitable for Rapid Prototyping
Prompt-driven approaches typically provide the model with:
- The user’s question and confirmed conditions;
- Accessible tables and fields;
- Relationships between tables;
- Metric definitions and boundary conditions;
- A small number of audited query examples;
- Output structure and prohibited actions.
For small to medium-sized data domains, this approach can quickly produce a working prototype. However, longer prompts are not necessarily better. Stuffing the context with a large amount of irrelevant table structures can increase field confusion and raise API costs. A more rational approach is to filter relevant metadata first and then generate the query.
For complex tasks, you can require the model to output a short, checkable analysis plan—including target metrics, filter conditions, join paths, and aggregation granularity—rather than relying on unaudited, free-form reasoning.
2.3 Model Adaptation: Suitable for Stable and Repetitive Tasks
When an enterprise has a sufficient number of high-quality “business question—correct query” samples, it can consider adapting the model for specific tasks. This approach is suitable for scenarios with relatively fixed terminology, repetitive query structures, and stable database schemas. For example, when the same type of risk monitoring queries continuously appears and the query audit process is already mature.
However, model adaptation does not mean permanently embedding business definitions into the model. After schema changes, field deprecation, or metric upgrades, knowledge must be updated and re-evaluated. More importantly, training samples must be governed. Erroneous queries, outdated metrics, and samples containing sensitive information will become sources of future system risk.
2.4 Retrieval-Augmented Generation and Execution Feedback: Suitable for Production
This route breaks the task into multiple steps:
- Retrieve tables, fields, and metrics relevant to the question;
- Generate candidate queries based on the retrieved results;
- Use programs to check query structure and permissions;
- Execute in a controlled environment;
- Perform limited repairs based on error types;
- Validate results against business rules before generating explanations.
Its advantage is not “guaranteeing the model is always right,” but making errors easier to discover, locate, and block.
The above three routes can be combined. A common practice is to establish a baseline using prompts and retrieval first, then deciding whether model adaptation is necessary based on evaluation results, rather than investing in training from the start.
3. Defining Metrics and Data Boundaries in Risk Control Scenarios
3.1 Converting Ambiguous Questions into Analysis Contracts
It is recommended to convert user questions into structured analysis contracts:
Analysis Object: LoansGrouping Dimension: Customer Acquisition ChannelTime Field: Disbursement DateTime Range: Specified quarter, left-closed and right-openTarget Metric: 30-day delinquency rate based on loan countObservation Scope: Loans that have completed the required observation periodComparison Baseline: Overall delinquency rate within the same statistical scopeOutput Content: Channel metrics, difference ranking, definition notes
The most crucial part here is distinguishing between “existing explicit standards” and “assumptions requiring user confirmation.” If the enterprise has established unified metric definitions, they can be directly referenced and displayed to the user. If unified definitions do not exist, clarification is mandatory; the model should never decide the denominator, delinquency threshold, or time range on its own.
3.2 Fixing Data Granularity to Prevent Duplicate Counting
For demonstration purposes, assume there is a sample loan performance snapshot table:
loan_performance_snapshot- snapshot_date: Data snapshot date- loan_id: Loan identifier- channel_code: Customer acquisition channel code- disbursement_date: Loan disbursement date- observation_complete_date: Required observation period completion date- dpd30_flag: Whether a 30-day or more delinquency occurred during the observation period
It is agreed that under the same snapshot date, each loan has only one record; dpd30_flag takes a value of 0 or 1 for loans with completed observation periods.
This is merely a schematic model to explain the implementation method. A real system might use installment details, repayment transactions, or event records, requiring aggregation to a clear loan granularity before calculating metrics based on loan count. If a single loan is associated with multiple repayment records, directly joining and counting will inflate the denominator. Simply using distinct counts may not fix all issues either, as amount summation and overdue flag aggregation can still be distorted.
3.3 Clarifying Observation Periods and Selection Bias
Recently disbursed loans that have not yet undergone a full observation period will often underestimate risk if directly included in delinquency rate calculations. Therefore, the system should explicitly distinguish between:
- All loans disbursed within the time range;
- Loans with completed observation periods;
- Loans with incomplete observation periods;
- Loans with completed observation periods that experienced the target delinquency event.
Note that counting only loans with completed observation periods alters the sample composition. If different channels have varying disbursement time distributions, the comparison results may be affected by the proportion of mature samples. Therefore, the results should simultaneously disclose the number of mature samples and coverage, rather than just showing a single percentage.
4. End-to-End Workflow Node Design
4.1 Request Access and Permission Identification
When a request enters the system, it should bind the user identity, tenant scope, role permissions, and session identifier. Permissions cannot merely exist in the prompt. The database access layer must enforce read-only access, row-level restrictions, and sensitive field limitations. Even if the model generates an unauthorized statement, it should not be able to actually read inaccessible data.
4.2 Intent Recognition and Requirement Clarification
First, determine whether the user is querying a metric, comparing groups, analyzing trends, or requesting a modification to business rules. Missing information can be handled in two categories:
- Display preferences that do not affect core conclusions: use explicit default values;
- Metric definitions, time fields, and observation periods that alter statistical results: prioritize asking the user for confirmation.
For requests like “explain the reasons,” additional judgment is needed to see if the existing data supports attribution. Having only channel delinquency rates typically reveals differences but cannot prove that the differences are caused by the channels themselves.
4.3 Metadata Retrieval and Association Path Selection
Metadata should include not only table and field names but also:
- Business meaning and common synonyms;
- Field types and enumeration descriptions;
- Primary keys, foreign keys, and cardinality;
- Table record granularity;
- Metric definitions and applicable scopes;
- Data update times;
- Known data quality issues;
- Access permissions.
The retrieval process can first locate the business domain, then select candidate tables, and finally determine fields and join paths. Table comments, sample content, and external documents should be treated as data to be interpreted, not as system instructions, to prevent anomalous text within them from altering workflow behavior.
4.4 Analysis Plan and Query Generation
Before generating a query, form a checkable plan:
1. Read the loan performance snapshot for the specified date.2. Filter loans disbursed in the specified quarter.3. Retain only loans with completed observation periods.4. Count the total loans and overdue loans by acquisition channel.5. Calculate the difference between channel delinquency rates and the overall rate.
Subsequently, generate the query and return the referenced tables, fields, definitions, and parameters. Query values should be passed via parameter binding supported by the database driver, not by directly concatenating user input. Table and column names generally cannot be bound as regular value parameters and must be selected through a programmatically maintained allowlist.
4.5 Static Validation and Cost Control
The generated query should enter an independent validation node, checking at least:
- Is there only one allowed query for execution?
- Does it contain write, delete, or schema alteration operations?
- Does it access objects outside the allowed scope?
- Are there unapproved functions or external access?
- Are necessary tenant and time conditions missing?
- Is there a multi-table combination without join conditions?
- Might it return sensitive details?
- Does it exceed execution time, scan scope, or returned row limits?
Checks should be at the Abstract Syntax Tree (AST) level, not just searching for a few dangerous keywords. Read statements can also cause side effects through specific functions, so read-only accounts, function restrictions, and execution isolation are indispensable. Additionally, limiting returned rows does not equal limiting scan costs; an aggregate query might scan massive amounts of data even if it only returns ten rows.
4.6 Controlled Execution and Limited Error Correction
Upon execution failure, first categorize the error type:
- Syntax error;
- Non-existent field;
- Type incompatibility;
- Insufficient permissions;
- Resource limits;
- Data quality anomaly.
Syntax and field issues can be attempted for repair; insufficient permissions cannot be “fixed” by switching tables or bypassing limits; insufficient resources should trigger query replanning or a request to narrow the scope. Error correction must have a limited number of retries, retaining each candidate statement and failure reason. Once the limit is reached, an explicit status should be returned, rather than continuously trying until a seemingly usable result appears.
5. Coordinating Query and Programmatic Calculation
5.1 Database Handles Filtering and Aggregation
Below uses a question mark to represent a placeholder for a schematic value parameter; the actual binding method depends on the database driver.
SELECTchannel_code,COUNT(*) AS mature_loan_count,SUM(CASE WHEN dpd30_flag = 1 THEN 1 ELSE 0 END)AS overdue_loan_count,1.0 * SUM(CASE WHEN dpd30_flag = 1 THEN 1 ELSE 0 END)/ NULLIF(COUNT(*), 0) AS overdue_rateFROM loan_performance_snapshotWHERE snapshot_date = ?AND disbursement_date >= ?AND disbursement_date < ?AND observation_complete_date <= ?GROUP BY channel_code;
This query is built upon the aforementioned data contract. Before execution, verify that loan identifiers are unique within the same snapshot and check that delinquency flags for mature loans are complete. The time range uses a left-closed, right-open format to help reduce boundary omissions when mixing dates and times.
5.2 Program Handles Post-processing and Deterministic Calculation
After the database returns the aggregated channel results, the program can calculate the overall baseline, channel differences, and display sorting. Below is schematic Python code:
def compare_channels(rows):total_count = sum(r["mature_loan_count"] for r in rows)overdue_count = sum(r["overdue_loan_count"] for r in rows)if total_count == 0:return {"status": "no_mature_samples", "items": []}overall_rate = overdue_count / total_countitems = []for row in rows:count = row["mature_loan_count"]if count <= 0:continuerate = row["overdue_loan_count"] / countitems.append({"channel": row["channel_code"],"sample_count": count,"overdue_rate": rate,"difference_pp": (rate - overall_rate) * 100})return {"status": "ok","overall_rate": overall_rate,"items": sorted(items,key=lambda item: item["difference_pp"],reverse=True)}
The overall delinquency rate must be calculated by dividing the total overdue count by the total sample count; you cannot simply average the channel delinquency rates. Percentage point differences and relative increases also need to be distinguished. For example, a rise from 2% to 3% means an increase of 1 percentage point, but a relative increase of 50%. Mixing these concepts will exaggerate or downplay risk changes.
The program execution environment should restrict file access, network access, and resource consumption. Fixed functions can be used to process aggregate results, without needing to let the model arbitrarily generate and execute code for the sake of flexibility.
5.3 Statistical Conclusions Cannot Rely Solely on Sorting
Small-sample channels might show a high proportion due to a few delinquency events. The system should display sample sizes and prompt result stability based on confirmed rules. If determining “significantly higher,” further clarification is needed:
- Whether to use a business threshold or statistical testing;
- Whether to compare against the overall sample or other channels excluding itself;
- Whether factors like disbursement month and product structure need to be controlled;
- Whether simultaneous comparison across multiple channels requires handling multiple testing issues.
A channel and the overall sample containing that channel are not two independent samples; independent sample comparison methods cannot be directly applied.
6. Result Interpretation Must Be Constrained by Evidence
An analysis report can be divided into four layers:
- Statistical Scope: Time interval, snapshot date, observation period, and sample size.
- Direct Findings: Which channel metrics are higher than the baseline, and by how much.
- Interpretation Boundaries: Whether samples are sufficient, and whether uncontrolled structural differences exist.
- Next Steps: Which dimensions to supplement, and which business hypotheses to verify.
For example, the system can point out that a certain channel’s delinquency rate is high under the current definition, but it cannot assert that “this channel has severe fraud” based solely on this result. Cause validation typically requires further comparison of customer structure, product terms, credit strategies, regional distribution, and disbursement batches. Even with these dimensions added, observational analysis does not automatically equate to a causal conclusion.
When the model generates explanations, it should only cite calculated data and confirmed business definitions. Empty results should be explained as “no data matches the current conditions,” not arbitrarily interpreted as “no business risk.”
7. Evaluation, Auditing, and Continuous Optimization
7.1 Building Evaluation Sets Covering Real Boundaries
Evaluation should not only check if syntax passes but also cover:
- Simple aggregation and multi-table joins;
- Time boundaries and observation period handling;
- Deduplication and denominator selection;
- Empty results and missing values;
- Clarification of ambiguous questions;
- Permission denial and sensitive field protection;
- Cost limitations for large-scale queries;
- Error feedback and retry behavior.
Identical query text is not the only standard; different statements can have the same semantics. However, comparing only a single execution result is also insufficient: an incorrect query might coincidentally return the correct result on specific test data. Therefore, evaluation should combine definition checks, execution result comparisons, and specifically constructed boundary data.
7.2 Phased Recording of Failure Sources
It is recommended to separately track the quality of requirement understanding, metadata retrieval, query generation, execution, and result interpretation. If relevant tables are not retrieved, adding query examples may not be effective; if a statement executes successfully but has the wrong denominator, fixing the metric contract should be prioritized; if the query is correct but the explanation is distorted, result citation constraints should be strengthened.
Simultaneously monitor end-to-end latency, retry counts, scan costs, rejection reasons, and manual correction ratios, avoiding focusing solely on a single success rate.
7.3 Retaining Complete Yet Protected Audit Chains
Audit records should be able to reconstruct an analysis, including user request, clarification process, metric versions, permission scope, retrieved objects, executed statements, bound parameters, result summaries, and model configuration versions.
Logs themselves may contain sensitive information and require desensitization, access control, and retention period management. The model context should尽量 use aggregate data to avoid unnecessarily exposing personal details. For high-impact risk control decisions, system output should be positioned as analytical assistance, not as the basis for automatically adjusting credit limits, rejecting customers, or modifying production strategies.
8. Recommended Sequence for Reproduction and Deployment
End-to-end reproduction can proceed in the following order:
Step 1: Fix the Scenario. Select a few confirmed metrics and a limited data domain, and first establish manually audited standard queries.
Step 2: Connect the Pipeline. Complete requirement clarification, metadata retrieval, query generation, validation, execution, and interpretation, ensuring each step can be tested independently.
Step 3: Cover Edge Cases. Add use cases for empty results, duplicate records, insufficient permissions, timeouts, and definition conflicts.
Step 4: Introduce Programmatic Calculation. Place sorting, baseline comparison, and statistical calculations into deterministic functions, rather than leaving them to the model’s mental math.
Step 5: Establish an Evaluation Baseline. Execute regression tests after changes to the model, prompts, metadata, or metric versions.
Step 6: Gradually Expand Scope. Only open up more complex data domains after the granularity, relationships, and definitions of newly added tables have been governed.
The engineering value of LLM text-to-query lies not in showcasing a beautiful query statement, but in transforming vague business expressions into verifiable, executable, and explainable analytical processes. A reliable system must not only be able to answer questions but also know when clarification is needed, when evidence is insufficient, and when execution must be refused.
