End-to-End Text2SQL with Fine-Tuning: Approaches and Engineering Practices

    This article presents an end-to-end fine-tuning approach to Text2SQL, covering task constraints, why fine-tuning is needed in enterprise settings, three common fine-tuning strategies, data construction and training practices, evaluation metrics, and production deployment techniques such as constrained decoding and execution feedback.

    End-to-End Text2SQL with Fine-Tuning: Approaches and Engineering Practices

    1. Overview of the Text2SQL Task

    Text2SQL, also called NL2SQL, converts natural language questions from users into SQL queries that can be executed on a database. It is essentially a sequence-to-sequence translation task, but unlike traditional machine translation, its output must satisfy three constraints at the same time: the SQL must be syntactically valid, semantically faithful to the user’s intent, and precisely aligned with the target database schema. These three constraints define the core challenge for large language models: the model must understand not only language, but also table structures, field types, foreign key relationships, and business definitions.

    Reproducing a Text2SQL system end to end usually involves four stages: data and schema preparation, model selection and fine-tuning, inference and execution validation, and evaluation and iteration. This article focuses on the fine-tuning-based technical route.

    2. Why Choose Fine-Tuning

    Although general-purpose large language models have strong language understanding capabilities, they often perform inconsistently in real enterprise scenarios for several reasons:

    1. Domain terminology mismatch: Business metrics and field naming can differ from general semantics. For example, “active user” may have different definitions across companies.
    2. Insufficient schema generalization: When the model has not seen the target database schema, it may hallucinate tables or fields that do not exist.
    3. SQL dialect differences: Different databases have different syntax details, and a general model may not follow the target dialect.
    4. Complex query capability: Multi-table joins, nested subqueries, window functions, and similar scenarios require targeted examples for guidance.

    Fine-tuning continues training on a specific dataset to embed domain knowledge into model parameters. This can significantly improve accuracy and output stability in these scenarios while reducing the prompt engineering burden and token cost during inference.

    3. Three Main Fine-Tuning Approaches

    3.1 Instruction Fine-Tuning

    Instruction fine-tuning converts the Text2SQL task into supervised sample pairs of “instruction + database schema + user question → SQL”, teaching the model to follow task instructions. A typical sample structure is as follows:

    1. {
    2. "instruction": "According to the following database schema, translate the user question into SQL.",
    3. "schema": "CREATE TABLE orders (order_id INT, user_id INT, amount DECIMAL, created_at DATE);",
    4. "question": "What is the total spending per user in 2024?",
    5. "output": "SELECT user_id, SUM(amount) FROM orders WHERE YEAR(created_at)=2024 GROUP BY user_id;"
    6. }

    Design considerations:

    • Instruction diversity: Describe the same intent in multiple ways to improve robustness to instruction variations.
    • Balanced samples: Cover different difficulty levels, including single-table queries, multi-table queries, aggregation, sorting, and time filtering.
    • Negative and correction samples: Add common errors and correction examples to reduce the occurrence of hallucinated fields.

    3.2 Multi-Task Fine-Tuning

    Multi-task fine-tuning trains the model on multiple related tasks at the same time, for example:

    • Question-to-SQL generation;
    • Schema linking, which determines which tables and fields are involved in the question;
    • SQL-to-natural-language reverse explanation;
    • SQL correctness judgment or error correction.

    Its value lies in the fact that tasks share language and structural knowledge, enabling the model to develop a deeper understanding of the relationship among question, schema, and SQL. This improves generalization and alleviates the problem of insufficient data for a single task. In practice, mixed sampling and task identifier prefixes can be used to organize training batches.

    3.3 Architecture-Specific Fine-Tuning

    This approach adapts the model structure or training objective to the characteristics of Text2SQL. Common ideas include:

    • Two-stage paradigm: Perform schema linking first, then generate SQL based on the linking result, reducing the search space during generation;
    • Encoder-decoder structure: Use the encoder to model the interaction between the question and schema, and the decoder to generate SQL step by step;
    • Structure-aware objective functions: Add skeleton constraints or execution result feedback during training to improve the syntax validity rate.

    This type of method is suitable for core systems with extremely high accuracy requirements, but its engineering complexity is higher.

    4. Data Construction and Training Practices

    High-quality data is key to successful fine-tuning. The following process is recommended:

    1. Schema collection: Extract DDL statements, field comments, enum values, and foreign key relationships from the target database.
    2. Question generation: Generate natural language questions based on schema templates and real user logs, covering different expression styles and difficulty levels.
    3. SQL annotation and validation: Manually write SQL or generate it with model assistance, then actually execute it in a sandbox database and keep only samples that are executable and produce correct results.
    4. Data augmentation: Generate synonymous rewrites of questions for the same schema; introduce distractor tables and fields to train the model’s robustness to noise.
    5. Training configuration: Parameter-efficient fine-tuning, such as LoRA, can significantly reduce compute requirements. A small learning rate is advisable to prevent catastrophic forgetting. Execution Accuracy on the validation set is recommended as the early-stopping metric.

    A simplified pseudo-code example for training data cleaning:

    1. def build_sample(schema, question, sql, engine):
    2. try:
    3. expected = engine.execute(sql)
    4. return {"schema": schema, "question": question, "sql": sql}
    5. except Exception:
    6. return None # Drop samples with syntax errors

    5. Evaluation and Production Deployment

    Evaluation metrics should cover the following:

    • Execution accuracy: The proportion of generated SQL queries whose execution results match the gold answer. This is the metric closest to business value.
    • Exact match rate: String-level comparison with the gold SQL, for reference only.
    • Syntax validity rate and schema hit rate: Used to identify weak points in the model.
    • Efficiency metrics: First-token latency and throughput, which affect the online experience.

    Common engineering techniques for production deployment include:

    1. Constrained decoding: Restrict the model to referencing only tables and fields that actually exist.
    2. Execution feedback retry: When SQL execution fails, pass the error information back to the model for correction.
    3. Result caching: Cache answers for frequently asked questions.
    4. Human-in-the-loop: Route low-confidence queries to manual review and form a data feedback loop for continuous model iteration.

    6. Conclusion

    Fine-tuning-based Text2SQL solutions align task objectives through instruction fine-tuning, enhance generalization through multi-task fine-tuning, and strengthen structural understanding through architecture-specific fine-tuning. Each path has its own focus: small and medium-sized teams can start with instruction fine-tuning, while those pursuing higher performance ceilings can combine multi-task and two-stage strategies. What ultimately determines the system’s ceiling is often engineering details such as schema modeling, data quality, and the execution feedback loop. Only by combining a fine-tuned model with schema constraints, execution validation, and data feedback can teams build stable and usable natural language data query capabilities.