Local LLMs for SQL Generation: Build Your Own Text-to-SQL

Text-to-SQL is one of the most practical business applications of local LLMs. Connecting a language model to your database schema lets non-technical users query data in plain English — without sending your sensitive business data to OpenAI's servers. Here's how to build it with locally-run models.

Why local matters here: Your database schema reveals your entire business structure. Sending it to a cloud API is a significant data exposure risk. Local LLMs keep everything on your infrastructure. For hardware capable of running SQL-focused models, LLMHardware.io has recommendations starting under $500.

Best Models for SQL Generation

SQLCoder-7B (from Defog) is fine-tuned specifically for SQL and outperforms GPT-4 on Text-to-SQL benchmarks for complex queries. Llama 3.1 8B Instruct with schema-in-context performs reasonably well. Codestral 22B excels at multi-table joins and subqueries. For production use, always fine-tune on your specific schema — even a small LoRA adapter trained on 100 examples dramatically improves accuracy.

Building the Pipeline

The basic pipeline: (1) extract schema as CREATE TABLE statements, (2) inject into system prompt, (3) take user question, (4) generate SQL, (5) execute against database, (6) return results. Use LangChain's SQLDatabaseChain or build it directly with the Ollama Python API. Always sandbox SQL execution — use a read-only database user and validate queries for dangerous keywords (DROP, DELETE, TRUNCATE) before execution.

Improving Accuracy

Schema clarity matters enormously. Add descriptive comments to your CREATE TABLE statements — columns named "c1", "c2" will produce poor SQL regardless of model quality. Include sample data rows in the prompt for ambiguous columns. Use few-shot examples of common queries. Implement a verification step where the model checks its own SQL before execution. Chain-of-thought prompting ("first identify relevant tables, then construct the query") improves accuracy by 15-25% on complex joins.

Comments

Popular posts from this blog

AMD RX 9070 XT for Local LLMs: ROCm Performance Guide (2026)

llama.cpp flash attention: how to enable and benchmark

SillyTavern with Local LLMs: Complete Setup for AI Companions