{"id":135398,"date":"2025-07-21T15:41:33","date_gmt":"2025-07-21T12:41:33","guid":{"rendered":"https:\/\/www.javacodegeeks.com\/?p=135398"},"modified":"2025-07-21T15:42:41","modified_gmt":"2025-07-21T12:42:41","slug":"build-text-to-sql-using-llm","status":"publish","type":"post","link":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html","title":{"rendered":"Build Text-to-SQL using LLM"},"content":{"rendered":"<p>Text-to-SQL is a powerful application of large language models (LLMs) like GPT that enables users to interact with a database using natural language. Let us delve into understanding how to build Text-to-SQL using LLM.<\/p>\n<h2><a name=\"section-1\"><\/a>1. What is an OpenAI and LLM?<\/h2>\n<p><a href=\"https:\/\/www.openai.com\" target=\"_blank\" rel=\"noopener\">OpenAI<\/a> is an AI research and deployment company focused on ensuring that artificial general intelligence (AGI) benefits all of humanity. It is known for developing advanced language models like GPT-3, GPT-4, and the newer GPT-4o, which power applications such as ChatGPT. These models are capable of understanding and generating human-like language, performing tasks like summarization, question answering, translation, and even code generation. LLM stands for Large Language Model, which refers to a type of AI model trained on massive amounts of textual data to understand context, syntax, semantics, and intent in human language. LLMs leverage deep learning, particularly transformer architectures, to process and generate language across a wide range of domains and tasks. When integrated with external systems like databases or APIs, LLMs can act as powerful natural language interfaces that convert user inputs into structured queries or commands.<\/p>\n<h2><a name=\"section-2\"><\/a>2. PostgreSQL Setup on Docker and Sample Data<\/h2>\n<p>Begin by setting up a PostgreSQL container using Docker. This eliminates the need for a manual installation and provides an isolated, reproducible environment for development and testing.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">docker run --name text2sql-postgres \\\n  -e POSTGRES_USER=admin \\\n  -e POSTGRES_PASSWORD=admin123 \\\n  -e POSTGRES_DB=employees_db \\\n  -p 5432:5432 \\\n  -d postgres\n<\/pre>\n<p>This command will create a new container named <code>text2sql-postgres<\/code>, set up a database user <code>admin<\/code> with the password <code>admin123<\/code>, initialize a database named <code>employees_db<\/code>, expose port <code>5432<\/code> to allow connections from your host machine, and run the official <code>postgres<\/code> image in detached mode. After the container starts, you can interact with the database using the `psql` CLI or GUI-based tools like DBeaver or pgAdmin. To connect with `psql`, use:<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">psql -h localhost -p 5432 -U admin -d employees_db\n<\/pre>\n<p>Once connected, execute the SQL statements below to create a sample table and seed it with mock data:<\/p>\n<pre class=\"brush:sql; wrap-lines:false;\">CREATE TABLE employees (\n    id SERIAL PRIMARY KEY,\n    name VARCHAR(100),\n    department VARCHAR(100),\n    salary INTEGER\n);\n\nINSERT INTO employees (name, department, salary) VALUES\n('Alice', 'Engineering', 95000),\n('Bob', 'HR', 60000),\n('Charlie', 'Engineering', 105000),\n('Diana', 'Sales', 70000);\n<\/pre>\n<p>This will create a table named <code>employees<\/code> with basic fields for ID, name, department, and salary, and insert sample records to simulate a simple company structure. This sample data serves as a foundational dataset for testing Text-to-SQL conversions, building query interfaces, or training AI-based SQL generation models.<\/p>\n<h2><a name=\"section-3\"><\/a>3. Sample Python Example<\/h2>\n<p>We\u2019ll now use Python to connect to both Azure OpenAI\u2019s API and the PostgreSQL database using SQLAlchemy as the ORM layer. This integration enables us to dynamically generate SQL queries using natural language inputs and execute them securely against the database.<\/p>\n<h3>3.1 Dependencies<\/h3>\n<p>The following Python packages are required to build this integration:<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">pip install openai sqlalchemy psycopg2-binary python-dotenv\n<\/pre>\n<h3>3.2 Python Code<\/h3>\n<p>Create a <code>main.py<\/code> file and add the following code to implement the complete flow that connects your Python application to Azure OpenAI and PostgreSQL using SQLAlchemy. The script allows users to input natural language questions, convert them to SQL using OpenAI, and execute those queries on the database.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<pre class=\"brush:python; wrap-lines:false;\"># Author: Yatin B.\n\nimport logging\nimport re\nfrom os import getenv\n\nimport sqlalchemy\nfrom dotenv import load_dotenv\nfrom openai import AzureOpenAI\nfrom sqlalchemy import text\nfrom sqlalchemy.exc import SQLAlchemyError\n\n# ========== Setup Logging ==========\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s - %(levelname)s - %(message)s\"\n)\nlogger = logging.getLogger(__name__)\n\n# ========== Load Environment ==========\nload_dotenv()\n\n# ========== Constants ==========\nTABLE_NAME = \"employees\"\nDB_URL = 'postgresql:\/\/username:password@hostname:5432\/company'\n\n\n# ========== Setup Clients ==========\n\ndef get_openai_client() -&gt; tuple[AzureOpenAI, str | None]:\n    \"\"\"Initialize and return an Azure OpenAI client.\"\"\"\n    api_key = getenv('OPENAI_API_KEY')\n    api_version = getenv('OPENAI_API_AZURE_API_VERSION')\n    api_endpoint = getenv('OPENAI_API_AZURE_API_ENDPOINT')\n    deployment = getenv('OPENAI_API_AZURE_DEPLOYMENT')\n\n    if not all([api_key, api_version, api_endpoint, deployment]):\n        logger.error(\"Missing OpenAI Azure environment configuration.\")\n        raise EnvironmentError(\"Missing OpenAI Azure credentials.\")\n\n    client = AzureOpenAI(\n        api_key=api_key,\n        api_version=api_version,\n        azure_endpoint=api_endpoint\n    )\n    return client, deployment\n\n\ndef get_db_engine() -&gt; sqlalchemy.Engine:\n    \"\"\"Initialize and return a SQLAlchemy engine.\"\"\"\n    return sqlalchemy.create_engine(DB_URL)\n\n\n# ========== Database Utilities ==========\n\ndef get_table_schema(engine: sqlalchemy.Engine, table_name: str) -&gt; str:\n    \"\"\"Fetch column names and data types from the specified table.\"\"\"\n    logger.info(f\"Fetching schema for table: {table_name}\")\n    query = text(\"\"\"\n        SELECT column_name, data_type \n        FROM information_schema.columns \n        WHERE table_name = :table\n    \"\"\")\n    try:\n        with engine.connect() as connection:\n            result = connection.execute(query, {\"table\": table_name})\n            schema = \"\\n\".join(f\"{row.column_name}: {row.data_type}\" for row in result)\n            if not schema:\n                raise ValueError(f\"No schema found for table '{table_name}'\")\n            return schema\n    except SQLAlchemyError as e:\n        logger.exception(\"Error fetching schema\")\n        raise RuntimeError(f\"Schema retrieval failed: {e}\")\n\n\ndef run_sql_query(engine: sqlalchemy.Engine, sql: str) -&gt; list[dict]:\n    \"\"\"Execute a SQL query and return results.\"\"\"\n    logger.info(\"Executing SQL query...\")\n    try:\n        with engine.connect() as conn:\n            result = conn.execute(text(sql))\n            return [dict(row._mapping) for row in result]\n    except SQLAlchemyError as e:\n        logger.exception(\"SQL execution failed\")\n        raise RuntimeError(f\"Database query failed: {e}\")\n\n\n# ========== OpenAI Utilities ==========\n\ndef create_prompt(question: str, schema: str, table_name: str) -&gt; str:\n    \"\"\"Generate prompt to send to OpenAI.\"\"\"\n    return f\"\"\"\nYou are an assistant that converts natural language into SQL queries.\nTable: {table_name}\nSchema:\n{schema}\n\nQuestion: {question}\nSQL:\n\"\"\"\n\n\ndef extract_sql_from_response(response_content: str) -&gt; str:\n    \"\"\"Extract SQL query from OpenAI response by removing markdown formatting.\"\"\"\n    return re.sub(r\"```(?:sql)?\\s*|\\s*```\", \"\", response_content).strip()\n\n\ndef text_to_sql(client: AzureOpenAI, deployment: str, question: str, schema: str, table_name: str) -&gt; str:\n    \"\"\"Generate SQL from a natural language question using OpenAI.\"\"\"\n    logger.info(f\"Generating SQL using OpenAI for question: {question}\")\n    prompt = create_prompt(question, schema, table_name)\n\n    try:\n        response = client.chat.completions.create(\n            model=deployment,\n            messages=[\n                {\"role\": \"system\", \"content\": \"You are a helpful assistant that converts natural language questions into SQL queries.\"},\n                {\"role\": \"user\", \"content\": prompt}\n            ]\n        )\n        raw_sql = response.choices[0].message.content\n        sql_query = extract_sql_from_response(raw_sql)\n        logger.info(\"Generated SQL: %s\", sql_query)\n        return sql_query\n    except Exception as e:\n        logger.exception(\"OpenAI API call failed\")\n        raise RuntimeError(f\"Failed to generate SQL: {e}\")\n\n\n# ========== Main Entry Point ==========\n\ndef main():\n    try:\n        question = input(\"Enter your question: \").strip()\n        if not question:\n            raise ValueError(\"Empty question provided.\")\n\n        # Setup\n        engine = get_db_engine()\n        client, deployment = get_openai_client()\n\n        # Generate SQL\n        schema = get_table_schema(engine, TABLE_NAME)\n        sql_query = text_to_sql(client, deployment, question, schema, TABLE_NAME)\n\n        # Execute and display results\n        results = run_sql_query(engine, sql_query)\n        logger.info(f\"\\nGenerated SQL Query:\\n{sql_query}\\n\")\n        logger.info(\"Query Results:\")\n        for row in results:\n            print(row)\n\n    except Exception as e:\n        logger.error(f\"[ERROR] {e}\")\n\n\nif __name__ == \"__main__\":\n    main()\n<\/pre>\n<h4>3.2.1 Code Explanation<\/h4>\n<p>This Python script connects Azure OpenAI with a PostgreSQL database using SQLAlchemy to convert natural language questions into executable SQL queries. It starts by importing required libraries for logging, environment management, database access, and OpenAI integration. Logging is configured to output timestamped messages, and environment variables are loaded using <code>python-dotenv<\/code>. Constants like <code>TABLE_NAME<\/code> and <code>DB_URL<\/code> are defined to point to the employees table and PostgreSQL connection string respectively. The <code>get_openai_client()<\/code> function initializes an AzureOpenAI client using credentials from environment variables, while <code>get_db_engine()<\/code> sets up a SQLAlchemy engine to interact with the database. The <code>get_table_schema()<\/code> function queries the database to retrieve column names and types, which are used to construct a schema prompt. The <code>run_sql_query()<\/code> function takes a SQL query, executes it, and returns the result as a list of dictionaries. The <code>create_prompt()<\/code> function builds a prompt that includes the table schema and user question, which is sent to OpenAI via <code>text_to_sql()<\/code>, where a chat completion request is made to generate the SQL query. The <code>extract_sql_from_response()<\/code> function cleans the SQL output by removing markdown formatting. Finally, the <code>main()<\/code> function orchestrates the entire workflow: it takes user input, prepares the schema, gets the generated SQL from OpenAI, runs it against the database, and prints the result. The script is executed when run directly and is designed to handle common errors with informative logging throughout.<\/p>\n<h3>3.3 Sample Output<\/h3>\n<p>The following is an example of how the application behaves when a user inputs a natural language question. In this case, the question is <code>List all employees from Engineering<\/code>. The application fetches the schema of the target table, constructs a prompt, sends the prompt to Azure OpenAI, receives a SQL query as a response, executes the query against the PostgreSQL database, and logs the results. Each step is timestamped using the logging module for easy debugging and monitoring. The OpenAI response is successfully parsed, resulting in a valid SQL query that retrieves all employee records from the Engineering department.<\/p>\n<pre class=\"brush:plain; wrap-lines:false;\">Enter your question: List all employees from Engineering\n2025-07-04 20:57:01,226 - INFO - Fetching schema for table: employees\n2025-07-04 20:57:01,260 - INFO - Generating SQL using OpenAI for question: List all employees from Engineering\n2025-07-04 20:57:02,739 - INFO - HTTP Request: POST https:\/\/jcg.openai.azure.com\/openai\/deployments\/gpt-4o\/chat\/completions?api-version=2024-08-01-preview \"HTTP\/1.1 200 OK\"\n2025-07-04 20:57:02,746 - INFO - Generated SQL: SELECT * FROM employees WHERE department = 'Engineering';\n2025-07-04 20:57:02,746 - INFO - Executing SQL query...\n2025-07-04 20:57:02,753 - INFO - \nGenerated SQL Query:\nSELECT * FROM employees WHERE department = 'Engineering';\n\n2025-07-04 20:57:02,753 - INFO - Query Results:\n{'id': 1, 'name': 'Alice', 'department': 'Engineering', 'salary': 95000}\n{'id': 3, 'name': 'Charlie', 'department': 'Engineering', 'salary': 105000}\n<\/pre>\n<h2><a name=\"section-4\"><\/a>4. Conclusion<\/h2>\n<p>We\u2019ve built a simple but functional Text-to-SQL application using OpenAI\u2019s LLMs. With just natural language, users can query structured databases. For production scenarios, you can improve security by adding query validation, and also switch to OpenAI\u2019s <code>chat\/completions<\/code> endpoint using function calling or tools like LangChain or LlamaIndex for better control. This approach can be extended for multi-table joins, complex aggregations, and dynamic dashboarding with visualization tools like Streamlit or Dash.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Text-to-SQL is a powerful application of large language models (LLMs) like GPT that enables users to interact with a database using natural language. Let us delve into understanding how to build Text-to-SQL using LLM. 1. What is an OpenAI and LLM? OpenAI is an AI research and deployment company focused on ensuring that artificial general &hellip;<\/p>\n","protected":false},"author":26931,"featured_media":219,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1878],"tags":[2234,1352,428,936,4182,2400,1408,2763,657,224,244],"class_list":["post-135398","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-env-files-support","tag-azure","tag-database","tag-docker","tag-environment","tag-llms","tag-microsoft-azure","tag-open-ai","tag-postgresql","tag-python","tag-sql"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Build Text-to-SQL using LLM - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Build Text-to-SQL using LLM - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html\" \/>\n<meta property=\"og:site_name\" content=\"Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2025-07-21T12:41:33+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-07-21T12:42:41+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Yatin Batra\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Yatin Batra\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html\"},\"author\":{\"name\":\"Yatin Batra\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/cda31a4c1965373fed40c8907dc09b8d\"},\"headline\":\"Build Text-to-SQL using LLM\",\"datePublished\":\"2025-07-21T12:41:33+00:00\",\"dateModified\":\"2025-07-21T12:42:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html\"},\"wordCount\":833,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/python-logo.jpg\",\"keywords\":[\".env files support\",\"azure\",\"Database\",\"Docker\",\"environment\",\"LLMs\",\"MicroSoft Azure\",\"open ai\",\"PostgreSQL\",\"Python\",\"SQL\"],\"articleSection\":[\"Python\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html\",\"name\":\"Build Text-to-SQL using LLM - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/python-logo.jpg\",\"datePublished\":\"2025-07-21T12:41:33+00:00\",\"dateModified\":\"2025-07-21T12:42:41+00:00\",\"description\":\"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#primaryimage\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/python-logo.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2012\\\/10\\\/python-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/build-text-to-sql-using-llm.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Web Development\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/web-development\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python\",\"item\":\"https:\\\/\\\/www.javacodegeeks.com\\\/category\\\/web-development\\\/python\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Build Text-to-SQL using LLM\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#website\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Developers Resource Center\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.javacodegeeks.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/06\\\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/javacodegeeks\",\"https:\\\/\\\/x.com\\\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/#\\\/schema\\\/person\\\/cda31a4c1965373fed40c8907dc09b8d\",\"name\":\"Yatin Batra\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Yatin.batra_.jpg\",\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Yatin.batra_.jpg\",\"contentUrl\":\"https:\\\/\\\/www.javacodegeeks.com\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Yatin.batra_.jpg\",\"caption\":\"Yatin Batra\"},\"description\":\"An experience full-stack engineer well versed with Core Java, Spring\\\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).\",\"sameAs\":[\"https:\\\/\\\/www.javacodegeeks.com\"],\"url\":\"https:\\\/\\\/www.javacodegeeks.com\\\/author\\\/yatin-batra\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Build Text-to-SQL using LLM - Java Code Geeks","description":"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html","og_locale":"en_US","og_type":"article","og_title":"Build Text-to-SQL using LLM - Java Code Geeks","og_description":"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.","og_url":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html","og_site_name":"Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2025-07-21T12:41:33+00:00","article_modified_time":"2025-07-21T12:42:41+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg","type":"image\/jpeg"}],"author":"Yatin Batra","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Yatin Batra","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#article","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html"},"author":{"name":"Yatin Batra","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/cda31a4c1965373fed40c8907dc09b8d"},"headline":"Build Text-to-SQL using LLM","datePublished":"2025-07-21T12:41:33+00:00","dateModified":"2025-07-21T12:42:41+00:00","mainEntityOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html"},"wordCount":833,"commentCount":0,"publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg","keywords":[".env files support","azure","Database","Docker","environment","LLMs","MicroSoft Azure","open ai","PostgreSQL","Python","SQL"],"articleSection":["Python"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html","url":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html","name":"Build Text-to-SQL using LLM - Java Code Geeks","isPartOf":{"@id":"https:\/\/www.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#primaryimage"},"image":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#primaryimage"},"thumbnailUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg","datePublished":"2025-07-21T12:41:33+00:00","dateModified":"2025-07-21T12:42:41+00:00","description":"Python text to sql: Convert natural language to SQL queries using Python with OpenAI and streamline database access easily.","breadcrumb":{"@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#primaryimage","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2012\/10\/python-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/www.javacodegeeks.com\/build-text-to-sql-using-llm.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Web Development","item":"https:\/\/www.javacodegeeks.com\/category\/web-development"},{"@type":"ListItem","position":3,"name":"Python","item":"https:\/\/www.javacodegeeks.com\/category\/web-development\/python"},{"@type":"ListItem","position":4,"name":"Build Text-to-SQL using LLM"}]},{"@type":"WebSite","@id":"https:\/\/www.javacodegeeks.com\/#website","url":"https:\/\/www.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Developers Resource Center","publisher":{"@id":"https:\/\/www.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/www.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/www.javacodegeeks.com\/#\/schema\/person\/cda31a4c1965373fed40c8907dc09b8d","name":"Yatin Batra","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/12\/Yatin.batra_.jpg","url":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/12\/Yatin.batra_.jpg","contentUrl":"https:\/\/www.javacodegeeks.com\/wp-content\/uploads\/2022\/12\/Yatin.batra_.jpg","caption":"Yatin Batra"},"description":"An experience full-stack engineer well versed with Core Java, Spring\/Springboot, MVC, Security, AOP, Frontend (Angular &amp; React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).","sameAs":["https:\/\/www.javacodegeeks.com"],"url":"https:\/\/www.javacodegeeks.com\/author\/yatin-batra"}]}},"_links":{"self":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/135398","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/users\/26931"}],"replies":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=135398"}],"version-history":[{"count":0,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/135398\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media\/219"}],"wp:attachment":[{"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=135398"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=135398"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=135398"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}