0Pricing
AI Agents · Lesson

How NL-to-SQL Agents Work

Schema injection, query generation, execution, and result formatting.

What Is a NL-to-SQL Agent?

A Natural Language to SQL agent translates plain English questions into SQL queries, executes them against a database, and returns human-readable answers.

Instead of writing SELECT COUNT(*) FROM orders WHERE status='pending', users simply ask: "How many pending orders do we have?"

The Core Architecture

Every NL-to-SQL agent follows the same pipeline:

  1. Schema injection — inject DB structure into the prompt
  2. LLM generates SQL — model produces a query
  3. Execute — run query against the database
  4. Format results — turn rows into readable text
  5. Return answer — respond to the user
# High-level pipeline
def nl_to_sql_agent(user_question, db_connection):
    schema = get_schema(db_connection)
    sql = llm_generate_sql(user_question, schema)
    rows = execute_query(db_connection, sql)
    answer = format_results(rows, user_question)
    return answer

All lessons in this course

  1. How NL-to-SQL Agents Work
  2. Schema Understanding and Injection
  3. Generating and Validating SQL Queries
  4. Handling Ambiguous Database Questions
← Back to AI Agents