> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.athenaintel.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.athenaintel.com/_mcp/server.

# Execute SQL against database

POST https://api.athenaintel.com/api/v0/databases/{asset_id}/sql
Content-Type: application/json

Execute a SQL statement against the database. SELECT queries return columns and rows. Non-SELECT statements (CREATE, INSERT, UPDATE, DELETE, ALTER, DROP, etc.) return execution statuses.

Reference: https://docs.athenaintel.com/api-reference/databases/execute-sql

## Authentication

- `X-API-KEY` header (required) — API Key authentication via header

## Request

### Path parameters

- `asset_id` (string, required)

### Body (application/json)

This endpoint expects a DatabaseSqlRequest.

- `sql` (string, required) — SQL statement to execute

## Response

### 200

Successful Response

- `columns` (list of string, optional, nullable) — Column names (populated for SELECT queries)
- `rows` (list of map from string to any, optional, nullable) — Row data as objects (populated for SELECT queries)
- `statuses` (list of string, optional, nullable) — Execution statuses (populated for non-SELECT statements)

## Errors

### 400 Bad Request Error

Invalid request (not a database asset or empty SQL), a statement the database rejected (its own message is the detail), or a statement cancelled on its 45 s budget (`Query timed out after …`; a cancelled single write was rolled back, a multi-statement submission may have applied earlier statements)

- `any`

### 403 Forbidden Error

Access denied to database

- `any`

### 404 Not Found Error

Database asset not found

- `any`

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

### 500 Internal Server Error

Internal server error

- `any`

### 501 Not Implemented Error

Provider not supported

- `any`

### 503 Service Unavailable Error

Database unavailable: starting or suspended, saturated (new statements are refused while running ones finish), or its control plane busy or not answering. `Retry-After` says when to retry; a refused statement did not run.

- `any`

## Types

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)
- `ctx` (ValidationErrorCtx, optional)
- `input` (any, optional)

### ValidationErrorLocItems

### ValidationErrorCtx

## Examples

**Request**

```json
{
  "sql": "SELECT id, name FROM users WHERE active = true LIMIT 10"
}
```

**Response**

```json
{
  "columns": [
    "id",
    "name"
  ],
  "rows": [
    {
      "id": 1,
      "name": "Alice"
    },
    {
      "id": 2,
      "name": "Bob"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.athenaintel.com/api/v0/databases/asset_id/sql"

payload = { "sql": "SELECT id, name FROM users WHERE active = true LIMIT 10" }
headers = {
    "X-API-KEY": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.athenaintel.com/api/v0/databases/asset_id/sql';
const options = {
  method: 'POST',
  headers: {'X-API-KEY': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"sql":"SELECT id, name FROM users WHERE active = true LIMIT 10"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.athenaintel.com/api/v0/databases/asset_id/sql"

	payload := strings.NewReader("{\n  \"sql\": \"SELECT id, name FROM users WHERE active = true LIMIT 10\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-API-KEY", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.athenaintel.com/api/v0/databases/asset_id/sql")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-API-KEY"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"sql\": \"SELECT id, name FROM users WHERE active = true LIMIT 10\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.athenaintel.com/api/v0/databases/asset_id/sql")
  .header("X-API-KEY", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"sql\": \"SELECT id, name FROM users WHERE active = true LIMIT 10\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.athenaintel.com/api/v0/databases/asset_id/sql', [
  'body' => '{
  "sql": "SELECT id, name FROM users WHERE active = true LIMIT 10"
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-API-KEY' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.athenaintel.com/api/v0/databases/asset_id/sql");
var request = new RestRequest(Method.POST);
request.AddHeader("X-API-KEY", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"sql\": \"SELECT id, name FROM users WHERE active = true LIMIT 10\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-API-KEY": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = ["sql": "SELECT id, name FROM users WHERE active = true LIMIT 10"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.athenaintel.com/api/v0/databases/asset_id/sql")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```