# Query with SQL

`POST /query` · Core · Data, Queries & Vectors

Executes a parameterised raw SQL statement against the project's user-data schema (`k9o_<proj_id>`). The request body carries `sql` (string) and an optional `params` array of positional bind values. Params are bound via Postgres positional placeholders (`$1`, `$2`, …) and never interpolated into the SQL text.

POST is used for all raw SQL regardless of read/write intent because the SQL cannot be safely carried in a URL parameter. RLS policies apply to all returned rows. DDL statements (`CREATE`, `DROP`, `ALTER`) are rejected because the `_query` credential lacks DDL grants.

Returns `K9O_INJECTION_DETECTED` (400) at the SDK layer when bare-string SQL contains unparameterised dynamic content.

## 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 | One read-only statement starting with SELECT or WITH, at most 100,000 characters. Bare table names are the project's collections. A query that names `dataset.<slug>` runs against those analytics datasets instead (address a collection there as `pg.<collection>`). Writes (INSERT, UPDATE, DELETE), DDL, SET/RESET, transaction control and more than one statement are refused. Use `$1`, `$2`, ... placeholders for values. |
| `params` | array of object | no | Values bound to the placeholders in order: strings, numbers, booleans or null; at most 1,000. Default empty. |
| _one of_ | | |  |
| _or_ | | |  |
| _or_ | | |  |
| _or_ | | |  |
| `limit` | integer | no | The most rows to return, 1 to 10,000; default 1,000. The statement runs as written; reading stops after `limit` rows, and `meta.truncated` says whether there were more. Applies to a collection query. |
| `timeoutSeconds` | integer | no | How long the statement may run, in seconds; default 60. The maximum is set by the deployment and is never above 300; a larger value is refused with 400 `K9O_INVALID_FIELD_VALUE`. A statement that runs longer is cancelled with 504 `K9O_QUERY_TIMEOUT`. Applies to a collection query. |

## Responses

- **200**: Success

| Field | Type | Required | Description |
|---|---|---|---|
| `data` | array of object | yes | The rows the statement returned, in the order it returned them. For a collection query, at most `limit` rows and at most the deployment's response-size cap of JSON; `meta.truncated` says whether rows were left out and `meta.truncatedBy` which cap stopped the read. |
| `meta` | object | yes | Request metadata (cost, timing, request and trace ids), plus `limit`, `truncated`, `truncatedBy` and `rawQuery`. |
| `meta.limit` | integer | no | The row limit applied. Present for a collection query. |
| `meta.truncated` | boolean | no | Whether the statement had more rows than `data` holds. Present for a collection query. |
| `meta.truncatedBy` | enum ("rows", "bytes") | no | Present only when `truncated` is true: `rows` when the read stopped at `limit` rows, `bytes` when it stopped at the response-size cap (the UTF-8 JSON size of the rows), whichever came first. Add a `LIMIT` or select fewer columns. |
| `meta.rawQuery` | object | no | Present for a collection query; absent for a dataset query. |
| `meta.rawQuery.intent` | enum ("read") | yes | The statement's classification. Only reads run here. |
| `meta.rawQuery.rowCount` | integer | yes | How many rows `data` holds. |


## Errors

| HTTP | Code | When |
|---|---|---|
| 401 | `K9O_SESSION_EXPIRED` | Your session has expired; sign in again to execute a query. |
| 401 | `K9O_INVALID_CREDENTIALS` | The credentials provided are not valid; the query request was rejected. |
| 403 | `K9O_ACCESS_DENIED` | Your role does not permit executing queries against this project. |
| 404 | `K9O_COLLECTION_NOT_FOUND` | A collection referenced in the query does not exist in this project. |
| 400 | `K9O_INVALID_FILTER` | The query contains a malformed or unsupported filter expression. |
| 400 | `K9O_INVALID_VECTOR_DIMENSION` | The embedding vector supplied for a vector search has a dimension that does not match the column's declared dimension. |
| 409 | `K9O_MULTIPLE_ROWS_RETURNED` | A single-row assertion in the query matched more than one row. |
| 422 | `K9O_CROSS_SHARD_TRANSACTION_UNSUPPORTED` | The query spans collections on multiple shards, which is not supported in a single transaction. |

## Code samples

### cURL

```bash
curl -X POST 'https://<org>.api-<region>.k9o.io/@storefront/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/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 query <sql|->
```

### @k9o/core

```typescript
// const k9o = new K9o({ orgSlug: 'playground', projectSlug: 'storefront', apiKey: 'k9o_…' })
const { data } = await k9o.query(k9o.sql`SELECT id, title FROM products WHERE id = ${'prod_demo00000001'}`)
```

### k9o

```python
# k9o = create_client(org_slug="playground", project_slug="storefront", api_key="k9o_…")
response = k9o.query(k9o.sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001"))
```

### sdk-go

```go
// ctx := context.Background()
// client, _ := k9o.NewClient(k9o.ClientOpts{OrgSlug: "playground", ProjectSlug: "storefront", APIKey: "k9o_…"})
data, _, kerr := client.Query(ctx, client.Sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001"))
```

### k9o

```rust
// let k9o = Client::new(ClientOpts { org_slug: "playground".into(), project_slug: "storefront".into(), api_key: "k9o_…".into() })?;
let resp = k9o.query(k9o.sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001")).await?
```

### dev.k9o:core

```java
// K9o k9o = K9o.createClient(K9o.Opts.builder().orgSlug("playground").projectSlug("storefront").apiKey("k9o_…").build());
var response = k9o.query(k9o.sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001"))
```

### K9o.Core

```c#
// var k9o = K9oClient.Create(new K9oOptions { OrgSlug = "playground", ProjectSlug = "storefront", ApiKey = "k9o_…" });
var response = await k9o.QueryAsync(k9o.Sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001"))
```

### k9o

```ruby
# k9o = K9o.create_client(org_slug: "playground", project_slug: "storefront", api_key: "k9o_…")
response = k9o.query(k9o.sql("SELECT id, title FROM products WHERE id = ", "prod_demo00000001"))
```

### k9o/sdk

```php
// $k9o = K9oClient::create(['org_slug' => 'playground', 'project_slug' => 'storefront', 'api_key' => 'k9o_…']);
$response = $k9o->query($k9o->sql('SELECT id, title FROM products WHERE id = ', 'prod_demo00000001'))
```


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