> 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/api-reference/query.md).

# Query

Submit queries and fetch results. Raw SQL, Semantic REST, and Semantic SQL all share the same async submit → poll → fetch pattern. See [GraphQL](/references/interfaces/apis/api-reference/graphql.md) for the synchronous semantic query endpoint.

## Which Query Type Should I Use?

| Type             | When to use it                                                                                                      |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| Raw SQL          | You know physical table names and want full SQL control                                                             |
| Semantic REST    | Query by measure/dimension names without writing SQL — best for BI integrations                                     |
| Semantic SQL     | SQL syntax with semantic layer field names instead of physical columns                                              |
| Semantic GraphQL | Your frontend or tooling already uses GraphQL — see [GraphQL](/references/interfaces/apis/api-reference/graphql.md) |
| Metric endpoints | Query a named metric directly — simplest option for dashboards                                                      |

## Execution Strategies (Cache Behaviour)

| Strategy        | Meaning                                                      |
| --------------- | ------------------------------------------------------------ |
| `from_cache`    | Identical query ran before — result returned instantly       |
| `await_primary` | Same query is currently running — deduplicated, waits for it |
| `execute`       | New query — queued for background execution                  |

***

## Query Result

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

### GET /api/v1/query/statement/{id}

**Summary:** Poll statement status

**Description:** Poll until `status` is `SUCCESS` or `FAILED`. Check the `error` field on failure. An `Is-Stale: true` header means the model was updated after this result was cached.

**Status values:** `ACCEPTED` → `QUEUED` → `IN_PROGRESS` → `SUCCESS` / `FAILED`

**cURL:**

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

**Returns:** JSON with `id`, `status`, `strategy`, `fingerprint`, and `_links.result` when done.

***

## GET /api/v1/query/statement/{id}/result

**Summary:** Fetch result data

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

**Key query params:** `format` (json/csv/yaml/parquet), `limit`, `offset`, `columns`

**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`. For `parquet`: HTTP 307 redirect to presigned binary download URL.

***

### POST /api/v1/query/statement

**Summary:** Submit raw SQL

**Description:** Submit a raw SQL query against physical table names. Returns a `statement_id` immediately — poll status before fetching results.

**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 orders_analytics.users LIMIT 10"}'
```

**Returns:** HTTP 202 with `id` (statement\_id), `status`, `strategy`, `fingerprint`, and `_links` to poll and result endpoints.

***

## Semantic REST

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

### POST /api/v1/query/semantic/rest

**Summary:** Submit semantic REST query

**Description:** Query using measure and dimension names from the semantic layer. The API transpiles to SQL automatically. Use `Model.COLUMN` dot-notation.

**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": ["users.total_users"],
      "dimensions": ["users.country"],
      "limit": 1000
    }
  }'
```

**Returns:** HTTP 202 — same `StatementAccepted` format as raw SQL.

***

## Semantic SQL

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

### POST /api/v1/query/semantic/sql

**Summary:** Submit semantic SQL

**Description:** Write SQL using semantic layer field names instead of physical column names. The transpiler converts to executable SQL.

**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 country, total_users FROM users LIMIT 10"}'
```

**Returns:** HTTP 202 — same `StatementAccepted` format.

***

## Semantic Metrics

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

### GET /api/v1/query/metric/{metric\_name}

**Summary:** Query a named metric (simple)

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

**Key query params:** `dimensions`, `granularity`, `timezone`, `limit`

**cURL:**

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

**Returns:** HTTP 202 — `StatementAccepted` with an additional `cols_mapping` field mapping result columns to semantic roles (measure / time / dimension).

***

### POST /api/v1/query/metric/{metric\_name}

**Summary:** Query a named metric (with filters)

**Description:** Same as the GET endpoint but accepts a request body, which allows AND / OR filter expressions.

**cURL:**

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

**Returns:** HTTP 202 — same `StatementAccepted` format with `cols_mapping`.

***

## Usage Metrics

Query API usage analytics for the data product. Not part of the async statement execution flow.

### GET /api/v1/query/usage-metrics

**Summary:** Query usage analytics

**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:** `week_start` (Monday in YYYY-MM-DD format)

**cURL:**

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

**Returns:** JSON with usage stats for the requested week: active user count, new users, total queries run, median query time (ms), and cache hit rate / savings.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
