---
orphan: true
---

# Run NL2SQL

Execute NL2SQL-generated SQL in the specified database and return the result columns and rows.

```text
POST https://moi.matrixorigin.cn/newmoi/catalog/nl2sql/run_sql
```

## Preparation before calling

First confirm the SQL statement and target database. Prepare a personal access token, target workspace ID, database ID, and SQL statement with access to the target workspace.

The example below uses:

- `$AI_STUDIO_API_KEY`: The actual personal access token, passed through the `X-API-Key` Header.
- `$WORKSPACE_ID`: Target workspace ID, passed through `X-Workspace-ID` Header.
- `$DATABASE_ID`: Database ID where SQL is executed.

This interface will execute the submitted SQL; please confirm the impact scope of the statement before submitting.

## Request example

```bash
curl -X POST "https://moi.matrixorigin.cn/newmoi/catalog/nl2sql/run_sql" \
  -H "X-API-Key: $AI_STUDIO_API_KEY" \
  -H "X-Workspace-ID: $WORKSPACE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "database_id": '"$DATABASE_ID"',
    "sql": "SELECT * FROM orders LIMIT 10"
  }'
```

## Request body

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `database_id` | integer | Yes | Database ID for executing SQL. |
| `sql` | string | Yes | The SQL to execute. |

## Successful response

On success, returns `200`, the result column name, and the result row.

```json
{
  "code": "OK",
  "msg": "OK",
  "data": {
    "columns": ["id", "amount"],
    "rows": [[1, 100]]
  }
}
```

The response fields are as follows.

| Field | Type | Description |
| --- | --- | --- |
| `data.columns` | string[] | Result set column name. |
| `data.rows` | array | Query result row; the field order of each row is the same as `columns`. |

`[]` after a type means an array. For example, `string[]` is an array of strings.

## Error response

```json
{
  "code": "ErrServer",
  "msg": "服务器内部错误",
  "data": null
}
```

### Common HTTP errors

```{list-table}
:header-rows: 1
:widths: 12 22 32 34

* - HTTP status code
  - error code
  - Common causes
  - Recommended actions
* - `400`
  - `ErrParamInvalid`
  - Invalid database ID, SQL, or request body.
  - Check request fields and SQL syntax.
* - `403`
  - `ErrForbidden`
  - The current identity does not have permission to execute SQL.
  - Use authorized credentials.
* - `500`
  - `ErrServer`
  - SQL execution or result reading failed.
  - Check the SQL and try again.
```
