End-to-End Engineering Practices for LLM-Based Text2SQL
While Text2SQL (Natural Language to SQL) is not a new problem, Large Language Models (LLMs) have transformed it from a barely functional concept to a practically applicable solution. This article explores why Text2SQL deserves renewed attention and outlines mainstream technical paradigms, ranging from rules to LLMs. We will dive into three primary LLM-based approaches—Prompt Engineering, model fine-tuning, and Retrieval-Augmented Generation (RAG)—and detail an end-to-end workflow through a credit risk management use case. Finally, we discuss key engineering practices and optimization directions for building scalable and reliable Text2SQL systems in production environments.
I. Why Text2SQL Deserves Renewed Attention
Text2SQL (Natural Language to SQL) is not a new problem, but the emergence of Large Language Models (LLMs) has shifted it from being merely “usable” to genuinely “applicable.” Previous methods based on rules and deep learning always had limited generalization capabilities when dealing with real-world business scenarios such as complex table structures, multi-table joins, and nested aggregations. With strong language understanding and code generation capabilities, LLMs make the goal of “allowing business users to query databases directly using natural language” practically feasible in engineering for the first time.
However, simply throwing table structures and questions at an LLM often yields unstable results. To build a production-ready system, it is necessary to understand the evolution of technical paradigms, design workflows tailored to specific business scenarios, and continuously optimize at the engineering level.
II. Mainstream Technical Paradigms: From Rules to LLMs
Looking at the technical evolution, Text2SQL has roughly gone through four stages:
- Rule-based methods: Generate SQL through syntax analysis, pattern matching, and template filling. The advantage is controllability and interpretability, but the disadvantage is an extremely narrow coverage; slightly complex phrasing will cause failures.
- Deep learning models: Encode questions and schemas and then use seq2seq to generate SQL. Generalization improved, but it relies heavily on labeled data and has weak cross-database migration capabilities.
- Pre-trained language models: Pre-trained on general corpora and then fine-tuned for Text2SQL tasks. Representative approaches include multi-task pre-training and schema linking ranking, achieving significant improvements on academic benchmarks.
- The LLM era: Leveraging prompt engineering, fine-tuning, or Retrieval-Augmented Generation (RAG) to let LLMs directly accomplish generation tasks, which has become the mainstream practice in the industry today.
Current LLM-based solutions can be categorized into three main routes.
2.1 Prompt Engineering Approach
This is the most lightweight route. The core lies in carefully designed prompts to guide the LLM in generating SQL. Common techniques include:
- Zero-shot prompting: Directly providing the table structure (DDL statements or field descriptions) and the natural language question, letting the model generate SQL in one step.
- Few-shot prompting: Embedding several “question-SQL” examples in the prompt to help the model understand task patterns and output formats, particularly useful for correcting expression habits specific to certain tables.
- Chain-of-Thought (CoT): Requiring the model to first decompose the question—identifying involved tables, filter conditions, aggregation methods, and time ranges—before assembling the SQL step-by-step. This significantly improves the accuracy of complex queries.
- Self-correction: After generating SQL, appending a validation prompt to let the model check for syntax errors, field existence, and logical consistency with the question intent, forming a “generate-check-correct” loop.
The advantage of this route is low development cost and fast iteration; the disadvantage is that the ceiling is limited by the model’s inherent capability, making it prone to hallucinations when encountering private domain terminology and complex schemas.
2.2 Model Fine-tuning Approach
When there is high-quality domain-specific “question-SQL” annotated data, fine-tuning can be considered:
- Instruction fine-tuning: Constructing the Text2SQL task as an instruction dataset to train the model to follow a unified output specification.
- Multi-task fine-tuning: Simultaneously training on two sub-tasks: schema linking (identifying relevant tables and fields) and SQL generation, improving overall generalization.
- Architecture-specific fine-tuning: Adjusting training strategies based on the input structure of the task (e.g., how the schema and question are concatenated).
The fine-tuning route can achieve more stable results than pure prompting in vertical domains, but it requires continuous data construction and training operational costs. It is suitable for enterprise scenarios where query patterns are relatively fixed and data accumulation is sufficient.
2.3 RAG (Retrieval-Augmented Generation) Approach
The RAG strategy is “retrieve first, generate later,” providing the model with sufficiently clear context through external knowledge. This is currently the mainstream choice for enterprise-level deployment:
- Schema retrieval: Based on natural language queries, retrieving the most relevant tables and fields from the full table structure repository, avoiding stuffing dozens or hundreds of tables into the context.
- Example retrieval: Recalling historical similar “question-SQL” pairs based on vector similarity as few-shot examples, dynamically injecting them into the prompt.
- Document retrieval: Introducing business metric documents (e.g., indicator definitions, field business meanings) to solve specification issues like “how to calculate the overdue rate.”
- Historical query retrieval: Maintaining context in multi-turn conversations to support follow-up questions, coreference resolution, and query modification.
These three routes are not mutually exclusive. In engineering practice, the most common combination is “RAG for context + Prompt Engineering for generation guidance + Python for post-processing and execution,” which is exactly the structure used in the case study below.
III. Use Case Analysis: Data Q&A in Credit Risk Management
Taking the credit risk management strategy scenario as an example, let’s illustrate the complete design of an end-to-end system. The risk management team frequently needs to query metrics such as loan volume, overdue rate, approval rate, and roll rate. Traditional methods rely on data engineers writing SQL on a scheduled basis, which creates obvious efficiency bottlenecks. A self-service analysis Q&A system built with Text2SQL allows strategy analysts to ask questions directly in natural language.
3.1 Workflow Deep Dive
An end-to-end workflow aligned with best practices typically includes the following nodes:
- Intent recognition and security validation: Determine whether the user input is a data query question, while intercepting risks such as unauthorized access and sensitive field requests.
- Schema retrieval: Vectorize the question and perform similarity search against a pre-built table structure knowledge base (including table descriptions, field comments, business specifications) to recall relevant schema fragments.
- Example retrieval: Recall top-N similar cases from the historical “question-SQL” repository as few-shot examples.
- SQL generation: Assemble the recalled schemas, examples, and user question into the prompt, guiding the model to generate SQL via CoT, and force the output into a structured format (e.g., JSON, containing fields like SQL, involved tables, confidence score) for easy downstream parsing.
- SQL validation: Use a Python code node for static checks—field whitelist validation, syntax parsing, and blocking DDL/DML operations. If it fails, return a correction prompt to regenerate.
- Execution and post-processing: Execute the SQL on a read-only account, catch exceptions and return error messages to trigger a retry; upon successful execution, use Python to organize the results into tables, chart descriptions, or natural language summaries.
- Answer organization: The LLM combines the query results with the original question to generate the final answer with data interpretation, such as providing values, specification notes, and brief analysis.
A schematic prompt skeleton for generation is as follows:
You are a senior data analyst. Given the following database schema:{Recalled table structures and field descriptions}Here are similar question examples:{Retrieved few-shot examples}Please analyze the question: "{User question}"Thinking steps:1. Determine which tables and fields are needed2. Clarify filter conditions (time, product, customer segment)3. Determine aggregation methods and metric specifications4. Output a valid read-only SELECT statement, returned in JSON format
3.2 Key Design Considerations
- Specification prioritization: Documenting the calculation specifications for metrics like “overdue rate” and “loan volume” and incorporating them into the retrieval base is the primary element to ensure trustworthy results.
- Minimal privilege: Use read-only accounts at the execution layer, and apply field-level permission filtering again at the application layer.
- Failure fallback: When SQL execution fails, pass the database error message back to the model for automatic correction. Usually, one round of retry can solve most syntax issues.
- Result interpretability: Attach the SQL in the final answer so users can verify the logic and build trust.
IV. Engineering Practices and Optimization Directions
- Continuous governance of the schema knowledge base: Synchronously update the knowledge base when table structures change; supplementing business semantic descriptions for each field is the most cost-effective investment for improving retrieval quality.
- Flywheel mechanism for the example library: Deposit manually validated high-quality “question-SQL” pairs into the library, making the system more accurate as it is used.
- Evaluation system construction: Build a domain evaluation set to continuously regress from two dimensions: execution accuracy and result accuracy, avoiding “blind optimization.”
- Multi-turn dialogue support: Maintain conversation state through historical query retrieval, supporting follow-up questions like “What about last week?” or “Only look at Product A.”
- Complex query orchestration: For complex questions spanning multiple metrics, first let the model decompose them into a sub-query plan, then generate and execute them individually before aggregating.
V. Conclusion
LLM-based Text2SQL is essentially a systems engineering endeavor that synergizes “retrieval-augmented context construction + structured prompt guidance + code-layer validation and execution.” Relying solely on model capabilities cannot meet production requirements. Only by solidifying schema governance, specification management, permission control, and evaluation loops can natural language data querying transition from a demo to large-scale deployment. Orchestrating the above nodes on an AI Agent workflow platform, combined with Python for validation and post-processing, is a proven, replicable best practice path in the industry today.
