# Text-to-SQL

> Turning a question in plain words into SQL. Then a database can run it.

**Field:** Artificial Intelligence  
**Category:** NLP & Language  
**Also known as:** Natural Language to SQL, NL2SQL, Text to SQL

## Think of it like

It is like asking a clerk how many red shirts you sold. He goes and checks the books.

## Definition

Text-to-SQL turns a question in plain words into a database query in SQL. The model sees the question and the layout of the tables, like their names and columns. It writes the SQL, and the database runs it to get the answer. This lets people ask data questions without knowing SQL. A query can run with no errors and still answer the wrong question, so results need checking.

## Example

Emma asks how many orders came from Germany last month. The model writes the query. The database runs it and says 418.

## Example code

```sql
-- How many orders came from Germany last month?
SELECT COUNT(*) FROM orders
WHERE country = 'Germany'
  AND order_date >= '2026-10-01'
  AND order_date < '2026-11-01';
```

The question, as a comment, and the query the model wrote for it.

## Why it matters

Most people with data questions cannot write SQL. Text-to-SQL lets them ask in their own words.

## Common mistake

Trusting a query because it ran. Check that it uses the right tables and dates before you use the number.

## Three principles

- **Words to a query.** A question becomes SQL.
- **Needs the tables.** The model must see the layout.
- **Check the logic.** Running is not the same as right.

## Related terms

- [Structured Query Language (SQL)](https://learn.benibix.com/term/development/sql)
- [Database](https://learn.benibix.com/term/development/database)
- [Natural Language Understanding (NLU)](https://learn.benibix.com/term/ai/natural-language-understanding)
- [Structured Output (LLM)](https://learn.benibix.com/term/ai/structured-output)
- [AI Data Analyst](https://learn.benibix.com/term/ai/ai-data-analyst)

![A question in plain words goes to a model, which also sees the table layout. The model writes an SQL query, the database runs it, and a single number, 418, comes back.](https://learn.benibix.com/diagrams/ai5-text-to-sql.svg)

---

Source: https://learn.benibix.com/term/ai/text-to-sql
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-18
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
