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:
- Schema injection — inject DB structure into the prompt
- LLM generates SQL — model produces a query
- Execute — run query against the database
- Format results — turn rows into readable text
- 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