# AI Text-to-SQL Data Analyst | 30 Days of Building AI Systems, Day 15

> Build an AI text-to-SQL data analyst: schema grounding, SQL generation, validation and read-only guards, safe execution, charts, and plain-language answers.

Source: https://codeitronics.com/blogs/ai-systems-day-15-ai-text-to-sql-data-analyst (published 2026-12-03)

Yesterday we built an AI BI system that turns governed metrics into reports and alerts. Today we handle the questions nobody predefined. The AI Text-to-SQL Data Analyst takes a question in plain English, understands your schema, generates SQL, runs it safely against your databases, and returns a chart plus a short explanation. Day 8 was a general analysis copilot for a dataset you load. This one is specifically about turning natural language into safe, correct SQL over a real warehouse.

![AI Text-to-SQL Data Analyst — CodeITronics infographic](https://pub-206c6a53642c4bdb86310f0393204592.r2.dev/blogs/series/30-days-of-building-ai-systems/60-ai-systems-day-15-ai-text-to-sql-data-analyst.png) *Save this sheet. The rest of this note walks through it section by section.*

## Table of Contents

* [What We Are Building](#what-we-are-building)
* [System Architecture](#system-architecture)
* [Key Components](#key-components)
* [Schema Grounding](#schema-grounding)
* [Validating and Guarding the SQL](#validating-and-guarding-the-sql)
* [A Minimal Tech Stack](#a-minimal-tech-stack)
* [Example Interaction](#example-interaction)
* [Production Concerns](#production-concerns)
* [Key Takeaways](#key-takeaways)
* [FAQs](#faqs)
* [Up Next](#up-next)

## What We Are Building

An AI Data Analyst that:

* Understands natural language questions
* Connects to multiple data sources (PostgreSQL, MySQL, Snowflake, BigQuery, Redshift, CSV and Excel, APIs)
* Analyzes data automatically and generates visualizations
* Finds trends, patterns, and anomalies
* Answers follow-up questions
* Creates reports and dashboards that can be exported or shared

Use cases: sales and revenue analysis, marketing campaigns, customer behavior, financial performance, operations, product usage, risk and fraud, and executive reporting. The real value is self-service: people get answers without waiting in the data team's queue.

## System Architecture

```
User Question -> Data Connection Layer -> Data Understanding and Context
   -> AI Analysis Engine (generate SQL) -> Visualization Engine
   -> Insights and Answers -> Export and Share
```

The detailed flow on the sheet expands the middle: intent detection, schema and data understanding, query generation, query execution, results, AI analysis and insights, visualization, a natural language summary, and follow-up questions that loop back to the start.

Two stages carry most of the risk: **query generation** (is the SQL correct?) and **query execution** (is it safe to run?). Most of this post is about those two.

## Key Components

| Component                  | Purpose                                                          |
| -------------------------- | ---------------------------------------------------------------- |
| LLM                        | Generates SQL and writes the summary                             |
| SQL generator and executor | Builds, validates, and runs queries                              |
| Data connectors and APIs   | One interface across database engines                            |
| Metadata store             | Schema, column descriptions, metric definitions, example queries |
| Visualization              | Plotly, ECharts, or Recharts                                     |
| Cache                      | Redis for repeated questions and results                         |
| Auth and permissions       | Who can query which tables and rows                              |
| Logging and monitoring     | Every question, query, and result recorded                       |

## Schema Grounding

The model cannot write correct SQL for a schema it does not understand. Dumping every table into the prompt does not work either; large schemas overwhelm it and cost a lot.

What works:

1. **Curate.** Expose a set of analytics views, not your raw production tables. Name columns clearly.
2. **Describe.** Store a one-line description per table and column in the metadata store, including units, enums, and gotchas ("amount is in cents", "status 3 means refunded").
3. **Retrieve.** For each question, retrieve only the relevant tables and descriptions.
4. **Show examples.** Include a few verified question and SQL pairs from your own data. These help more than any amount of instruction text.
5. **Reuse metrics.** If yesterday's semantic layer exists, let the model use defined metrics like `net_revenue` instead of re-deriving them.

## Validating and Guarding the SQL

Never execute generated SQL directly. Parse it, check it, then run it with database-level limits. A small guard using sqlglot:

```python
import sqlglot
from sqlglot import exp

ALLOWED_TABLES = {"orders", "order_items", "products", "customers"}

def guard(sql: str, max_rows: int = 1000) -> str:
    statements = sqlglot.parse(sql, read="postgres")
    if len(statements) != 1 or not isinstance(statements[0], exp.Select):
        raise ValueError("Only a single SELECT statement is allowed")
    stmt = statements[0]
    cte_names = {cte.alias_or_name for cte in stmt.find_all(exp.CTE)}
    tables = {t.name for t in stmt.find_all(exp.Table)} - cte_names
    if not tables <= ALLOWED_TABLES:
        raise ValueError(f"Tables not allowed: {tables - ALLOWED_TABLES}")
    if not stmt.args.get("limit"):
        stmt = stmt.limit(max_rows)
    return stmt.sql(dialect="postgres")
```

The parser check is a convenience layer, not your security boundary. The real boundary is the database:

```sql
CREATE ROLE ai_analyst LOGIN;
GRANT USAGE ON SCHEMA analytics TO ai_analyst;
GRANT SELECT ON ALL TABLES IN SCHEMA analytics TO ai_analyst;
ALTER ROLE ai_analyst SET default_transaction_read_only = on;
ALTER ROLE ai_analyst SET statement_timeout = '15s';
```

Run against a read replica or the warehouse, never the primary that serves your app. If users have row-level permissions, enforce them with row-level security or per-user views, not with prompt instructions.

For sensitive or expensive queries, add a review step: show the SQL and an estimated cost (from `EXPLAIN` or the warehouse's dry-run feature), and run only after the user confirms.

## A Minimal Tech Stack

| Layer          | Minimal choice                                                                  |
| -------------- | ------------------------------------------------------------------------------- |
| Frontend       | Next.js with a chat panel and chart area                                        |
| Backend        | Python (FastAPI)                                                                |
| LLM            | One strong model for SQL generation                                             |
| SQL layer      | SQLAlchemy for connections, sqlglot for parsing, DuckDB for CSV and Excel files |
| Visualization  | Plotly or Recharts                                                              |
| Cache and jobs | Redis and Celery for long-running queries                                       |
| Auth           | JWT or OAuth, mapped to database permissions                                    |

DuckDB is a quiet hero here. Uploaded CSV and Excel files can be queried with the same SQL path as your warehouse.

## Example Interaction

The sheet's example: "What were our top 5 products by revenue last quarter?"

Behind the scenes, the system detects an aggregation intent with a time filter, retrieves the `orders`, `order_items`, and `products` tables, and generates a query that sums revenue by product for the previous calendar quarter, ordered descending, limited to five rows. The guard approves it, the read-only role runs it, and the result goes to the visualization step.

The user sees a bar chart of the top five products and an AI summary noting which product led, the combined total for the top five, and which product grew fastest versus the previous quarter. The user can then ask a follow-up ("break Product A down by channel") and the conversation keeps context.

Two details make this trustworthy. First, show the SQL behind every answer in an expandable panel. Second, spell out interpretations: "last quarter" means the previous calendar quarter unless your company uses fiscal quarters. State the assumption in the answer.

## Production Concerns

**Evaluation.** Build a test set of real questions with verified SQL or verified results. Compare result sets, not SQL text, since many different queries are correct. Track execution success rate and result accuracy, and re-run on every prompt or model change.

**Silent wrong answers.** The dangerous failure is not an error; it is valid SQL that answers a slightly different question. Join fan-out that double counts revenue is the classic one. Clear views, examples, and visible SQL catch most of it.

**Cost.** Warehouse queries can cost more than the LLM call. Use dry runs or `EXPLAIN` to block unbounded scans, and cache results for repeated questions.

**Ambiguity.** When a question is ambiguous ("active users"), ask a clarifying question or state the definition used.

**Audit.** Log who asked what, the SQL generated, and the rows returned. Analysts will want this, and so will your security team.

## Key Takeaways

* Text-to-SQL quality depends mostly on schema curation, descriptions, and examples.
* Parse and validate every query, but treat the read-only database role as the real security boundary.
* Show the SQL and state assumptions so users can check answers.
* Evaluate on result accuracy against a test set of real questions.

## FAQs

### Can the LLM ever write or modify data?

Not in this system. It is an analyst, not an operator. Write operations belong in a separate workflow with explicit approvals.

### Does fine-tuning help text-to-SQL?

Sometimes, but start with retrieval of schema descriptions and verified examples. That usually gets you further for less effort and adapts immediately when the schema changes.

### What about very large schemas?

Retrieve relevant tables per question, expose curated views, and group tables by domain. The model should see a few tables, not hundreds.

## Up Next

Day 16 builds the AI Recommendation System: candidate generation, ranking, feedback loops, and the metrics that tell you whether recommendations help. We will also be clear about where LLMs help and where classic recommendation models do the heavy lifting. If you want safe text-to-SQL on your own warehouse, [talk to us](/contact).
