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

# Execute SQL statement with database specified in path

POST /v1/execute/{database}
Content-Type: application/json

Executes an SQL statement and returns the results. Supports both regular
and streaming responses. For streaming, use Accept: application/stream+json header.

This endpoint is functionally identical to `/execute` but with the database
specified in the URL path instead of the request body. This can be more
convenient for clients that organize requests by database.

### Example

```
POST /v1/execute/retail

{
  "statement": "SELECT * FROM customers LIMIT 10",
  "format": "collection"
}
```

The database specified in the path takes precedence over any database
specified in the request body.

Reference: https://ocient.ferndocs.com/api-reference/query-execution/execute-post-database

## Authentication

- `Authorization` header (bearer token, required) — Access token obtained from the login endpoint
- `Authorization` header (basic auth, required) — HTTP Basic authentication with username and password

## Request

### Path parameters

- `database` (string, required)

### Query parameters

- `format` (enum, optional, default: array) — Response format: * array - Returns schema and data as arrays (more efficient for large datasets) * collection - Returns data as JSON objects (more convenient for client processing) **Note**: This parameter is only applicable when using Content-Type: text/plain. When using Content-Type: application/json, specify format in the request body.
  - Allowed values: `array`, `collection`
- `schema` (string, optional) — The schema to use for the SQL statement. **Note**: This parameter is only applicable when using Content-Type: text/plain. When using Content-Type: application/json, specify schema in the request body.

### Headers

- `Accept-Encoding` (string, optional) — Supported compression algorithms for responses. Multiple algorithms can be specified as a comma-separated list. Common values include 'gzip', 'deflate', 'br' (Brotli), or combinations like 'gzip, br'. Note that for large result sets, compression may produce suboptimal results. Without compression the result sets can be chunks of rows and processed in a streaming fashion. With compression the entire result set must be compressed before it is returned to the client. Thus the entire result set will be decompressed on the client before any rows can be processed
- `Accept` (enum, optional, default: application/json) — Supported response media types. Note that regardless of the Accept header, large queries results will always be returned via chunked encoding. Also see the note about compression in the AcceptEncoding section.
  - Allowed values: `application/json`, `application/stream+json`, `application/parquet`
- `Preferred-Encoding` (enum, optional) — Indicates the preferred encoding type from those specified in Accept-Encoding. This header provides fine-grained control when Accept-Encoding contains multiple values, allowing the client to explicitly specify which encoding is preferred for this specific request.
  - Allowed values: `gzip`, `br`
- `Preferred-Compression-Level` (integer, optional) — Specifies the desired compression level for the selected encoding algorithm. Values typically range from 1 (fastest, least compression) to 9 (slowest, maximum compression). The exact behavior depends on the specific compression algorithm being used.

### Body (application/json)

This endpoint expects an ExecuteRequest.

- `statement` (string, required) — Parameters to substitute in the SQL statement. The keys should match the parameter names in the statement (without the enclosing braces). String values are wrapped in single quotes, all other types are unquoted. Null values will be expanded as null. **Example**: If your SQL is `SELECT * FROM orders WHERE order_date > {start_date}`, you would provide `{"start_date": "2023-01-01"}` in this field.
- `database` (string, optional) — Target database name to execute the query against. If not specified, the database from authentication will be used.
- `format` (enum, optional, default: array) — Response format: * array - Returns schema and data as arrays (more efficient for large datasets) * collection - Returns data as JSON objects (more convenient for client processing)
  - Allowed values: `array`, `collection`
- `params` (map from string to any, optional) — Parameters to substitute in the SQL statement. The keys should match the parameter names in the statement (without the enclosing braces). String values are wrapped in single quotes, all other types are unquoted. Null values will be expanded as null. **Example**: If your SQL is `SELECT * FROM orders WHERE order_date > {start_date}`, you would provide `{"start_date": "2023-01-01"}` in this field.
- `fetch_size` (integer, optional, default: 0) — Number of rows to return in each chunk for streaming responses. A value of 0 means the database can determine how many to return. - For interactive applications: Use smaller values (100-1000) - For batch processing: Use larger values (5000-10000)
- `max_rows` (integer, optional, default: 9223372036854776000) — The maximum number of rows to return. Note that the SQL LIMIT clause is much preferred, since the query engine will generate the total number of rows, but then only max_rows will be returned to the caller.
- `schema` (string, optional) — The schema to use for this statement

## Response

### 200

Query executed successfully

- `Query Execution_execute_post_database_Response_200`
  - ArrayExecuteResponse
  - CollectionExecuteResponse

## Errors

### 401 Unauthorized Error

Unauthorized

- `status` (Status, required)

### 404 Not Found Error

Object not found

- `status` (Status, required)

### 500 Internal Server Error

Server Error

- `status` (Status, required)

## Types

### ArrayExecuteResponse

- `query_id` (string, required, nullable) — Unique identifier for the query.
- `status` (Status, required)
- `schema` (list of ArrayExecuteResponseSchemaItems, required) — Array of column metadata objects describing the structure of the result set. Each object contains the column name and data type.
- `data` (list of list of any, required) — Two-dimensional array containing the query results. The outer array represents rows, and each inner array contains column values in the same order as defined in the schema.

### CollectionExecuteResponse

- `query_id` (string, required, nullable) — Unique identifier for the query.
- `status` (Status, required)
- `data` (list of map from string to any, required) — Array of objects representing the query results. Each object has properties corresponding to the column names from the query.

### Status

- `reason` (string, required) — Human-readable description of the operation result
- `sql_state` (string, required) — SQL state code (see Error Handling section for common codes)
- `vendor_code` (integer, required) — Vendor-specific error code

### ArrayExecuteResponseSchemaItems

- `name` (string, required) — Column name
- `type` (string, required) — Column data type. Common types include: - INTEGER, BIGINT, SMALLINT (whole numbers) - DOUBLE, REAL, DECIMAL (floating point numbers) - VARCHAR, CHAR, TEXT (text data) - DATE, TIMESTAMP, TIME (temporal data) - BOOLEAN (true/false values) - ARRAY, MAP, TUPLE (complex types)

## Examples

**Request**

```json
{
  "statement": "SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100"
}
```

**Response**

```json
{
  "query_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": {
    "reason": "Query executed successfully",
    "sql_state": "00000",
    "vendor_code": 0
  },
  "data": [
    {
      "station_id": "KORD",
      "temperature": 12.5,
      "timestamp": "2023-01-01T12:00:00Z"
    },
    {
      "station_id": "KORD",
      "temperature": 15.3,
      "timestamp": "2023-01-01T13:00:00Z"
    },
    {
      "station_id": "KORD",
      "temperature": 10.2,
      "timestamp": "2023-01-01T14:00:00Z"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://v1/execute/database"

querystring = {"format":"collection","schema":"mydata"}

payload = { "statement": "SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100" }
headers = {
    "Accept-Encoding": "gzip, deflate, br",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://v1/execute/database?format=collection&schema=mydata';
const options = {
  method: 'POST',
  headers: {
    'Accept-Encoding': 'gzip, deflate, br',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"statement":"SELECT * FROM weather.observations WHERE station_id = \'KORD\' LIMIT 100"}'
};

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://v1/execute/database?format=collection&schema=mydata"

	payload := strings.NewReader("{\n  \"statement\": \"SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100\"\n}")

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

	req.Header.Add("Accept-Encoding", "gzip, deflate, br")
	req.Header.Add("Authorization", "Bearer <token>")
	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://v1/execute/database?format=collection&schema=mydata")

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

request = Net::HTTP::Post.new(url)
request["Accept-Encoding"] = 'gzip, deflate, br'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"statement\": \"SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100\"\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://v1/execute/database?format=collection&schema=mydata")
  .header("Accept-Encoding", "gzip, deflate, br")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"statement\": \"SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100\"\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://v1/execute/database?format=collection&schema=mydata', [
  'body' => '{
  "statement": "SELECT * FROM weather.observations WHERE station_id = \'KORD\' LIMIT 100"
}',
  'headers' => [
    'Accept-Encoding' => 'gzip, deflate, br',
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://v1/execute/database?format=collection&schema=mydata");
var request = new RestRequest(Method.POST);
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"statement\": \"SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Accept-Encoding": "gzip, deflate, br",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["statement": "SELECT * FROM weather.observations WHERE station_id = 'KORD' LIMIT 100"] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://v1/execute/database?format=collection&schema=mydata")! 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()
```