An AI-powered Natural Language Interface for Relational Databases (NLIDB) that translates plain English queries into executable, standards-compliant SQL using Google's Gemini Large Language Model.
- Overview
- Why It Matters
- Key Features
- Tech Stack
- Architecture & Workflow
- AI/ML Implementation & Prompt Engineering
- Practical Applications
- Project Structure
- Installation & Setup
- Usage & Sample Scenarios
- Engineering Decisions & Technical Depth
- Roadmap & Future Enhancements
- Learning Outcomes
- Author & Connect
- License
The English-to-SQL Query Generator bridges the gap between natural language comprehension and relational database querying. By leveraging Google's state-of-the-art Gemini LLM through the official google-genai SDK, this application converts everyday English requests into structured SQL syntax in real time.
Built with a focus on clean software design, strict output formatting, and prompt engineering, the project provides a responsive, interactive Command-Line Interface (CLI) that enables both technical and non-technical stakeholders to formulate database queries seamlessly.
Relational databases power modern enterprise applications, but extracting insights typically demands familiarity with SQL dialects, clause structures (JOIN, GROUP BY, HAVING), and filtering syntax.
- For Business & Operations Teams: Eliminates dependence on data engineering teams for routine ad-hoc queries, accelerating decision-making.
- For Developers & Analysts: Reduces context switching and boilerplate query drafting, serving as an intelligent query-authoring assistant.
- For AI/Data Engineering: Demonstrates foundational concepts of Natural Language to SQL (NL-to-SQL), a cornerstone capability in modern Agentic RAG pipelines and conversational analytics architectures.
- Zero-Shot NL-to-SQL Translation: Direct mapping from intent-rich natural language expressions to ANSI SQL queries.
- Strict Format Enforcement: Multi-tier sanitization combining negative constraint prompting with deterministic string cleaning to strip Markdown wrappers (
sql ...). - Interactive Session Loop: Persistent CLI session supporting consecutive query generations without process re-initialization.
- Defensive Error Handling: Input validation against empty queries and resilient handling of upstream API connection timeouts and exceptions.
- Environment Isolation: Zero-hardcoding security architecture isolating API credentials and configurable model identifiers via
.env.
| Domain | Technology | Role / Purpose |
|---|---|---|
| Language | Python 3.10+ | Core application logic and CLI runtime |
| AI / LLM SDK | Google Gen AI SDK (google-genai) |
Modern client interface for Google Gemini API models |
| Foundation Model | Google Gemini Flash | High-speed, cost-effective inference for code & structured generation |
| Configuration | python-dotenv | Secure runtime environment variable injection |
| Version Control | Git & GitHub | Source control, issue tracking, and repository management |
The following sequence outlines the end-to-end data lifecycle from user prompt entry to sanitized SQL output:
sequenceDiagram
autonumber
actor User
participant CLI as CLI Interface (main.py)
participant Engine as Prompt Engine
participant GenAI as Google GenAI Client
participant Model as Gemini LLM
participant Sanitizer as Output Sanitizer
User->>CLI: Enters English instruction
CLI->>CLI: Validate input (check non-empty)
CLI->>Engine: Construct constrained prompt
Engine->>GenAI: Dispatch generate_content request
GenAI->>Model: Run inference (Zero-Shot SQL generation)
Model-->>GenAI: Return raw model response
GenAI-->>Sanitizer: Stream response payload
Sanitizer->>Sanitizer: Strip markdown backticks & leading/trailing whitespace
Sanitizer-->>CLI: Return clean SQL string
CLI-->>User: Display formatted SQL query
- Input Ingestion & Validation: Captures string input via standard input; strips whitespace and guards against null/empty payloads.
- Constrained Prompt Assembly: Wraps input with directive rules restricting natural language pleasantries, explanations, or code-block formatting.
- Inference Execution: Sends the payload to Gemini using
client.models.generate_contentwith configurable model targets. - Post-Processing & Output Scrubbing: Normalizes output by removing accidental markdown code blocks (
```sql/```) to ensure terminal-ready query text. - Interactive Lifecycle: Prompts the user to continue or terminate gracefully.
- Selected Model Family: Google Gemini (e.g.,
gemini-2.5-flashorgemini-1.5-flash). - Rationale: Optimized for sub-second latency, high instruction fidelity, and structural token generation (SQL/JSON), providing cost-effective generation suitable for real-time developer tooling.
Large language models frequently default to conversational filler ("Sure! Here is your query:") and Markdown code formatting. To guarantee consistent query output for downstream consumption:
contents = f"""
Convert the following English sentence into an SQL query.
Rules:
- Return only the SQL query.
- Do not explain anything.
- Do not use Markdown.
- Do not use code blocks.
English:
{query}
"""Because generative models may occasionally include markdown fences despite negative constraints, the application implements a defense-in-depth sanitization layer:
sql = response.text.strip()
sql = sql.replace("```sql", "")
sql = sql.replace("```", "").strip()- Schema Agnosticism: Currently operates without database schema context (DDL); table names and column attributes are inferred from user wording rather than actual database catalogs.
- Dialect Specificity: Defaults to standard ANSI SQL. Advanced dialect-specific extensions (e.g., PostgreSQL JSONB, BigQuery arrays, SQLite-specific pragmas) require explicit mention in the prompt.
- Self-Service Analytics: Embedded into internal slackbots or dashboards to assist non-technical team members in querying read-replicas.
- Database Exploration: Helps junior developers quickly formulate multi-table
JOINconditions and window functions (ROW_NUMBER(),RANK()). - Data Pipeline Ingestion: Serves as a modular subsystem for automated natural-language ETL filters.
English-to-SQL-Query-Generator/
│
├── main.py # Application entry point, CLI loop, LLM call, and sanitizer
├── requirements.txt # Locked production dependencies
├── .env # Local secrets (API keys, model configuration) - excluded from git
├── .gitignore # Git ignore file for venv, caches, and .env
└── README.md # Comprehensive project documentation
- Python: Version
3.10or higher - Gemini API Key: Obtainable from Google AI Studio
git clone https://github.com/soumyadip-das-dev/English-to-SQL-Query-Generator.git
cd English-to-SQL-Query-GeneratorOn Windows (PowerShell):
python -m venv venv
.\venv\Scripts\Activate.ps1On macOS / Linux:
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtCreate a .env file in the root directory:
GEMINI_API_KEY=your_google_gemini_api_key_here
MODEL_NAME=gemini-2.5-flashNote: Ensure
.envis listed in your.gitignoreto prevent committing sensitive credentials.
Run the main application:
python main.py==================================================
English to SQL Generator
==================================================
Convert English into SQL using Gemini LLM
==================================================
Enter Your English Query: Find the top 5 highest-earning employees in the Engineering department hired after 2022
Generated SQL:
SELECT *
FROM employees
WHERE department = 'Engineering'
AND hire_date > '2022-12-31'
ORDER BY salary DESC
LIMIT 5;
Generate another SQL query? (y/n): y
Enter Your English Query: Calculate the average order amount per customer for completed orders in 2023
Generated SQL:
SELECT customer_id, AVG(order_amount) AS average_order_amount
FROM orders
WHERE status = 'Completed'
AND order_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY customer_id;
Generate another SQL query? (y/n): n
Thank you for using English to SQL Generator!
Instead of deprecated legacy libraries (google-generativeai), this project adopts the modern Google Gen AI SDK (google-genai v2.x), ensuring long-term API support, structured response models, and compatibility with Google's latest Gemini models.
Relying solely on LLM instruction following can result in sporadic formatting issues. Combining negative prompt constraints with deterministic string normalization ensures the output can be directly redirected or piped into SQL query runners without syntax errors.
The architecture decouples the generation logic (generate_sql()) from the control loop (main()), making it straightforward to refactor the core translation function into a REST API endpoint (e.g., FastAPI) or a GUI component (e.g., Streamlit).
- Schema-Aware Generation (DDL Grounding): Ingest database schemas or
sqlite3/PostgreSQL table catalogs to eliminate column/table hallucination. - Direct Execution Engine: Add an optional read-only execution module to run generated queries against connected databases and return formatted tabular results.
- Dialect Selector: Add support for explicit target dialects (PostgreSQL, MySQL, SQLite, Snowflake, BigQuery).
- Web & API Interfaces: Develop a Streamlit web interface and a FastAPI microservice wrapper with OpenAPI documentation.
- SQL Validation & Syntax Highlighting: Integrate
sqlparsefor syntax validation, auto-formatting, and ANSI terminal syntax colorization.
- AI/LLM Engineering: Hands-on experience with LLM API orchestration, system prompting, negative constraint formulation, and output sanitization.
- Python Engineering: Designing robust CLI applications, virtual environment management, clean dependency resolution, and defensive error handling.
- Relational Data Modeling: Translating diverse relational algebra requirements (projections, selections, aggregations, joins) into standardized SQL syntax.
Contributions are welcome! If you'd like to improve the prompt design, add tests, or introduce new features:
- Fork the repository (
https://github.com/soumyadip-das-dev/English-to-SQL-Query-Generator). - Create a feature branch (
git checkout -b feature/schema-grounding). - Commit your changes (
git commit -m "feat: add schema-aware SQL translation"). - Push to the branch (
git push origin feature/schema-grounding). - Open a Pull Request.
This project is licensed under the MIT License. See the LICENSE file for details.
Soumyadip Das
Aspiring Software Engineer & AI/ML Engineer
B.Tech in Computer Science & Engineering (AI & ML)
- GitHub: @soumyadip-das-dev
- Repository: English-to-SQL-Query-Generator