# Run a SQL query

Runs a SQL query over a source's logs, spans or metrics and returns the resulting rows. Write the query as a template, with `{{source}}` in place of a table name, as in [dashboard SQL queries](https://betterstack.com/docs/logs/dashboards/sql-queries/).

The query API accepts a [Telemetry API token](https://betterstack.com/docs/logs/api/getting-started/#get-a-telemetry-api-token), a [global API token](https://betterstack.com/docs/logs/api/getting-started/#get-a-global-api-token) or the OAuth access token of a signed-in user.

[endpoint]
base_url = "https://telemetry.betterstack.com"
path = "/api/v2/query"
method = "POST"

[[body_param]]
name = "source_id"
description = "The ID of the source to query. For an application inside a collector, only that application's rows are returned."
required = true
type = "integer"

[[body_param]]
name = "query"
description = "The SQL query to run. `{{source}}` reads the source's data of the chosen `source_type`. `{{start_time}}` and `{{end_time}}` stand for the time range, and `{{time}}` buckets `dt` into intervals that suit the range."
required = true
type = "string"

[[body_param]]
name = "source_type"
description = "Which data `{{source}}` reads: `logs`, `spans` or `metrics`. Defaults to the source's own type, or `logs`."
required = false
type = "string"

[[body_param]]
name = "start_time"
description = "The start of the time range, as an ISO 8601 timestamp like `2026-11-16T09:00:00Z` or a relative time like `now-3h`. Defaults to `now-1h`."
required = false
type = "string"

[[body_param]]
name = "end_time"
description = "The end of the time range, in the same formats as `start_time`. Defaults to `now`."
required = false
type = "string"

[[body_param]]
name = "limit"
description = "The maximum number of rows to return, from `1` to `1000`. Defaults to `500`. Applied only when the query has neither `LIMIT` nor `GROUP BY`, and never to metrics."
required = false
type = "integer"

[[header]]
name = "Authorization"
description = "Bearer `$TOKEN`"
required = true
type = "string"

[[header]]
name = "Content-Type"
description = "application/json"
required = true
type = "string"
[/endpoint]

[responses]
[[response]]
status = 200
description = '''Returns the rows of the query, and the query as you sent it.'''
body = '''{
  "data": {
    "type": "query_result",
    "attributes": {
      "query": "SELECT dt, raw FROM {{source}} WHERE dt >= {{start_time}} AND dt < {{end_time}} ORDER BY dt DESC",
      "rows": [
        {
          "dt": "2026-11-16T10:00:01Z",
          "raw": "{\"message\":\"Payment accepted\",\"level\":\"info\"}"
        },
        {
          "dt": "2026-11-16T10:00:00Z",
          "raw": "{\"message\":\"Payment requested\",\"level\":\"info\"}"
        }
      ]
    }
  }
}'''

[[response]]
status = 401
description = '''Authentication failed due to a missing or invalid token.'''
body = '''{
  "errors": "Invalid Team API token. How to find your Team API token: https://betterstack.com/docs/logs/api/getting-started/#obtaining-a-logtail-api-token"
}'''

[[response]]
status = 403
description = '''The user's role can't view Live tail in the team.'''
body = '''{
  "errors": "You don't have permission to view live tail in this team. Your Better Stack role restricts this action. Ask an organization admin to update your role's permissions."
}'''

[[response]]
status = 404
description = '''No source with this ID is available to your token.'''
body = '''{
  "errors": "Resource with the provided ID was not found"
}'''

[[response]]
status = 422
description = '''Returned when the query fails, with the error from the database.'''
body = '''{
  "errors": "Query execution failed: Query failed: DB::Exception: Unknown identifier: nope"
}'''

[[response]]
status = 422
description = '''Returned for an invalid value. A missing `source_id` or `query` returns `required_attributes`, and an unsupported attribute returns `invalid_attributes` instead.'''
body = '''{
  "errors": "Sorry, some values are incorrect",
  "invalid_values": {
    "limit": "limit must be an integer between 1 and 1000."
  }
}'''
[/responses]

[params]
title = "Response attributes"

[[param]]
name = "type"
type = "string"
description = "Always `query_result`."

[[param]]
name = "attributes.query"
type = "string"
description = "The query as you sent it, before the template variables are filled in."

[[param]]
name = "attributes.rows"
type = "array"
description = "The rows the query returned, each an object keyed by column name."
[/params]

#### Example cURL

```shell
[label Example]
curl --request POST \
  --url https://telemetry.betterstack.com/api/v2/query \
  --header "Authorization: Bearer $TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "source_id": 123456,
    "query": "SELECT dt, raw FROM {{source}} WHERE dt >= {{start_time}} AND dt < {{end_time}} ORDER BY dt DESC",
    "source_type": "logs",
    "start_time": "now-3h",
    "limit": 100
  }'
```
