{"slug": "from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator", "title": "From Natural Language to SQL with AI: Building an Intelligent SQL Query Generator Using Hugging Face and Streamlit", "summary": "A developer built a Text-to-SQL application using Hugging Face Transformers and Streamlit that converts natural language questions into SQL queries. The system uses a T5-based model to generate SQL from plain English, executes it against a SQLite database, and displays results via a Streamlit dashboard. The project demonstrates how AI can enable non-technical users to query databases without knowing SQL syntax.", "body_md": "Introduction\n\nWriting SQL queries is a fundamental skill for developers, data analysts, and database administrators. However, not everyone knows SQL syntax, and even experienced developers spend time writing repetitive queries.\n\nRecent advances in Generative AI and Large Language Models (LLMs) make it possible to convert plain English into SQL automatically. Instead of writing:\n\nSELECT name, salary\n\nFROM employees\n\nWHERE department = 'IT'\n\nORDER BY salary DESC;\n\nA user can simply ask:\n\n\"Show me all IT employees ordered by salary from highest to lowest.\"\n\nThe AI translates the request into SQL.\n\nIn this article, we'll build a Text-to-SQL application using:\n\nPython\n\nStreamlit\n\nHugging Face Transformers\n\nSQLite\n\nSQLAlchemy\n\nWe'll also discuss real-world applications, limitations, and best practices.\n\nWhy Text-to-SQL Matters\n\nOrganizations generate massive amounts of structured data stored in relational databases.\n\nBusiness users often need answers without knowing SQL.\n\nExamples include:\n\nSales managers checking monthly revenue\n\nHR departments analyzing employee records\n\nFinance teams generating reports\n\nCustomer support searching order history\n\nAI enables these users to retrieve information using natural language.\n\nProject Architecture\n\nUser Question\n\n│\n\n▼\n\nHugging Face Model\n\n│\n\n▼\n\nGenerated SQL Query\n\n│\n\n▼\n\nSQLite Database\n\n│\n\n▼\n\nResults\n\n│\n\n▼\n\nStreamlit Dashboard\n\nThe workflow is simple:\n\nUser enters a question.\n\nAI generates SQL.\n\nSQL executes against SQLite.\n\nResults appear instantly.\n\nTechnologies Used\n\nTechnology Purpose\n\nPython Backend\n\nStreamlit Web Interface\n\nHugging Face LLM for Text-to-SQL\n\nSQLAlchemy Database connection\n\nSQLite Sample database\n\nInstalling Dependencies\n\npip install streamlit\n\npip install transformers\n\npip install torch\n\npip install sqlalchemy\n\npip install pandas\n\nCreating a Sample Database\n\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\"sqlite:///company.db\")\n\nengine.execute(\"\"\"\n\nCREATE TABLE employees(\n\nid INTEGER PRIMARY KEY,\n\nname TEXT,\n\ndepartment TEXT,\n\nsalary INTEGER\n\n)\n\n\"\"\")\n\nInsert sample data:\n\nengine.execute(\"\"\"\n\nINSERT INTO employees(name, department, salary)\n\nVALUES\n\n('Alice','IT',7500),\n\n('Bob','Sales',5200),\n\n('Carol','IT',8900)\n\n\"\"\")\n\nLoading a Hugging Face Model\n\nOne popular Text-to-SQL model is based on T5.\n\nfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM\n\nmodel_name = \"tscholak/1wnr382e\"\n\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\nmodel = AutoModelForSeq2SeqLM.from_pretrained(model_name)\n\nConverting Natural Language into SQL\n\nquestion = \"Show employees working in IT\"\n\ninputs = tokenizer(question, return_tensors=\"pt\")\n\noutputs = model.generate(**inputs)\n\nsql = tokenizer.decode(outputs[0], skip_special_tokens=True)\n\nprint(sql)\n\nPossible output:\n\nSELECT *\n\nFROM employees\n\nWHERE department='IT';\n\nExecuting the SQL\n\nimport pandas as pd\n\nresult = pd.read_sql(sql, engine)\n\nprint(result)\n\nOutput:\n\nid name department salary\n\n1 Alice IT 7500\n\n3 Carol IT 8900\n\nBuilding the Streamlit Interface\n\nimport streamlit as st\n\nquestion = st.text_input(\"Ask your database\")\n\nif st.button(\"Generate SQL\"):\n\nsql = generate_sql(question)\n\n```\nst.code(sql, language=\"sql\")\n\nresult = pd.read_sql(sql, engine)\n\nst.dataframe(result)\n```\n\nNow users only need to type questions such as:\n\nShow all employees\n\nList employees in Sales\n\nAverage salary by department\n\nHighest paid employee\n\nReal-World Applications\n\nBusiness Intelligence\n\nEmployees can generate reports without learning SQL.\n\nHealthcare\n\nDoctors can retrieve patient records using natural language.\n\nBanking\n\nAnalysts can summarize transactions through conversational queries.\n\nE-commerce\n\nManagers can ask:\n\n\"Which products sold the most last month?\"\n\ninstead of writing complex SQL.\n\nChallenges\n\nAlthough Text-to-SQL is impressive, it has limitations.\n\nDatabase Schema Understanding\n\nThe AI performs much better when it understands the database schema.\n\nSQL Validation\n\nGenerated SQL should always be validated before execution.\n\nNever execute AI-generated SQL directly in production.\n\nSecurity\n\nRestrict permissions to read-only whenever possible.\n\nAvoid allowing AI to execute:\n\nDELETE\n\nUPDATE\n\nDROP\n\nALTER\n\nwithout human approval.\n\nBest Practices\n\n✅ Provide the database schema as context.\n\n✅ Validate SQL syntax.\n\n✅ Limit user permissions.\n\n✅ Log generated queries.\n\n✅ Review queries before execution.\n\nPublic GitHub Example\n\nA complete open-source implementation can be found in projects like:\n\n[https://github.com/vanna-ai/vanna](https://github.com/vanna-ai/vanna)\n\n[https://github.com/defog-ai/sqlcoder](https://github.com/defog-ai/sqlcoder)\n\n[https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain) (SQL agents)\n\nThese repositories demonstrate production-ready approaches for natural language querying over SQL databases.\n\nFuture Improvements\n\nSome ideas to extend this project include:\n\nPostgreSQL support\n\nMySQL support\n\nSQL Server support\n\nQuery explanation\n\nChart generation\n\nConversational memory\n\nRetrieval-Augmented Generation (RAG)\n\nIntegration with local LLMs using Ollama\n\nConclusion\n\nText-to-SQL is transforming how users interact with relational databases. By combining Hugging Face, Streamlit, and Python, developers can build applications that allow anyone to query databases using natural language.\n\nWhile these systems require careful validation and security controls, they significantly lower the barrier to accessing structured data and improve productivity for both technical and non-technical users.\n\nAs open-source AI models continue to improve, conversational database interfaces will become an increasingly common feature in modern data applications.\n\nReferences\n\nHugging Face Transformers: [https://huggingface.co/docs/transformers](https://huggingface.co/docs/transformers)\n\nStreamlit Documentation: [https://streamlit.io](https://streamlit.io)\n\nSQLAlchemy Documentation: [https://docs.sqlalchemy.org](https://docs.sqlalchemy.org)\n\nVanna AI: [https://github.com/vanna-ai/vanna](https://github.com/vanna-ai/vanna)\n\nSQLCoder: [https://github.com/defog-ai/sqlcoder](https://github.com/defog-ai/sqlcoder)", "url": "https://wpnews.pro/news/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator", "canonical_source": "https://dev.to/vincenzo_rafaelllanosni/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator-using-hugging-3cgj", "published_at": "2026-07-10 18:50:12+00:00", "updated_at": "2026-07-10 19:16:59.382927+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "natural-language-processing", "ai-tools", "developer-tools"], "entities": ["Hugging Face", "Streamlit", "SQLite", "SQLAlchemy", "T5", "Python"], "alternates": {"html": "https://wpnews.pro/news/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator", "markdown": "https://wpnews.pro/news/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator.md", "text": "https://wpnews.pro/news/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator.txt", "jsonld": "https://wpnews.pro/news/from-natural-language-to-sql-with-ai-building-an-intelligent-sql-query-generator.jsonld"}}