> 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/tools/text-to-sql-supabase.md).

# Text to SQL with Supabase

## What Is Supabase?

Supabase is an open-source platform service designed to simplify modern application development. Its core features include:

* **Database:** Store various types of data.
* **Real-time updates:** Your application is notified immediately when data changes.
* **Account management:** Manage user accounts and passwords.
* **Built-in authentication mechanism:** A built-in authentication mechanism that simplifies user identity management and provides multiple authentication methods.
* **Auto-generated API (data access endpoints):** Access your database data through simple methods.

### Benefits of Integrating Supabase

* **Cross-table queries:** Supabase supports multi-table relationships, allowing you to query relationships between Table A and Table B.
* **Indexing for improved query performance:** You can create indexes on frequently queried content to help the AI assistant find what you need more precisely.

## Set Up Your Supabase

### 1. Create a Supabase Account

* First, go to the [Supabase website](https://supabase.com/) and click "Sign in / Start your project."

> If you haven't registered yet, please create an account first to proceed with the following steps

* After logging in, you can create a new organization or use an existing one. Within the organization, create a project — each project has its own independent database.

### 2. Navigate to the Database Page

After entering the project, click Database > Tables in the left navigation bar to add data

#### Create a New Table

Click "New Table" to create a table and name it:

Supabase offers several ways to create a new table:

* **Manually add columns:** Suitable for designing the table structure from scratch. You can add columns one by one and set each column's data type, default value, etc.
* **Import .csv/.tsv or plain text:** Suitable for quickly creating tables, especially when you already have existing data.
  * **Notes:**
    * The first row of a plain text file must contain column names, with columns separated by commas (CSV) or tabs (TSV).

Here, choose to import data: click "<mark style="color:blue;">Import data from CSV</mark>" and paste a tab-separated text file. Scroll down to see the table result. After import is complete, click "Save."

#### Primary Key

After the import is complete, you are redirected to the settings page where you must specify a primary key. A primary key is like an ID number — it uniquely identifies each record. Here, we select Customer ID as the primary key.

#### Foreign Key

Scroll down to see the Foreign Key settings. A Foreign Key is like an address that points to the source of a record or more detailed data associated with it.

Suppose we have two tables: "Customers" and "Orders."

* **Customers Table:**
  * CustomerID - Primary Key
  * CustomerName
  * Phone
  * Address
* **Orders Table:**
  * OrderID - Primary Key
  * CustomerID - Foreign Key (references CustomerID in the Customers table)
  * OrderDate
  * TotalAmount

In this example, the "CustomerID" in the Orders table is a foreign key that references the primary key "CustomerID" in the Customers table. Through this foreign key, we can identify which customer placed each order.

{% hint style="info" %}
In this example, the foreign key should be placed in the Order Table:

**Relationship direction:**

* One customer → can have multiple orders (one-to-many relationship)
* One order → belongs to only one customer

**Foreign key principle:**

> The foreign key should be placed on the "many" side

Therefore:

* The Order Table has a `customer_id` (foreign key), because it is the "many" side in the one-to-many relationship
* The Customer Table does not need to store order information
  {% endhint %}

Therefore, we set up the Order Table to link the Customer ID in the Customer Table to the Customer ID in the Order Table.

After the relationship is configured, click "Save" to establish the database relationship.

### 3. Setup Complete

Once the tables are created, you have a complete database and can query data within it using SQL syntax.

## How to Create a Supabase Tool

To use the Supabase tool on MaiAgent, you need to create it as an MCP tool so the AI assistant can access Supabase functionality:

{% hint style="info" %}
For tool introduction, see: [Tool Overview](/maiagent-user-guide/maiagent-user-guide-en/tools/tool_description.md)
{% endhint %}

{% stepper %}
{% step %}
**Create a Server on an MCP Service Platform and Connect to Supabase**

For how to connect MCP tools, see: [Remote MCP Service Overview](https://docs.maiagent.ai/tech/remote-mcp/remote-mcp). Currently, only the [Composio Platform](https://docs.maiagent.ai/tech/remote-mcp/composio) supports Supabase integration.
{% endstep %}

{% step %}
**Enable Available Features in Composio**

When connecting to Composio, enable basic database operations such as create, delete, query, etc.

{% hint style="warning" %}
Composio has basic options pre-selected under Important by default. You do not need additional configuration — just make sure the Important options remain checked.
{% endhint %}
{% endstep %}

{% step %}
**Add the Configured Supabase Tool to the Available Tools List**

For how to create MCP tools, see: [Create MCP Tools](/maiagent-user-guide/maiagent-user-guide-en/build/setup.md)

**Supabase Tool Connection URL**

After creating the server service on the MCP service platform, process the URL as follows:

1. Original URL (obtained from the MCP Server):\
   [https://backend.composio.dev/v3/mcp/12345678/mcp?include\_composio\_helper\_actions=true](https://backend.composio.dev/v3/mcp/5987158a-806a-4c32-9ff6-4236e8891ac2/mcp?include_composio_helper_actions=true)
2. Remove "[?include\_composio\_helper\_actions=true](https://backend.composio.dev/v3/mcp/5987158a-806a-4c32-9ff6-4236e8891ac2/mcp?include_composio_helper_actions=true)" entirely
3. New URL (to paste on the MaiAgent tools page):\
   [https://backend.composio.dev/v3/mcp/12345678/mcp](https://backend.composio.dev/v3/mcp/5987158a-806a-4c32-9ff6-4236e8891ac2/mcp?include_composio_helper_actions=true)

{% hint style="danger" %}
You must remove the above content; otherwise, the AI assistant will not be able to use the Supabase tool correctly.
{% endhint %}
{% endstep %}
{% endstepper %}

After the tool is created, go to the AI assistant settings and add the Supabase tool to the assistant's available tools list:

{% hint style="danger" %}
Make sure to click Save on the tools page; otherwise, the AI assistant still cannot use the Supabase tool.
{% endhint %}

## Using the Supabase Tool

With MaiAgent AI assistant and the Supabase tool, simply describe the data you want to query in everyday language, and Supabase automatically generates the corresponding SQL syntax to extract the information you need from the relational database.

### Sample Database

#### **1. Customers Table** <a href="#id-1.-customers-biao-ge-gu-ke-zi-xun" id="id-1.-customers-biao-ge-gu-ke-zi-xun"></a>

<table><thead><tr><th width="242.3333740234375">Column Name</th><th width="98.6666259765625">Primary Key</th><th width="92.77777099609375">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>CustomerID</code></td><td>Yes</td><td>Yes</td><td>Unique customer identifier</td></tr><tr><td><code>CustomerName</code></td><td>No</td><td>No</td><td>Customer company or individual name</td></tr><tr><td><code>CustomerType</code></td><td>No</td><td>No</td><td>Customer category (e.g., Retailer, Restaurant, Distributor)</td></tr><tr><td><code>ContactName</code></td><td>No</td><td>No</td><td>Primary contact name</td></tr><tr><td><code>Phone</code></td><td>No</td><td>No</td><td>Contact phone number</td></tr><tr><td><code>Email</code></td><td>No</td><td>No</td><td>Email address</td></tr><tr><td><code>Address</code></td><td>No</td><td>No</td><td>Customer address</td></tr><tr><td><code>Region</code></td><td>No</td><td>No</td><td>Geographic region (e.g., North, South)</td></tr><tr><td><code>CustomerLevel</code></td><td>No</td><td>No</td><td>Customer importance level (A, B, C)</td></tr></tbody></table>

**Primary Key**: `CustomerID`\
**Foreign Key Relationships**: None

***

#### **2. Orders Table** <a href="#id-2.-orders-biao-ge-ding-dan-zi-xun" id="id-2.-orders-biao-ge-ding-dan-zi-xun"></a>

<table><thead><tr><th width="235.88897705078125">Column Name</th><th width="92.66668701171875">Primary Key</th><th width="94.3333740234375">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>OrderID</code></td><td>Yes</td><td>Yes</td><td>Unique order identifier</td></tr><tr><td><code>CustomerID</code></td><td>No</td><td>No</td><td>References the Customers table</td></tr><tr><td><code>OrderDate</code></td><td>No</td><td>No</td><td>Order creation date</td></tr><tr><td><code>DeliveryDate</code></td><td>No</td><td>No</td><td>Expected or actual delivery date</td></tr><tr><td><code>PaymentMethod</code></td><td>No</td><td>No</td><td>Payment method (Cash, Credit Card, Wire Transfer)</td></tr><tr><td><code>OrderStatus</code></td><td>No</td><td>No</td><td>Order processing status</td></tr><tr><td><code>TotalAmount</code></td><td>No</td><td>No</td><td>Order total amount (numeric)</td></tr><tr><td><code>ShippingFee</code></td><td>No</td><td>No</td><td>Shipping cost</td></tr></tbody></table>

**Primary Key**: `OrderID`\
**Foreign Key Relationships**:

* `CustomerID` → `Customers.CustomerID` (The CustomerID in Orders references the CustomerID in the Customers table)

***

#### **3. Products Table** <a href="#id-3.-products-biao-ge-shang-pin-zi-xun" id="id-3.-products-biao-ge-shang-pin-zi-xun"></a>

<table><thead><tr><th width="202.3333740234375">Column Name</th><th width="88.5555419921875">Primary Key</th><th width="100">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>ProductID</code></td><td>Yes</td><td>Yes</td><td>Unique product identifier</td></tr><tr><td><code>ProductName</code></td><td>No</td><td>No</td><td>Product name</td></tr><tr><td><code>Description</code></td><td>No</td><td>No</td><td>Detailed product description</td></tr><tr><td><code>Category</code></td><td>No</td><td>No</td><td>Product category</td></tr><tr><td><code>Brand</code></td><td>No</td><td>No</td><td>Product brand</td></tr><tr><td><code>Size</code></td><td>No</td><td>No</td><td>Product specification or size</td></tr><tr><td><code>Cost</code></td><td>No</td><td>No</td><td>Product cost (numeric)</td></tr><tr><td><code>Price</code></td><td>No</td><td>No</td><td>Product selling price (numeric)</td></tr><tr><td><code>StockQuantity</code></td><td>No</td><td>No</td><td>Current stock quantity (numeric)</td></tr></tbody></table>

**Primary Key**: `ProductID`\
**Foreign Key Relationships**: None

### Scenario 1: Track Incomplete Orders

* **Database state:** The `Orders` table has two incomplete orders: `OR003` and `OR004`.
* **Natural language input:** In the AI assistant's chat, simply type: "Tell me which orders are not yet completed." The AI assistant automatically invokes the tool and generates a structured SQL query.
* **Supabase automatic query:** The AI assistant automatically invokes the Supabase tool, converting your natural language into an SQL query, such as:

Combining the query results with the AI assistant's analysis, the AI assistant responds with the following order information, sorted by priority:

Through the collaboration of the Supabase tool and the AI assistant, you can easily track incomplete orders and receive analysis and prioritization suggestions from the AI assistant, enabling more efficient order processing and improved customer satisfaction.

### Scenario 2: Query Contact Information for Incomplete Orders

* Order OR003 is still being processed, with customer CU003 and the contact person being **Huang Procurement**
* **Natural language input:** In the AI assistant's chat, type: "Who should I contact for the orders still being processed?" The AI assistant automatically invokes the tool and generates a structured SQL query.
* **Supabase automatic relational query:** Although the conversation with the AI assistant is about the Orders table, through the configured foreign key relationships, Supabase knows that the `Customer ID` here references the `ID` in the `Customers` table, so the returned content comes from the `Customers` table.
* **AI assistant response:** The AI assistant then provides the correct contact information and other contact methods based on its analysis.

Through the Supabase tool, you can fully leverage table relationships in the database to easily extract information from multiple related tables and receive a customer name list from the AI assistant. The clearly defined relationships between tables ensure data consistency and reliability, making query results more trustworthy.

## **Additional Notes:**

* You can adjust the natural language input based on your actual needs, such as: "Tell me about today's incomplete orders" or "Tell me about VIP customers' incomplete orders." The Supabase tool can accurately parse and execute these queries.
* The AI assistant can further integrate other information, such as inventory status and logistics information, to provide more comprehensive order analysis.

{% hint style="warning" %}
The tool can only access data stored in your database. If you have analysis needs, make sure to upload the data to the database before starting the analysis.
{% 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/tools/text-to-sql-supabase.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.
