> 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/maiagent-user-guide-en/database/text-to-sql-maiagent.md).

# Text to SQL with MaiAgent Database

To have the AI Assistant help you analyze spreadsheet data such as Excel and CSV files, simply upload the files to the MaiAgent Database. The AI Assistant can then query the data using natural language and produce statistical analysis results.

{% hint style="info" %}
For an introduction to the Text to SQL concept, see: [Text to SQL Feature](/maiagent-user-guide/maiagent-user-guide-en/database/text2sql.md)
{% endhint %}

## Step 1: Create a MaiAgent Database <a href="#step-1-create-maiagent-database" id="step-1-create-maiagent-database"></a>

1. Navigate to "<mark style="color:blue;">AI Features</mark>" > "<mark style="color:blue;">Database</mark>" from the left sidebar
2. Click "<mark style="color:blue;">Add Database</mark>"
3. Select "<mark style="color:blue;">MaiAgent Database</mark>"
4. Enter a database name (e.g., "2024 Annual Sales Data") and click Create

{% hint style="info" %}
For detailed creation steps, see: [Create and Configure Database](/maiagent-user-guide/maiagent-user-guide-en/database/create-database.md)
{% endhint %}

## Step 2: Upload Spreadsheet Files <a href="#step-2-upload-spreadsheet" id="step-2-upload-spreadsheet"></a>

After creation, go to the database settings page:

1. Switch to the "<mark style="color:blue;">Table Management</mark>" tab
2. Click "<mark style="color:blue;">Upload Table File</mark>"
3. Drag and drop or select your spreadsheet file

You can download the sample file (a food sales file with 100 items in .xlsx format) to test and experience the AI Assistant's data analysis capabilities.

After the upload is complete, wait for the processing status to show "<mark style="color:blue;">Success</mark>", which indicates the data table has been created successfully.

{% hint style="warning" %}
Supported formats: `.csv`, `.xlsx`, `.xls`, `.json`, `.jsonl`. Each worksheet in an Excel file will be created as a separate data table.
{% endhint %}

#### Table Format Notes <a href="#table-format-notes" id="table-format-notes"></a>

* [x] Each worksheet (Sheet) must contain only one table
* [x] The first row must be field names
* [x] It is recommended to annotate data formats after field names, such as: `Price(int)`, `Date(datetime)`
* [x] Data types within each field should be consistent
* [x] If there are special formats (e.g., currency, percentages), standardize the formatting before uploading

{% hint style="info" %}
To improve AI query accuracy, it is recommended to add descriptions to data tables and fields. See: [Create and Configure Database — Edit Field Descriptions](/maiagent-user-guide/maiagent-user-guide-en/database/create-database.md#bian-ji-lan-wei-miao-shu)
{% endhint %}

## Step 3: Link AI Assistant <a href="#step-3-link-ai-agent" id="step-3-link-ai-agent"></a>

Link the database to your AI Assistant so it can query the data:

1. Switch to the "<mark style="color:blue;">Linked AI Assistants</mark>" tab
2. Select the AI Assistant to link from the left side and move it to the right
3. Click "<mark style="color:blue;">Save</mark>"

{% hint style="warning" %}
Ensure the AI Assistant's Response Mode is set to **Agent Mode**, otherwise the Text to SQL feature cannot be used.

For detailed Response Mode settings, see: [Create AI Assistant](https://github.com/Playma-Co-Ltd/maiagent-user-guide-gitbook/tree/main/en/build/setup.md)
{% endhint %}

## Step 4: Chat with the AI Assistant <a href="#step-4-chat-with-ai-agent" id="step-4-chat-with-ai-agent"></a>

Once the above steps are complete, you can go to the AI Assistant's conversation page and describe your needs directly using natural language.

{% hint style="info" %}
For the AI Assistant conversation interface, see: [Choose an Integration Platform](/maiagent-user-guide/maiagent-user-guide-en/conversations/choose-channel.md) to select the most suitable conversation platform for your needs.
{% endhint %}

### Data Analysis <a href="#data-analysis" id="data-analysis"></a>

The Text to SQL tool can help you analyze data in spreadsheets. For example: "Find the best-selling dairy product from last year"

* When you make a request, the AI Assistant will automatically invoke the Text-to-SQL tool.
* This tool acts like a translator, converting your natural language into SQL syntax that the computer can understand, allowing the AI Assistant to extract data from the database.

The AI Assistant automatically adds conditional logic, sorting criteria, and other query constraints to convert your request into a more complete query command.

* **AI Assistant's Query Reasoning:** Find the best-selling dairy product from last year, sorted by sales quantity in descending order. It automatically adds descending order conditions to better match your needs.
* **AI Assistant's Response (click the tool response to view):**

**Result**

* The AI Assistant found all sales data for "Dairy Products" along with other field data for those items.
* Each row represents a data record, including: Product ID, Product Name, Product Category, Sales Amount, Sales Quantity, etc.
* Based on this data, the AI Assistant determined that the best-selling dairy product is "Cheese", with a sales quantity of 110 and sales amount of 40,150 TWD.

### Report Creation (Canvas Mode) <a href="#report-creation-canvas-mode" id="report-creation-canvas-mode"></a>

The Text to SQL tool can also help you create polished reports. This feature requires enabling Canvas Mode:

1. Go to "AI Assistant Settings Page > Response Mode Settings" and find <mark style="color:blue;">Agent Mode</mark>
2. Change Agent Mode from Standard Mode to <mark style="color:blue;">**Canvas Mode**</mark>

After saving the settings, you can chat with the AI Assistant. For example: "Please generate a visualized revenue report with statistics"

* **AI Assistant's Query Reasoning:** Calculate revenue statistics for each product in the food company, including total revenue, average revenue, revenue standard deviation, revenue distribution ranges, revenue share by category, and other statistical metrics. It automatically generates the calculation results needed for the report to better match your needs.
* **AI Assistant's Response (click the tool response to view):**

{% code overflow="wrap" %}

```
[('Category Revenue Share - Staples', '10.72%'), ('Category Revenue Share - Dairy', '11.97%'), ('Category Revenue Share - Frozen', '9.06%'), ('Category Revenue Share - Canned', '10.25%'), ('Category Revenue Share - Meat', '13.23%'), ('Category Revenue Share - Fruits & Vegetables', '13.34%'), ('Category Revenue Share - Condiments', '4.51%'), ('Category Revenue Share - Snacks', '14.53%'), ('Category Revenue Share - Beverages', '12.40%'), ('Total Products', '100'), ('Average Revenue', '19546.06'), ('Minimum Revenue', '1400'), ('Maximum Revenue', '63364'), ('Revenue Std Dev', '15736.83'), ('Total Revenue', '1954606')]
```

{% endcode %}

**Result**

* The AI Assistant received the automatically computed results for all required statistical items from the tool.
* The AI Assistant used this data as the basis for visualization and created an interactive report interface using Canvas.

> Click the "Use Canvas" box to view the content

The report display is shown below. You can:

1. Toggle between viewing the source code or the rendered view
2. Switch report content by statistical category (this varies depending on each AI Assistant's output)

When switching to other categories, you can view the category revenue share pie chart and distribution analysis bar chart:

{% hint style="info" %}
**Additional Tips**

* **Data quality matters:** Ensure your spreadsheet data is clean and accurate, as this directly affects the accuracy of the AI Assistant's analysis results.
* **Data you do not want the AI to access must be deleted:** Hidden data in spreadsheets can still be parsed and provided to the AI Assistant. Therefore, data you do not want exposed cannot simply be hidden — it must be deleted.
* **Try different questions:** By asking questions in different ways, you can uncover more valuable insights from your data.
* **Make good use of Canvas Mode:** Canvas Mode allows you to easily create various visualized reports for a more intuitive presentation of data analysis results.
* **Make good use of field descriptions:** Adding descriptions to data table fields can significantly improve AI query accuracy.
  {% endhint %}


---

# 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 dynamically by asking a question.

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

```
GET https://docs.maiagent.ai/maiagent-user-guide/maiagent-user-guide-en/database/text-to-sql-maiagent.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
