# Text to SQL Feature

## **What is Text to SQL?**

**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 AI assistants to "<mark style="color:blue;">understand human language</mark>" and directly operate databases.

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

Imagine you're 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 teaching, which is time-consuming.

**With Text2SQL:**

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

### **Core Functions of Text to SQL**

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

When you ask the AI assistant "Find yesterday's best-selling beverage," the AI assistant first analyzes your question, understands you're looking for a "beverage" that was the "best-selling" "yesterday," then generates SQL syntax to query the database, and finally tells you the result: "Coca-Cola."

## **What Text to SQL Can Help AI Accomplish**

### **Specific Application Scenarios**

#### **🏥 Medical Clinic**

```
Doctor asks: "Find today's diabetes patient appointments"
AI responds: "There are 5 diabetes patients scheduled today:
- Mr. Wang 10:00 Follow-up visit
- Mrs. Lee 14:30 Follow-up examination
- Miss Chen 16:00 Blood glucose monitoring"
```

#### **🏫 School Management**

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

#### **🏪 Retail Chain Store**

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

### **Advantages of Text to SQL**

#### **⚡ Efficiency Improvement**

* **Traditional approach**: Requires SQL expert to write queries → 30 minutes
* **Text2SQL**: Natural language questions → 3 seconds

#### **🎯 Lower Barrier to Entry**

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

#### **📱 Real-time Interaction**

* Get answers immediately after asking
* Support for follow-up questions
* Dynamic adjustment of query conditions

## How to Use Text to SQL Feature in MaiAgent

{% hint style="info" %}
Before using, you need to prepare: Enterprise-associated database or Excel file (upload to knowledge base)

If using a database, we recommend:

* Ensure clear data table structure
* Create appropriate indexes
* Maintain data quality
  {% endhint %}

### 1. Enter AI Assistant Settings

* Select the AI assistant you want to configure
* Switch to the response mode settings page

<div><figure><img src="/files/E5dcPurNMgtqjvHqn0Nd" alt=""><figcaption></figcaption></figure> <figure><img src="/files/8voGSl92xGkOWiFo14LM" alt=""><figcaption></figcaption></figure></div>

### 2. Switch AI Assistant's Response Mode to Agent Mode

{% hint style="warning" %}
You must switch to Agent mode, otherwise the AI assistant cannot use the Text to SQL feature

For detailed introduction of each response mode, please refer to: [Create AI Assistant](https://github.com/Playma-Co-Ltd/maiagent-user-guide-gitbook/blob/main/build/setup.md#xuan-ze-shi-he-de-hui-da-mo-shi-jian-li-zhi-ling)
{% endhint %}

<figure><img src="/files/K9ObQhPV4TNjGZBTPInR" alt=""><figcaption></figcaption></figure>

### 3. Enter Enterprise Database URL

* Use the dropdown menu to select the database service used within the enterprise
* Enter the database service URL used by the enterprise to allow the MaiAgent system to connect and operate within the database

{% hint style="info" %}

* MaiAgent supports:
  * **MySQL**
  * **PostgreSQL**
  * **Oracle DB**
  * **Microsoft SQL Server (MSSQL)**
* The maiagent option applies Excel files you have uploaded in the MaiAgent knowledge base
  {% endhint %}

<div><figure><img src="/files/1gzHZFov943MTUnj7yTe" alt=""><figcaption></figcaption></figure> <figure><img src="/files/YIN8x8zOR1fNw6yvlg9y" alt=""><figcaption></figcaption></figure></div>

{% hint style="danger" %}
Please ensure the URL format is correct and includes necessary connection information, such as: host name, port, database name, username, and password.
{% endhint %}

#### MaiAgent

{% hint style="info" %}
Please refer to: [Using MaiAgent Knowledge Base for Text to SQL](/maiagent-user-guide/maiagent-user-guide-en/tools/text-to-sql-maiagent.md)
{% endhint %}

#### Microsoft SQL Server(MSSSQL)

Connect to an existing MSSQL database by pasting the MSSQL database connection string

📍Please note: Ensure the database URL is accessible by MaiAgent service

<figure><img src="/files/W7yIEPmxD02xIJ7sKpuo" alt=""><figcaption></figcaption></figure>

#### **MySQL**

Connect to an existing MySQL database by pasting the MySQL database connection string

📍Please note: Ensure the database URL is accessible by MaiAgent service

<figure><img src="/files/u3olNnEIYNbyc0L94zIt" alt=""><figcaption></figcaption></figure>

#### **Oracle**

Connect to an existing Oracle database by pasting the Oracle database connection string

📍Please note: Ensure the database URL is accessible by MaiAgent service

<figure><img src="/files/Xd7fb61TTzCvygyGQGkR" alt=""><figcaption></figcaption></figure>

#### **PostgreSQL**

Connect to an existing PostgreSQL database by pasting the PostgreSQL database connection string

📍Please note: Ensure the database URL is accessible by MaiAgent service

<figure><img src="/files/hf9XPJmbhaniwlMjO1IP" alt=""><figcaption></figcaption></figure>

### **4. Click Save to Preserve Settings**

<figure><img src="/files/EYZHkgMYOdYjamUZADzc" alt=""><figcaption></figcaption></figure>

This way, the AI assistant can help you quickly query your inventory, employee information, etc., and compile well-organized reports and trends for you.

## **Common Troubleshooting**

* **Connection failure**: Check database URL format and network connectivity
* **Query error**: Confirm table names and column names are correct
* **Insufficient permissions**: Check database user permission settings
* **Slow response**: Check query complexity, consider adding indexes

***

Text2SQL turns AI assistants into database experts, enabling anyone to use natural language to quickly gain business insights, dramatically improving the efficiency of data-driven decision-making!


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maiagent.ai/maiagent-user-guide/maiagent-user-guide-en/tools/text2sql.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
