> For the complete documentation index, see [llms.txt](https://v2.dataos.info/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://v2.dataos.info/references/interfaces/apis/data-product-apis/api-reference/query.md).

# Query

API contracts for running analytical requests and working with their outputs.

Vulcan supports multiple query interfaces over the same Data Product. Choose the interface that matches how much abstraction your application needs.

Submit queries and fetch results. Raw SQL, Semantic REST, Semantic SQL, and Metric queries share the same async submit → poll → fetch pattern. See [GraphQL](https://v2.dataos.info/references/interfaces/apis/data-product-apis/api-reference/graphql.md) for the Semantic GraphQL interface.

Async query submissions return a statement `id`. Poll it through **Query Result**. The Postman collection saves the `id` as `statement_id` automatically.

## Which Query Type Should I Use?

| Type             | When to use it                                                                     |
| ---------------- | ---------------------------------------------------------------------------------- |
| Raw SQL          | You know the physical data model and need direct `SELECT` control.                 |
| Semantic REST    | Your application builds structured requests from governed measures and dimensions. |
| Semantic SQL     | You prefer SQL syntax while retaining semantic measures and dimensions.            |
| Semantic GraphQL | Your application uses GraphQL and needs an inline response.                        |
| Metric endpoints | You want to query one predefined metric with minimal request construction.         |

### Asynchronous query lifecycle

```
Submit query
   ↓ 202 Accepted + statement id
Poll GET /query/statement/{id}
   ↓ SUCCESS
Fetch GET /query/statement/{id}/result
```

**Statement status:** `ACCEPTED` → `QUEUED` → `IN_PROGRESS` → `SUCCESS`. A statement can also become `FAILED` or `CANCELLED`.

`202 Accepted` means the request was accepted, not that execution completed. Poll until the statement reaches `SUCCESS`, `FAILED`, or `CANCELLED`.

## Execution Strategies (Cache Behavior)

| Strategy        | Meaning                                                                     |
| --------------- | --------------------------------------------------------------------------- |
| `EXECUTE`       | A new warehouse query was queued.                                           |
| `AWAIT_PRIMARY` | An identical query is already running; this request follows that execution. |
| `REUSE_RESULT`  | A compatible successful result already exists and can be reused.            |

Semantic GraphQL normally waits and returns data inline. If processing exceeds its polling window, it can return `202` and ask the caller to retry.

***

## Query Result

Poll statement status and retrieve results after any async query submission.

### Poll statement status

**API endpoint:** GET /api/v1/query/statement/{id}

**Description:** Poll the status and metadata of an asynchronous query. Use the `Location` header or statement `id` returned by a submission endpoint. Poll until `status` is `SUCCESS`, `FAILED`, or `CANCELLED`. Check the `error` field on failure. An `Is-Stale: true` header means dependencies are not current.

**Path params:**

| Parameter | Description                                          |
| --------- | ---------------------------------------------------- |
| `id`      | Statement identifier returned by a query submission. |

**cURL:**

```bash
curl -s https://$BASE_URL/api/v1/query/statement/$STATEMENT_ID \
  -H "Authorization: Bearer $TOKEN"
```

**Example response:**

```json
{
  "id": "stmt_abc123",
  "status": "SUCCESS",
  "strategy": "EXECUTE",
  "fingerprint": "sha256:4a9c2e1f...",
  "is_stale": false,
  "_links": {
    "self": {
      "href": "/api/v1/query/statement/stmt_abc123"
    },
    "result": {
      "href": "/api/v1/query/statement/stmt_abc123/result"
    }
  }
}
```

**Returns:** `200 OK` with statement status, query type, execution strategy, timestamps, error information when failed, staleness information, and result links when available. `404 Not Found` means the statement does not exist.

***

### Fetch result data

**API endpoint:** GET /api/v1/query/statement/{id}/result

**Description:** Fetch result once status is `SUCCESS`. Parquet returns a `307` redirect to a presigned download URL.

**Path params:**

| Parameter | Description                                             |
| --------- | ------------------------------------------------------- |
| `id`      | Statement ID returned from a query submission endpoint. |

**Key query params:**

| Parameter | Default   | Description                                                      |
| --------- | --------- | ---------------------------------------------------------------- |
| `format`  | `parquet` | Response format: `parquet`, `json`, `yaml`, or `csv`.            |
| `limit`   | None      | Maximum rows to return for text formats. Must be `0` or greater. |
| `offset`  | `0`       | Number of rows to skip for text formats.                         |
| `columns` | None      | Comma-separated column names to include for text formats.        |

**cURL:**

```bash
# JSON format
curl -s "https://$BASE_URL/api/v1/query/statement/$STATEMENT_ID/result?format=json" \
  -H "Authorization: Bearer $TOKEN"

# Parquet (follow redirect)
curl -L -o result.parquet "https://$BASE_URL/api/v1/query/statement/$STATEMENT_ID/result?format=parquet" \
  -H "Authorization: Bearer $TOKEN"
```

**Returns:** For `json`: object with `cols[]`, `rows[][]`, `types[]`, `row_count`, `size_bytes`, `is_stale`, and `_links`. For `parquet`: HTTP 307 redirect to presigned binary download URL.

```json
{
  "cols": ["customer_id", "revenue"],
  "rows": [[101, 12500.5], [102, 8450.0]],
  "types": [
    { "name": "customer_id", "type": "INT" },
    { "name": "revenue", "type": "DOUBLE" }
  ],
  "row_count": 2,
  "size_bytes": 96,
  "is_stale": false,
  "_links": {
    "self": {
      "href": "/api/v1/query/statement/stmt_abc123/result"
    }
  }
}
```

Text formats return `200 OK`. Parquet returns `307 Temporary Redirect` with a presigned URL in `Location`; clients must follow redirects. `400 Bad Request` indicates an invalid column projection, `404 Not Found` means the result is unavailable, and `406 Not Acceptable` indicates an unsupported format.

For result sets over 50,000 records, see the [pagination recipe](https://v2.dataos.info/consume/recipes/retrieve-large-result-sets-with-pagination) in Consume: submit with `limit`/`offset`/`order` in the request body and page through with a constant `order`.

***

### Submit raw SQL

**API endpoint:** POST /api/v1/query/statement

**Description:** Submit a read-only SQL query against physical models in the active environment. Use this when semantic interfaces do not support the required analysis and the caller understands the physical schema. Only `SELECT` queries are accepted. Access policies apply before execution.

**Key query params:** `retry_on_recent_failure` (default `false`): retry even if an identical query failed recently, instead of getting the cached failure back.

**Request body:**

```json
{
  "sql": "SELECT * FROM retail.sales.orders_enriched LIMIT 1"
}
```

**cURL:**

```bash
curl -s -X POST https://$BASE_URL/api/v1/query/statement \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"sql": "SELECT * FROM retail.orders_enriched LIMIT 10"}'
```

**Returns:** `202 Accepted` with the statement ID and a `Location` header pointing to its status endpoint. Invalid, unsafe, or unauthorized SQL returns `400 Bad Request`. Invalid request bodies return `422 Unprocessable Entity`.

***

## Semantic REST

Submit semantic REST queries (measures, dimensions, filters). See **Query Result** above for submit, poll, and fetch.

### Submit semantic REST query

**API endpoint:** POST /api/v1/query/semantic/rest

**Description:** Query governed measures and dimensions using a structured JSON body. This is the recommended interface for query builders and BI-style applications that should not construct warehouse SQL.

**Key query params:**

* `retry_on_recent_failure` (default `false`): retry even if an identical query failed recently.
* `transpile_only` (default `false`, truthy values: `true`): return the generated warehouse SQL instead of executing the query; no statement is created. See the [transpile-only recipe](https://v2.dataos.info/consume/recipes/transpile-semantic-queries-to-native-warehouse-sql) in Consume.

**Request body:**

```json
{
  "query": {
    "measures": ["customer.ACTIVE_CUSTOMERS"],
    "dimensions": ["customer.FULL_NAME"],
      "timeDimensions": [
        {
          "dimension": "customer.CREATED_AT",
          "granularity": "month"
        }
      ],
      "filters": [],
    "limit": 10,
    "timezone": "UTC"
  }
}
```

**cURL:**

```bash
curl -s -X POST https://$BASE_URL/api/v1/query/semantic/rest \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": {
      "measures": ["orders.total_units"],
      "dimensions": ["orders.store_region"],
      "limit": 1000
    }
  }'
```

**Returns:** Normally `202 Accepted` with a statement `id`, `status`, execution `strategy`, staleness information, and links. With `transpile_only=true`, returns `200 OK` with generated SQL and creates no statement. Invalid semantic requests return `400 Bad Request`; transpiler failures return `502` or `503`.

***

## Semantic SQL

Submit SQL that references semantic measures and dimensions. See **Query Result** above for submit, poll, and fetch.

### Submit semantic SQL

**API endpoint:** POST /api/v1/query/semantic/sql

**Description:** Write SQL against semantic model fields and governed measures. Use this when analysts prefer SQL but should remain on the semantic contract instead of physical tables.

**Key query params:**

* `retry_on_recent_failure` (default `false`): retry even if an identical query failed recently.
* `transpile_only` (default `false`, truthy values: `true`): return the generated warehouse SQL instead of executing the query; no statement is created. See the [transpile-only recipe](https://v2.dataos.info/consume/recipes/transpile-semantic-queries-to-native-warehouse-sql) in Consume.

**Request body:**

```json
{
  "sql": "SELECT customer.FULL_NAME, MEASURE(customer.ACTIVE_CUSTOMERS) FROM customer GROUP BY customer.FULL_NAME LIMIT 10"
}
```

**cURL:**

```bash
curl -s -X POST https://$BASE_URL/api/v1/query/semantic/sql \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"sql": "SELECT orders.store_region, MEASURE(orders.total_units) FROM orders GROUP BY orders.store_region LIMIT 10"}'
```

**Returns:** `202 Accepted` with a statement reference, or `200 OK` with compiled warehouse SQL when `transpile_only=true`. Invalid semantic SQL returns `400 Bad Request`; transpiler failures return `502` or `503`.

***

## Semantic Metrics

Shorthand for named metric queries. Translates to semantic REST internally. See **Query Result** above for submit, poll, and fetch.

### Query a named metric (simple)

**API endpoint:** GET /api/v1/query/metric/{metric\_name}

**Description:** Simplest way to query a metric. Discover metric names from `GET /metadata/semantic`. Slice by dimensions or time granularity via query params.

**Path params:**

| Parameter     | Description                                                       |
| ------------- | ----------------------------------------------------------------- |
| `metric_name` | Metric name from catalog metadata, for example `CUSTOMER_GROWTH`. |

**Key query params:**

| Parameter     | Default        | Description                                                                                        |
| ------------- | -------------- | -------------------------------------------------------------------------------------------------- |
| `dimensions`  | None           | Comma-separated dimension aliases defined on the metric.                                           |
| `granularity` | Metric default | Time-series granularity: `second`, `minute`, `hour`, `day`, `week`, `month`, `quarter`, or `year`. |
| `timezone`    | `UTC`          | Timezone for time dimensions.                                                                      |
| `limit`       | `10000`        | Maximum rows to return. Range: `1`–`50000`.                                                        |
| `offset`      | `0`            | Number of rows to skip.                                                                            |

**cURL:**

```bash
curl -s "https://$BASE_URL/api/v1/query/metric/store_revenue?granularity=month&limit=1000" \
  -H "Authorization: Bearer $TOKEN"
```

**Returns:** `202 Accepted` with a statement reference. Returns `404 Not Found` when the metric does not exist, `400 Bad Request` for an invalid metric query, and `502 Bad Gateway` for a transpiler failure.

***

### Query a named metric (with filters)

**API endpoint:** POST /api/v1/query/metric/{metric\_name}

**Description:** Query one predefined metric using a request body. Use this variant when dimensions, ordering, or compound filters are required.

**Path params:**

| Parameter     | Description                                                       |
| ------------- | ----------------------------------------------------------------- |
| `metric_name` | Metric name from catalog metadata, for example `CUSTOMER_GROWTH`. |

**Request body:**

```json
{
  "dimensions": ["store_region"],
  "granularity": "month",
  "filters": [
    {
      "member": "sales_channel",
      "operator": "equals",
      "values": ["web"]
    }
  ],
  "order": [["order_date", "desc"]],
  "timezone": "UTC",
  "limit": 1000,
  "offset": 0
}
```

**cURL:**

```bash
curl -s -X POST https://$BASE_URL/api/v1/query/metric/store_revenue \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "dimensions": ["product_category"],
    "granularity": "month",
    "filters": [{ "member": "sales_channel", "operator": "equals", "values": ["web"] }],
    "limit": 1000
  }'
```

**Returns:** `202 Accepted` with a statement reference. Error behavior matches the GET metric endpoint.

***

## Usage Metrics

Query API usage analytics for the Data Product. Not part of the async statement execution flow.

### Query usage analytics

**API endpoint:** GET /api/v1/query/usage-metrics

**Description:** Weekly usage stats: active users, new users, total queries, median execution time, and cache hit savings. Defaults to the current week.

**Key query params:**

| Parameter    | Default      | Description                                                  |
| ------------ | ------------ | ------------------------------------------------------------ |
| `week_start` | Current week | Monday of the target week in UTC, formatted as `YYYY-MM-DD`. |

**cURL:**

```bash
curl -s "https://$BASE_URL/api/v1/query/usage-metrics?week_start=2026-09-14" \
  -H "Authorization: Bearer $TOKEN"
```

**Returns:** `200 OK` with active users, new users, total queries, median execution time, and cache-reuse savings for the requested week. Returns `400 Bad Request` for an invalid date and `501 Not Implemented` when the configured state backend does not support usage metrics.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://v2.dataos.info/references/interfaces/apis/data-product-apis/api-reference/query.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
