SQL for Data and AI Applications Handbook · PRACTICAL GUIDE

Text-to-SQL and Safe AI Agents

Design a governed natural-language-to-SQL workflow with clarification, validation, least privilege, execution limits and audit evidence.

HANDBOOK JOURNEYByte 5 of 5View all Bytes
HANDBOOK JOURNEYByte 5 of 5

SQL for Data and AI Applications Handbook

25 min focused reading
  1. BYTE 01SQL Fundamentals for AI Applications
  2. BYTE 02Aggregations and Window Functions
  3. BYTE 03Vector Search in SQL with pgvector
  4. BYTE 04Feature Engineering for Machine Learning with SQL
FAMILIAR SCENARIO

A busy railway counter needs safe, fast transactions

The correct passenger record must be found quickly, values must be handled safely and a failed payment must not leave half a booking.

01Parameterise
02Index
03Transact
04Audit

Connect the idea: Production SQL combines correctness, security, speed and recoverability.

TEXT-TO-SQL · BYTE 05

What you will build

You will trace a natural-language question through clarification, generation, structural validation and read-only execution—then see unsafe SQL stopped before it reaches the database.

“Show our best customers” is not ready for SQL

Does best mean revenue, margin, number of orders or on-time payment? Generating SQL before resolving that ambiguity can produce a valid query that answers the wrong question.

GOVERNED SQL AGENTGeneration is only one step; validation and database permissions enforce safety.
01Question→02Clarify→03Validate→04Read only
Generation is only one step; validation and database permissions enforce safety.

The safe workflow has gates

  1. Understand the question and authorised user context.
  2. Clarify ambiguous metrics and time ranges.
  3. Retrieve approved schema and business definitions.
  4. Generate a bounded query.
  5. Parse and validate structure, tables, columns and operations.
  6. Execute with a read-only role, timeout, cost and row limits.
  7. Explain the result with query and source context.
  8. Log the request, decision, SQL and execution metadata.

The agent must pass these gates in order. It should clarify before generation, validate before execution and stop before any action outside its permission.

BYTE 05 · SAFE TEXT-TO-SQLWatch the agent decide before execution
Question→Definitions→Generate→Validate→CLARIFY
INTERACTIVE SQL QUERY LABWrite → Run → Inspect → Learn
Edit the SQL, then select Run query to generate the result.
Guided browser simulation · no database is changed

A governed query template

User question: “Which five customers generated the highest paid revenue in September 2026?”

SQL
01SELECT c.customer_id,02       c.name,03       SUM(o.total_amount) AS paid_revenue04FROM analytics.customers AS c05JOIN analytics.orders AS o06  ON o.customer_id = c.customer_id07WHERE o.status = 'PAID'08  AND o.ordered_at >= DATE '2026-09-01'09  AND o.ordered_at < DATE '2026-10-01'10GROUP BY c.customer_id, c.name11ORDER BY paid_revenue DESC, c.customer_id12LIMIT 5;

The request defines the metric, state, time range and result size. A business definition layer can supply those meanings, but a SQL view alone is only one implementation building block—not a complete semantic governance system.

Example result returned to the agent

customer_idnamepaid_revenue
C101Meena₹48,900
C208Farah₹41,250
C145Arun₹38,600

The agent should explain that this ranking uses paid revenue during September 2026, rather than presenting “best customer” as an undefined fact.

Permissions enforce what prompts cannot

SQL
01CREATE ROLE reporting_agent NOLOGIN;02GRANT USAGE ON SCHEMA analytics TO reporting_agent;03GRANT SELECT ON ALL TABLES IN SCHEMA analytics TO reporting_agent;04ALTER DEFAULT PRIVILEGES IN SCHEMA analytics05GRANT SELECT ON TABLES TO reporting_agent;

Production configuration needs an appropriate login/session role and must follow the organisation’s database policy. Crucially, a prompt saying “do not delete” is not access control. Database privilege should make prohibited actions impossible.

SEE IT IN PRACTICE

Real-world application: finance question

An executive asks an agent for overdue invoice totals. The agent may prepare and execute an approved read-only query. Changing an invoice, issuing a refund or sending a collection notice crosses into consequential action and requires a separate workflow with explicit approval.

Validate before execution

String matching alone is fragile. Parse the SQL and apply an allowlist:

  • Permit only approved statement types, schemas, tables, columns and functions.
  • Reject multiple statements, comments used for evasion and unbounded operations.
  • Apply statement timeout, maximum rows and resource controls.
  • Consider EXPLAIN or a database-specific dry run before costly queries.
  • Keep an audit trail and redact sensitive values from logs.

Common text-to-SQL mistakes

AVOID THESE

Common mistakes

  • Treating a syntactically valid query as a semantically correct answer.
  • Allowing direct access to every production table.
  • Depending on the model prompt instead of database permissions.
  • Executing before clarifying vague metrics or dates.
  • Returning a number without showing the definition, query context or freshness.

Practice the safety decision

For the request “Remove customers who have not purchased this year,” list the clarifications required, explain why read-only execution must block it and design a human-approved operational workflow instead.

LESSON CHECKPOINTConfirm the concept before moving forward

Choose an answer, inspect the explanation and explain the idea in your own words.

RETENTION

What is the strongest control against a generated DELETE statement?

Learning rule: explain the answer in your own words before checking the next Byte.

Interview-ready explanation

CLEAR ANSWER

Why is prompt-only SQL safety insufficient?

Model instructions are probabilistic and can be misunderstood or bypassed. Safety needs independent enforcement: parsed-query allowlists, least-privilege database roles, execution limits, approval boundaries and audit logs.

Questions beginners usually ask

Should every generated query require approval? Not necessarily. Low-risk, read-only queries can run inside strict controls; high-cost, sensitive or consequential requests should stop or require review.

What should the answer show? Include the interpreted metric, time range, data freshness and enough query or source context for a person to verify the result.

What to remember

REMEMBER THIS

Key takeaways

  • Text-to-SQL begins with business meaning, not generation.
  • Validation should understand SQL structure and enforce explicit allowlists.
  • Read-only privilege, timeouts and row limits provide independent protection.
  • High-impact actions belong behind a separate human approval boundary.
  • Audit evidence makes results explainable and incidents diagnosable.

Project complete: your Business Data Analyst can retrieve exact facts, analyse trends, search meaning, build time-safe ML features and answer natural-language questions within governed database boundaries.

Primary references

OPTIONAL LEARNING CONNECTIONS

Continue by concept

Choose only what supports your next goal. This Byte does not require either link.