# Query Datasets with SQL

`POST /analytics/query` · Core · Analytics & Intelligence

Runs a read-only SQL `SELECT` over the project's datasets and returns the rows. Body: `sql` (at most 100,000 characters) and `datasets` (the dataset slugs the query reads, 1 to 64). Reference each as `dataset.<slug>`; a table that is not a declared dataset is refused with `400 K9O_QUERY_INVALID`.

Requires the PROJECT_ADMIN, PROJECT_AUTHOR or PROJECT_EDITOR role and the `datasets:query` permission on every dataset it reads.

Callers must be members of the project (an organization role alone does not grant access); project service tokens and extension tokens cannot call it.

Returns `503 K9O_ANALYTICS_UNAVAILABLE` until the region's analytics storage is provisioned.

## Parameters

| Name | In | Required | Description |
|---|---|---|---|
| `projectSlug` | path | yes | The project's slug: the path segment after `@`. It is unique within the org. Example: `"storefront"`. |

## Request body

| Field | Type | Required | Description |
|---|---|---|---|
| `sql` | string | yes | DuckDB SQL; every table is `dataset.<slug>` and must be listed in `datasets`. |
| `datasets` | array of string | yes | The slugs of every dataset the SQL reads, without the `dataset.` prefix. The query is refused if the SQL reads a dataset not listed here, or one the caller may not query. |

## Responses

- **200**: Success

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | array of object | yes | The result rows, keyed by the query's column names. |
| `meta` | object | yes | Request metadata: cost, timing and correlation ids. |
| `meta.cost` | object | yes | Metered usage for this request; empty when nothing was metered. |
| `meta.timing` | object | yes |  |
| `meta.timing.gatewayMs` | number | yes |  |
| `meta.timing.totalMs` | number | yes |  |
| `meta.context` | object | yes |  |
| `meta.context.requestId` | string | yes |  |
| `meta.context.traceId` | string | yes |  |
| `meta.context.projectId` | string | no |  |
| `meta.warnings` | array of object | no |  |
| `meta.warnings.[]code` | string | yes |  |
| `meta.warnings.[]message` | string | yes |  |


## Errors

| HTTP | Code | When |
|---|---|---|
| 401 | `K9O_UNAUTHENTICATED` | The caller is not signed in. |
| 403 | `K9O_ACCESS_DENIED` | The caller is not a member of this project; an organization role alone does not grant access. |
| 403 | `K9O_RBAC_DENY` | Only PROJECT_ADMIN, PROJECT_AUTHOR and PROJECT_EDITOR may query datasets. |
| 403 | `K9O_IAM_POLICY_DENIED` | The caller's role or IAM policy does not grant datasets:query. |
| 400 | `K9O_INVALID_FIELD_VALUE` | The body is not an object, `sql` is empty or too long, or `datasets` is empty, too long or names an invalid slug. |
| 400 | `K9O_QUERY_INVALID` | The SQL cannot be parsed, or reads a table that is not one of the declared datasets. |
| 404 | `K9O_DATASET_NOT_FOUND` | No active dataset with this slug exists in the project. |
| 500 | `K9O_QUERY_EXECUTION_FAILED` | The query failed while running. |
| 503 | `K9O_ANALYTICS_UNAVAILABLE` | The region's analytics storage is not available yet; retry later. |

## Code samples

### cURL

```bash
curl -X POST 'https://<org>.api-<region>.k9o.io/@storefront/analytics/query' \
  -H 'Authorization: Bearer $K9O_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{}'
```

### fetch

```javascript
const res = await fetch('https://<org>.api-<region>.k9o.io/@storefront/analytics/query', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.K9O_TOKEN}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({}),
});
const { data, meta } = await res.json();
```

### k9o CLI

```bash
k9o analytics query --sql <sql|@file|-> --datasets a,b,...
```

### @k9o/core

```typescript
// const k9o = new K9o({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })
const { data } = await k9o.analytics.query({})
```

### k9o

```python
# k9o = create_client(org_slug="playground", project_slug="storefront", api_key="k9o_…")
response = k9o.analytics.query({})
```

### sdk-go

```go
// ctx := context.Background()
// client, _ := k9o.NewClient(k9o.ClientOpts{OrgSlug: "playground", ProjectSlug: "storefront", APIKey: "k9o_…"})
data, _, kerr := client.Analytics.Query(ctx, map[string]any{})
```

### k9o

```rust
// let k9o = Client::new(ClientOpts { org_slug: "playground".into(), project_slug: "storefront".into(), api_key: "k9o_…".into() })?;
let resp = k9o.analytics.query(json!({})).await?
```

### dev.k9o:core

```java
// K9o k9o = K9o.createClient(K9o.Opts.builder().orgSlug("playground").projectSlug("storefront").apiKey("k9o_…").build());
var response = k9o.analytics().query(Map.of())
```

### K9o.Core

```c#
// var k9o = K9oClient.Create(new K9oOptions { OrgSlug = "playground", ProjectSlug = "storefront", ApiKey = "k9o_…" });
var response = await k9o.Analytics.QueryAsync(new Dictionary<string, object> {  })
```

### k9o

```ruby
# k9o = K9o.create_client(org_slug: "playground", project_slug: "storefront", api_key: "k9o_…")
response = k9o.analytics.query({  })
```

### k9o/sdk

```php
// $k9o = K9oClient::create(['org_slug' => 'playground', 'project_slug' => 'storefront', 'api_key' => 'k9o_…']);
$response = $k9o->analytics->query([])
```


Canonical page: https://docs.kilimanjaro.dev/api-playground/core/query-datasets-with-sql
