Analytics Agents and Text-to-SQL: How AI Agents Query Your Data

By Rahul Singh

Updated on Dec 2, 2026

Share:

Quick Overview:

  • Text-to-SQL is an AI technique that converts natural language questions into SQL queries, allowing users to access databases without writing SQL manually.

  • Analytics agents extend Text-to-SQL by planning tasks, executing queries, correcting errors, analysing results, and explaining findings.

  • Text-to-SQL architecture includes context retrieval, schema linking, SQL generation, validation, query execution, and response generation.

  • Common Text-to-SQL approaches include rule based methods, fine tuned models, LLM prompting, self-correction, and agentic systems.

  • In this blog you will explore Text-to-SQL architecture, generation methods, analytics agent workflows, security guardrails, and a practical Python example.

Text-to-SQL and analytics agents are practical applications of data science and agentic AI. IIT Kharagpur's Applied Data Science & Agentic AI Course - Executive Post Graduate Certificate helps you develop practical skills in data analysis, machine learning, and building AI agents for real business problems.

What Is Text-to-SQL?

Text to SQL is a technique that converts a question written in everyday language into a SQL query. Instead of writing SELECT region, SUM(revenue) FROM sales GROUP BY region, you simply ask, "What was our revenue by region?" A text-to-SQL system reads the question, looks at the database structure and produces the query for you.

Why does it matter? In most companies, only a few people can query the database, so business teams wait days for a number that takes seconds to compute. Text-to-SQL AI closes that gap.

The idea is not new. Early systems in the 1970s and 1980s used hand-written grammar rules and worked only on narrow databases. The field changed with large public benchmarks. 

Spider, released by Yale researchers in 2018, tested models on unseen databases across many domains. BIRD, introduced in 2023, added messier, larger and more realistic databases. Both showed how hard the job really is, because real schemas are confusing and real questions are vague.

How Text-to-SQL Works in Simple Terms

Think of the system as a very fast junior analyst. It checks which tables matter, writes a query and hands back the result. A text-to-SQL LLM does the writing part, having seen millions of SQL examples during training.

Here is a quick example.


Text-to-SQL workflow infographic showing how an LLM converts natural language questions into SQL queries, identifies relevant database tables, executes queries and returns results.
  • Question: Which five customers spent the most in 2025?

  • Generated SQL: SELECT customer_name, SUM(amount) AS total_spent FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31' GROUP BY customer_name ORDER BY total_spent DESC LIMIT 5;

That looks easy. The hard part is everything the model cannot see by default, such as what "spent" means in your business, which table holds refunds and which date column to trust.

Why Text-to-SQL Is Hard

Three problems show up again and again. 

  • First, ambiguity: "recent sales" could mean last week or last quarter. 

  • Second, schema complexity: real warehouses have hundreds of tables with cryptic names like tbl_cust_v2. 

  • Third, business logic: a metric such as "active user" is a company decision, not something a model can guess. 

Most of the engineering effort in text-to-SQL models and systems goes into solving these three issues.

What Are Analytics Agents in AI?

An analytics agent is an AI system that answers data questions by working through a task step by step. It does not stop after writing one query. It decides what to look at, runs queries, reads the results, notices problems and keeps going until it can give a useful answer.

The word "agent" matters here. A basic text-to-SQL tool is a one-shot translator: question in, query out. 

A text-to-SQL agent behaves more like a careful analyst. If a query throws an error, it reads the message and fixes the query. If the result looks odd, such as zero rows, it checks its filters. If the question is broad, it splits the work into several queries and combines the answers.

Text-to-SQL vs Analytics Agents

Aspect

Basic Text-to-SQL

Analytics Agent

Workflow

Single step, question to query

Multi-step loop with planning and checks

Error handling

Returns the error to the user

Reads errors and retries on its own

Output

SQL query or raw result

Explained answer, often with charts

Architecture of a Text-to-SQL System

Advanced analytics systems follow an agentic AI architecture that combines reasoning, memory, tool calling, and feedback mechanisms.

Here is the typical flow.

  1. Question intake: The user types a question, sometimes with conversation history so follow-ups like "now break that down by month" make sense.

  2. Context retrieval: The system gathers the schema, column descriptions, sample values and any business definitions that relate to the question.

  3. SQL generation: The language model writes the query using that context.

  4. Validation: The query is checked for safety and correctness before it touches the data.

  5. Execution: The database runs the query and returns rows.

  6. Response: The result is formatted as a table, chart or plain-language summary.

Schema Linking and Context

Schema linking means matching the words in a question to the right tables and columns. It is the most important step, and it is where many failures start. If a user asks about "sales", is that the orders table, the invoices table or a pre-built sales_summary view?

Practical systems improve linking in a few ways. They add short descriptions to tables and columns. They include a few sample rows or distinct values, so the model knows that the status column holds values like shipped and cancelled. For large databases, teams can store schema embeddings in vector databases to retrieve relevant tables before generating SQL queries. Many teams also add a semantic layer, a defined set of metrics and dimensions, so "revenue" always means the same thing.

Validation and Guardrails

Never let a model write to a production database unchecked. Good LLM guardrails include:

  • Connecting with a read-only database user, so even a bad query cannot change data.

  • Allowing only SELECT statements and blocking anything that modifies or drops data.

  • Setting row limits and query timeouts to protect performance and cost.

  • Restricting which tables and columns each user is allowed to see.

  • Logging every question and query for audits.

Prompt injection, where hidden instructions try to trick the model, is a known risk. Database-level permissions are your strongest defence, since they work even when the model is fooled.

Different Approaches to Text-to-SQL Generation

The field has moved through several generations of text-to-SQL models. Each approach still has uses today.

Approach

Main Strength

Main Weakness

Rule-based templates

Predictable and cheap

Breaks on new phrasing

Fine-tuned models

Strong on trained domains

Needs labelled data per domain

Prompted LLMs

Fast to set up

Sensitive to prompt and schema quality

Agentic systems

Handles complex, unfamiliar data

Higher cost and latency

1. Rule-Based and Template Methods

The oldest approach maps question patterns to query templates. These systems are predictable and cheap, but they break when a user phrases something differently. They still suit narrow, repetitive reports.

2. Fine-Tuned Neural Models

From around 2017, researchers trained sequence-to-sequence models, including fine-tuned versions of T5 and BERT-based encoders, on datasets like Spider.

These text-to-SQL models learned the mapping from examples. They performed well on benchmarks but needed labelled question-and-SQL pairs for each new domain, and they struggled with unfamiliar schemas.

3. Prompting General-Purpose LLMs

The next leap came with large language models. Instead of training a special model, you give a general LLM the schema and a question, sometimes with a few example pairs, and ask for SQL. This is the quickest way to start. Quality depends heavily on the prompt, the schema description and the model's strength.

4. Decomposition and Self-Correction

Researchers found that splitting the task helps. The DIN-SQL paper from 2023 broke generation into stages, including schema linking, query classification, SQL generation and a self-correction pass, and reported a clear jump in accuracy over simple prompting. 

Later systems added candidate generation, where the model writes several queries and a selector picks the best based on execution results.

5. Agentic Approaches

Agentic systems go one step further. The model gets tools, such as a function to list tables, one to preview columns and one to run queries. It explores the database the way a person would, then writes and tests its SQL. This text-to-SQL agent style handles large, unfamiliar databases better, though it costs more per question because it makes several model calls.

How Analytics Agents Query and Analyse Your Data?

Let us follow an agent through a real question: "Why did revenue drop last month?"

A single query cannot answer that. A good analytics agent works in stages.

  1. Understand the goal: It recognises that this is a diagnostic question, not a lookup. It needs to compare periods and break the change into parts.

  2. Plan the steps: Analytics agents can work as planning agents, breaking complex business questions into smaller data queries. 

  3. Explore the schema: It lists the available tables, finds the sales data and checks the column types.

  4. Write and run queries: It runs the first comparison query, then follow-up queries for each breakdown.

  5. Check the results: If a query returns nothing or an error, it investigates and corrects itself.

  6. Analyse and explain: It spots that most of the drop came from one region and one product line, then writes a short summary, perhaps with a chart.

Tools an Analytics Agent Uses

Most agents combine a handful of tools.

  • SQL execution tool: Runs read-only queries and returns rows.

  • Schema explorer: Lists tables, columns and sample values.

  • Python or code tool: Handles statistics, forecasting and charts that SQL does poorly.

  • Retrieval tool: Pulls in documentation, metric definitions or past queries.

  • Memory: Keeps earlier questions in view so follow-ups work.

Agentic AI Frameworks such as LangChain, LlamaIndex and LangGraph include ready-made SQL toolkits, and many data platforms now ship their own natural language query features. 

You can also connect agents to tools through the Model Context Protocol (MCP), which standardises how models talk to databases and other systems.

Building a Text-to-SQL Analytics Agent in Python

Let us build a small version. It connects to a SQLite database, reads the schema, asks an LLM for a query, checks the query for safety, runs it, retries on errors and then explains the result. SQLite keeps the setup simple, but the same logic applies to PostgreSQL, MySQL or a cloud warehouse.

You will need Python 3.10 or later, a SQLite database file and access to an LLM through any provider's API. The code below uses a placeholder function, ask_llm, so you can plug in whichever provider you use.

Step 1: Connect and Read the Schema

Open the database in read-only mode and pull the table definitions. These go into the prompt as context.

import re

import sqlite3

DB_PATH = "sales.db"

MAX_RETRIES = 2

def ask_llm(prompt: str) -> str:

    """Send the prompt to your LLM provider and return the text reply."""

    raise NotImplementedError("Plug in your LLM client here")

def connect():

    # mode=ro opens the file read-only, so writes are impossible

    return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)

def get_schema(conn) -> str:

    rows = conn.execute(

        "SELECT sql FROM sqlite_master WHERE type='table' AND sql IS NOT NULL"

    ).fetchall()

    return "\n\n".join(row[0] for row in rows)

Step 2: Build the Prompt

A clear prompt does a lot of work. Tell the model its role, the SQL dialect and the rules. If a previous attempt failed, include the failed query and the error so the model can fix it.

def build_prompt(question, schema, previous_sql=None, error=None):

    prompt = (

        "You are a careful data analyst. Write one SQLite SELECT query.\n"

        "Use only tables and columns from the schema. Return only the SQL.\n\n"

        f"Schema:\n{schema}\n\n"

        f"Question: {question}\n"

    )

    if error:

        prompt += (

            f"\nYour previous query failed.\nQuery: {previous_sql}\n"

            f"Error: {error}\nWrite a corrected query.\n"

        )

    return prompt

Step 3: Clean and Validate the SQL

Models often wrap code in markdown fences. Strip those, then check that the query is read-only. This is a second line of defence on top of the read-only connection.

BLOCKED = ["insert", "update", "delete", "drop", "alter", "create", "attach", "pragma"]

def clean_sql(text: str) -> str:

    text = re.sub(r"```(?:sql)?", "", text).strip()

    return text.rstrip(";")

def is_safe(sql: str) -> bool:

    lowered = sql.lower()

    if not lowered.startswith(("select", "with")):

        return False

    return not any(re.search(rf"\b{word}\b", lowered) for word in BLOCKED)

Step 4: Run the Agent Loop

This is the heart of the agent. It generates a query, validates it, executes it and feeds any error back to the model.

def run_agent(question: str) -> dict:

    conn = connect()

    schema = get_schema(conn)

    sql, error = None, None

    for in range(MAXRETRIES + 1):

        sql = clean_sql(ask_llm(build_prompt(question, schema, sql, error)))

        if not is_safe(sql):

            error = "Only read-only SELECT queries are allowed."

            continue

        try:

            cursor = conn.execute(sql)

            columns = [col[0] for col in cursor.description]

            rows = cursor.fetchmany(100)  # cap the result size

            return {"sql": sql, "columns": columns, "rows": rows}

        except sqlite3.Error as exc:

            error = str(exc)

    return {"sql": sql, "error": error}

Step 5: Explain the Result

Raw rows are not an answer. A final model call turns the result into plain language.

def answer(question: str) -> str:

    result = run_agent(question)

    if "error" in result:

        return f"Sorry, I could not answer that. Last error: {result['error']}"

    summary_prompt = (

        f"Question: {question}\n"

        f"SQL used: {result['sql']}\n"

        f"Columns: {result['columns']}\n"

        f"Rows: {result['rows']}\n"

        "Answer the question in two plain sentences using only these rows."

    )

    return ask_llm(summary_prompt)

print(answer("Which five customers spent the most in 2025?"))

Final sample output:

The five highest-spending customers in 2025 were Amit Sharma, Priya Singh, Rohit Verma, Neha Gupta and Vikram Patel.

Amit Sharma spent the most at 125,000, followed by Priya Singh at 112,500.

Ways to Improve the Agent

This version is a starting point. To make it production-ready, consider these upgrades.

  • Add column descriptions and sample values to the schema context.

  • Store a list of approved example questions and queries, and include the closest ones in the prompt.

  • Use embeddings to pick relevant tables when your schema is large.

  • Log every question, query and result for debugging and audits.

  • Build a small test set of questions with known answers and run it after every change.

Conclusion

The real value of Text-to-SQL lies beyond converting questions into queries. Reliable analytics agents depend on accurate schema context, clear business metrics, query validation, and self-correction mechanisms to deliver trustworthy results.

Start by building a simple analytics agent using a familiar dataset. Test its accuracy, identify limitations, and maintain human oversight when using AI for critical business decisions.


Rahul Singh

Rahul Singh

49+ of articles published


Current role in the industry :

Associate - Content Marketing

Education Qualification :

B.Tech in Computer Science & Engineering

Expertise :

Artificial intelligenceMachine Learning (ML)Data ScienceFull-Stack DevelopmentData Structures & Algorithms

Tools & Technologies :

PythonReact.js & Next.jsJavaScript (ES6+)SQLTailwind CSSNode.js & MongoDBGit & GitHubSEO Tools (SEMRush)Google Search ConsoleTableau / Power BIFigma

About

Rahul Singh is an Associate Content Writer, with a strong interest in Generative AI, Agentic AI and AI-Native Software Engineering. He combines technical development skills with data-driven strategies to build scalable applications and optimize digital content. Rahul specializes in simplifying complex concepts across AI, ML and software development into practical, easy-to-understand insights, helping learners understand how AI products, systems and services are built and applied. He focuses on real world applications and explains advanced topics in a clear, step by step manner so you can follow along without confusion. His work connects theory with hands-on examples, covering AI-assisted development, intelligent automation and AI integration in software applications. He aims to help you learn faster, create better projects, and apply your knowledge confidently in real scenarios.

Follow me on :

Frequently Asked Questions

FAQ

Ready to Take the Next Step? Enroll Today!