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.

The query API accepts a Telemetry API token, a global API token or the OAuth access token of a signed-in user.

POST https://telemetry.betterstack.com/api/v2/query

Headers

Authorization
required string
Content-Type
required string

Body parameters

source_id
required integer
query
required string
source_type
string
start_time
string
end_time
string
limit
integer
200

Response 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\"}"
        }
      ]
    }
  }
}
401

Response 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"
}
403

Response 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."
}
404

Response body

{
  "errors": "Resource with the provided ID was not found"
}
422

Response body

{
  "errors": "Query execution failed: Query failed: DB::Exception: Unknown identifier: nope"
}
422

Response body

{
  "errors": "Sorry, some values are incorrect",
  "invalid_values": {
    "limit": "limit must be an integer between 1 and 1000."
  }
}

Response attributes

type
string
attributes.query
string
attributes.rows
array

Example cURL

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
  }'