> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/maiagent-user-guide/en/build/database/text2sql.md).

# Text to SQL Features

This article introduces how to use the Text to SQL feature in the MaiAgent system, helping you easily query database information using everyday conversation

## **What is Text to SQL?** <a href="#what-is-text-to-sql" id="what-is-text-to-sql"></a>

**Text to SQL** (also known as Text2SQL) is an intelligent tool that automatically converts **natural language questions** (everyday human language) into **SQL database query statements**. Simply put, it enables an Agent to "<mark style="color:blue;">understand human language</mark>" and directly operate on databases.

{% hint style="info" %}
To learn more about Text2SQL, see: [Technical Manual — Text to SQL](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql)
{% endhint %}

Imagine you are a convenience store owner:

**Traditional approach:**

* You: "Help me check how many bottles of cola were sold yesterday"
* Employee: "Boss, you need to teach me how to use the POS system to query..."
* You: "Click here, select there, enter conditions..."

Requires hands-on instruction, which is time-consuming.

**With Text2SQL:**

* You: "Help me check how many bottles of cola were sold yesterday"
* AI Employee: "Sure!" 💫 *(automatically generates the query method and calls the database)* → "87 bottles of cola were sold yesterday" ✅

### **Core Features of Text to SQL** <a href="#text-to-sql-core-features" id="text-to-sql-core-features"></a>

```
Natural language question → AI understanding & analysis → SQL query statement → Execute query → Return results
```

When you ask the Agent "Find the best-selling beverage from yesterday," the Agent first analyzes your question, understands that you want to find a "beverage" that sold the "best" "yesterday," then generates SQL syntax to query the database, and finally tells you the result: "cola."

## **What Text to SQL Can Help AI Accomplish** <a href="#what-text-to-sql-can-do" id="what-text-to-sql-can-do"></a>

### **Use Cases** <a href="#use-cases" id="use-cases"></a>

#### **🏥 Medical Clinic** <a href="#medical-clinic" id="medical-clinic"></a>

```
Doctor asks: "Find today's appointments for diabetic patients"
AI responds: "There are 5 diabetic patients with appointments today:
- Mr. Wang 10:00 follow-up visit
- Mrs. Li 14:30 follow-up checkup
- Ms. Chen 16:00 blood sugar monitoring"
```

#### **🏫 School Management** <a href="#school-management" id="school-management"></a>

```
Teacher asks: "How many students failed this exam?"
AI responds: "This math exam:
- Total students: 45
- Failed: 8 (17.8%)
- The list of students requiring a makeup exam has been compiled"
```

#### **🏪 Retail Chain Store** <a href="#retail-chain" id="retail-chain"></a>

```
Store manager asks: "Compare the monthly revenue of three branches"
AI responds: "November revenue comparison by branch:
- Taipei store: $1,200,000 (↑15%)
- Taichung store: $950,000 (↑8%)  
- Kaohsiung store: $800,000 (↓3%)"
```

### **Advantages of Text to SQL** <a href="#text-to-sql-advantages" id="text-to-sql-advantages"></a>

#### **⚡ Efficiency Improvement** <a href="#efficiency-improvement" id="efficiency-improvement"></a>

* **Traditional approach**: Requires an SQL expert to write queries → 30 minutes
* **Text2SQL**: Ask in natural language → 3 seconds

#### **🎯 Lower Barrier** <a href="#lower-barrier" id="lower-barrier"></a>

* **No need** to learn complex SQL syntax
* **No need** to memorize database structure
* **Anyone** can query data

#### **📱 Real-Time Interaction** <a href="#real-time-interaction" id="real-time-interaction"></a>

* Ask and get answers immediately
* Supports follow-up questions
* Dynamically adjust query conditions

## How to Use Text to SQL in MaiAgent <a href="#how-to-use-text-to-sql-in-maiagent" id="how-to-use-text-to-sql-in-maiagent"></a>

Databases are created in one central place under <mark style="color:blue;">AI Features</mark> → <mark style="color:blue;">Database</mark> in the left menu. One database can be used by multiple Agents, and one Agent can be linked to multiple databases. Setup takes three steps:

### 1. Create and Enable the Database <a href="#enter-database-url" id="enter-database-url"></a>

On the <mark style="color:blue;">Database</mark> page, click <mark style="color:blue;">Add Database</mark> and select the database type:

* **MaiAgent database**: Use this if you don't have your own database. Upload an Excel, CSV, or JSON file and the system automatically creates the tables. No connection string is needed. See [Using a MaiAgent Database for Text to SQL](/maiagent-user-guide/en/build/database/text-to-sql-maiagent.md).
* **External database**: Connect to an existing PostgreSQL, MySQL, SQL Server, Oracle, or SynxDB database. You need to enter a connection string and first confirm that the database allows connections from MaiAgent.

Newly created databases are disabled by default. Turn on <mark style="color:blue;">Enable Database</mark> before the Agent can query it. For the complete steps, the connection string format for each database, and the network checklist, see [Create and Configure a Database](/maiagent-user-guide/en/build/database/create-database.md).

### 2. Switch the Agent to Agent Mode <a href="#switch-to-agent-mode" id="switch-to-agent-mode"></a>

In the Agent's <mark style="color:blue;">Settings</mark>, click <mark style="color:blue;">Response Mode Settings</mark> in the left navigation and select <mark style="color:blue;">Agent Mode</mark>.

{% hint style="warning" %}
Text to SQL is only available in Agent Mode. For Agents in other response modes, <mark style="color:blue;">Database Settings</mark> in the left navigation is locked and no database can be selected. For details about each response mode, see [Create an Agent](/maiagent-user-guide/en/build/agent/setup.md#select-answer-mode-to-build-prompt).
{% endhint %}

### 3. Link the Database to the Agent <a href="#link-database-to-agent" id="link-database-to-agent"></a>

Choose either of the following methods:

* In the Agent's <mark style="color:blue;">Settings</mark>, click <mark style="color:blue;">Database Settings</mark> in the left navigation, click <mark style="color:blue;">Select Database</mark>, check the databases to query, and then click Save.
* On the database settings page, open the <mark style="color:blue;">Linked AI Assistants</mark> tab, move the Agent to the right side, and save. See [Link Agents and Group Permissions](/maiagent-user-guide/en/build/database/link-chatbots-groups.md).

Once setup is complete, you can query data with natural language in the Agent's conversation, for example, "Which product sold the most last month?"

## **Troubleshooting** <a href="#troubleshooting" id="troubleshooting"></a>

* **Connection failed**: Check the connection string format, username and password, and whether the firewall and allowlist are open. See [Create and Configure a Database: Network Prerequisites](/maiagent-user-guide/en/build/database/create-database.md#network-prerequisites).
* **The Agent does not query the database**: Confirm that the response mode is Agent Mode, the database is enabled, and it is linked to this Agent.
* **The Agent only queries the database and replies that it has no knowledge base retrieval tool**: In Agent Mode, knowledge base retrieval is also a set of tools (`retrieve_text_nodes`, etc.). When <mark style="color:blue;">Enable Tool Search</mark> is on, these tools must be found by search before they can be called, just like Text to SQL, and the model occasionally skips the search and answers that it has "no tools." Write "Query the knowledge base with retrieve\_text\_nodes before answering" in the role instructions, or turn off tool search so that all tools are directly available. See [Configure Tools for an Agent](/maiagent-user-guide/en/build/tools/configure_tools.md). For the differences in retrieval between the two modes, see [Technical Manual - How Chat Mode and Agent Mode Query the Knowledge Base](https://docs.maiagent.ai/tech/quickstart/rag#chat-vs-agent-retrieval).
* **You want to restrict certain users to part of the data**: [Query metadata](/maiagent-user-guide/en/org/querymetadata.md#scope-and-limits) only restricts knowledge base retrieval and does not apply to Text to SQL. The scope of a database can only be controlled by enabling it/linking Agents, <mark style="color:blue;">Specify Tables</mark>, and role permissions; it cannot be restricted per request. If you need to separate access by user, create different Agents and database connections (or read-only accounts) for different identities.
* **Query error**: Verify that table names and column names are correct, and add descriptions to tables and columns. See [Edit Column Descriptions](/maiagent-user-guide/en/build/database/create-database.md#edit-column-description).
* **Insufficient permissions**: Check whether the database account has read permission on these tables.
* **Slow response**: Check query complexity, consider adding indexes, or narrow the query scope with <mark style="color:blue;">Specify Tables</mark>.

For specifications (read-only protection, network requirements, handling of large schemas, and query result limits), see [Technical Manual - Text to SQL](https://docs.maiagent.ai/tech/advanced-genai-tech/text-to-sql).

***

Text2SQL turns the Agent into a database expert, allowing anyone to quickly obtain business insights using natural language, greatly improving the efficiency of data-driven decision making!


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/maiagent-user-guide/en/build/database/text2sql.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
