A fine-tuned Mistral-7B model for generating PostgreSQL queries from natural language questions. This model uses LoRA (Low-Rank Adaptation) for efficient fine-tuning on the Spider text-to-SQL benchmark dataset.
Model Description
This model converts natural language questions into PostgreSQL queries given a database schema. It was trained using parameter-efficient fine-tuning (LoRA) on the Spider dataset, which contains complex SQL queries across 200+ database domains.
1defgenerate_sql(schema:str, question:str)->str:2"""Generate SQL query from natural language question."""34 prompt =f"""<s>[INST] You are a SQL expert. Given the following PostgreSQL database schema, write a SQL query that answers the user's question.
56Database Schema:
7{schema}89Question: {question}1011Generate only the SQL query without any explanation. [/INST]"""1213 inputs = tokenizer(prompt, return_tensors="pt").to(model.device)1415with torch.no_grad():16 outputs = model.generate(17**inputs,18 max_new_tokens=256,19 temperature=0.1,20 do_sample=True,21 top_p=0.95,22 pad_token_id=tokenizer.eos_token_id
23)2425 response = tokenizer.decode(outputs[0], skip_special_tokens=True)26# Extract SQL after the prompt27 sql = response.split("[/INST]")[-1].strip()28return sql
2930# Example usage31schema ="""
32CREATE TABLE customers (
33 customer_id SERIAL PRIMARY KEY,
34 name VARCHAR(100),
35 email VARCHAR(100),
36 created_at TIMESTAMP
37);
3839CREATE TABLE orders (
40 order_id SERIAL PRIMARY KEY,
41 customer_id INTEGER REFERENCES customers(customer_id),
42 total DECIMAL(10,2),
43 order_date DATE
44);
45"""4647question ="Find the top 5 customers by total order amount"4849sql = generate_sql(schema, question)50print(sql)
Expected Output
sql
1SELECT c.name,SUM(o.total)as total_amount
2FROM customers c
3JOIN orders o ON c.customer_id = o.customer_id
4GROUPBY c.customer_id, c.name
5ORDERBY total_amount DESC6LIMIT5;
Prompt Format
This model uses the Mistral instruction format:
<s>[INST] You are a SQL expert. Given the following PostgreSQL database schema, write a SQL query that answers the user's question.
Database Schema:
{schema}
Question: {question}
Generate only the SQL query without any explanation. [/INST]
Important Notes
Always include the full database schema in the prompt
Use PostgreSQL-style syntax in your schema (SERIAL, VARCHAR, etc.)
The model generates only the SQL query, not explanations
For best results, keep questions clear and specific
Limitations
PostgreSQL Only: The model is trained on PostgreSQL syntax. SQLite or MySQL queries may have syntax differences.
Schema Required: The model requires the database schema as context. It cannot generate queries without knowing the table structure.
Complex Nested Queries: While the model handles most SQL operations, extremely complex nested subqueries may not always be accurate.
Domain-Specific Terms: The model works best with common database domains. Highly specialized terminology may require clearer questions.
No Query Validation: The model generates SQL based on patterns learned during training. Always validate generated queries before execution.
Context Length: Very large schemas (>50 tables) may exceed the model's context window.
Ethical Considerations
SQL Injection: Generated queries should be parameterized before use in production applications
Data Privacy: Do not include sensitive data in prompts
Validation: Always review generated SQL before executing on production databases
Spider is a large-scale complex and cross-domain semantic parsing and text-to-SQL dataset annotated by 11 Yale students. It consists of 10,181 questions and 5,693 unique complex SQL queries on 200 databases with multiple tables covering 138 different domains.
Citation (Spider Dataset)
bibtex
1@inproceedings{yu2018spider,
2 title={Spider: A Large-Scale Human-Labeled Dataset for Complex and Cross-Domain Semantic Parsing and Text-to-SQL Task},
3 author={Yu, Tao and Zhang, Rui and Yang, Kai and Yasunaga, Michihiro and Wang, Dongxu and Li, Zifan and Ma, James and Li, Irene and Yao, Qingning and Roman, Shanelle and others},
4 booktitle={Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing},
5 pages={3911--3921},
6 year={2018}
7}