/betterstack:spans-queryfrom Better Stack
Provides the required SQL syntax and query patterns for querying Better Stack spans/traces. Must load before writing any span query to avoid failures.
Ships in Better Stack. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
These queries read raw events, so they run ad hoc through query and render_chart; dashboard charts only read the metrics collection (see dashboard-builder for log and span volumes there). Write them as this skill shows, with {{source}}, {{time}}, {{start_time}} and {{end_time}}, and pass source_id, source_type (logs, spans or web_events), start_time and end_time (now-3h, now-1d, or an ISO 8601 datetime) and no table; the tool builds the source's collections for {{source}} and resolves {{time}} to a bucket that suits the range. One change from the examples: filter time with dt >= {{start_time}} AND dt < {{end_time}}, not {{time}} BETWEEN {{start_time}} AND {{end_time}}, the dashboards' form, which drops the rows of the range's first partial bucket and which query cannot split.
First call query_help with the source ID for the syntax.
Add a LIMIT. A template that lists the newest rows (ORDER BY dt DESC LIMIT n, no aggregate, GROUP BY, DISTINCT or subquery), or one that only aggregates (count(), countIf(), sum(), sumIf(), min() or max() beside its GROUP BY columns, no HAVING, DISTINCT or subquery) over at most 300,000,000 rows, then needs one query call however wide its range: query reads the range in time windows itself, merges the rows and says how far it read. A query of any other shape whose range is too wide for one call, in query or render_chart, is refused without running, with the time windows that each fit, newest first: run it once per window, each as start_time and end_time, and merge the results: rows concatenate, count() and sum() add up, min() and max() combine, and an average needs sum() and count() per window. quantile() and uniq() don't merge, so narrow the range or the filters until one call holds them.
| Need | Pattern |
|---|---|
| Source | FROM {{source}} |
| Time filter | WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}} |
| Time bucket | {{time}} AS time |
| Service filter | <service expression> = 'service-name' |
| Group by service | <service expression> AS series |
| Extract field | JSONExtract(raw, 'span', 'field', 'Nullable(String)') |
| Trace ID | JSONExtractString(raw, 'span', 'trace_id') |
| Span ID | JSONExtractString(raw, 'span', 'span_id') |
| Duration (ns) | JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64') - JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64') |
raw Column (JSON)Spans follow OpenTelemetry format. All span fields are nested under raw.span, resource fields under raw.resource.
Enum values are stored as lowercase short names, not the proto constants: kind is server / client / internal / producer / consumer (never SPAN_KIND_SERVER), status.code is ok / error / unset.
-- Span fields (under "span" key)
JSONExtract(raw, 'span', 'trace_id', 'Nullable(String)') AS trace_id
JSONExtract(raw, 'span', 'span_id', 'Nullable(String)') AS span_id
JSONExtract(raw, 'span', 'parent_span_id', 'Nullable(String)') AS parent_span_id
JSONExtract(raw, 'span', 'name', 'Nullable(String)') AS span_name
JSONExtract(raw, 'span', 'kind', 'Nullable(String)') AS span_kind
JSONExtract(raw, 'span', 'root', 'Nullable(Boolean)') AS is_root
-- Duration (nanoseconds) - calculate from start/end
JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64') AS duration_ns
-- Duration in milliseconds
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000 AS duration_ms
-- Status
JSONExtract(raw, 'span', 'status', 'code', 'Nullable(String)') AS status_code
span.attributes)-- HTTP status
JSONExtract(raw, 'span', 'attributes', 'http.status_code', 'Nullable(Int64)') AS http_status
-- Or newer convention:
JSONExtract(raw, 'span', 'attributes', 'http.response.status_code', 'Nullable(Int64)') AS http_status
-- gRPC status
JSONExtract(raw, 'span', 'attributes', 'rpc.grpc.status_code', 'Nullable(Int64)') AS grpc_status
-- Database system
JSONExtractString(raw, 'span', 'attributes', 'db.system') AS db_type
-- Server address/port
JSONExtractString(raw, 'span', 'attributes', 'server.address') AS server_address
resource.attributes)-- Service name: the service name expression built from the source's service_fields (below), never a guessed path
-- Host
JSONExtractString(raw, 'resource', 'attributes', '_host') AS host
-- Kubernetes
JSONExtractString(raw, 'resource', 'attributes', 'k8s.namespace.name') AS namespace
JSONExtractString(raw, 'resource', 'attributes', 'k8s.pod.name') AS pod
Important: For service filtering/grouping, build the service name expression from the source tool's service_fields: one JSONExtractCaseInsensitive(raw, ...) per name_key (its dots separate keys, \. is a dot inside a key), inside COALESCE(...) in their order, such as COALESCE(JSONExtractCaseInsensitive(raw, 'resource', 'service.name', 'Nullable(String)')). Never guess service field paths.
{{source}} - table name (never hardcode){{time}} - time bucket column (NOT dt){{start_time}}, {{end_time}} - time range boundsThere is no service template variable: filter or group by service with the service name expression from the source tool.
A span is an error if ANY of these conditions is true:
JSONExtract(raw, 'span', 'status', 'code', 'Nullable(String)') = 'error'
OR JSONExtract(raw, 'span', 'attributes', 'http.status_code', 'Nullable(Int64)') >= 400
OR JSONExtract(raw, 'span', 'attributes', 'http.response.status_code', 'Nullable(Int64)') >= 400
OR JSONExtract(raw, 'span', 'attributes', 'rpc.grpc.status_code', 'Nullable(Int64)') > 0
Use COUNT, AVG, SUM - NOT avgMerge, countMerge (those are for pre-aggregated metrics).
Column aliases become chart legend labels. Use descriptive names.
raw LIKE PrefilterWhen filtering on one specific ID (trace_id, span_id, session ID), add a substring prefilter before the extraction:
AND raw LIKE '%YOUR_TRACE_ID%'
AND JSONExtractString(raw, 'span', 'trace_id') = 'YOUR_TRACE_ID'
The cheap LIKE scan skips JSON-parsing rows that can't match; keep the equality as the authoritative filter. LIKE is case-sensitive — use the ID verbatim.
Span count over time:
SELECT {{time}} AS time, COUNT(*) AS "Span count"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY time
ORDER BY time
Span count by service - series uses the service name expression from the source tool:
SELECT {{time}} AS time, <service name expression> AS series, COUNT(*) AS "Span count"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY time, series
ORDER BY time
Error rate (root spans only):
SELECT
{{time}} AS time,
countIf(
JSONExtract(raw, 'span', 'root', 'Nullable(Boolean)') = true AND (
JSONExtract(raw, 'span', 'status', 'code', 'Nullable(String)') = 'error'
OR JSONExtract(raw, 'span', 'attributes', 'http.status_code', 'Nullable(Int64)') >= 400
OR JSONExtract(raw, 'span', 'attributes', 'http.response.status_code', 'Nullable(Int64)') >= 400
)
) / countIf(JSONExtract(raw, 'span', 'root', 'Nullable(Boolean)') = true) AS "Error rate"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY time
ORDER BY time
Average duration by span name (top 10 slowest):
SELECT
JSONExtract(raw, 'span', 'name', 'Nullable(String)') AS span_name,
AVG(
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000
) AS "Avg duration (ms)",
COUNT(*) AS "Count"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY span_name
ORDER BY "Avg duration (ms)" DESC
LIMIT 10
P95 latency over time (root spans):
SELECT
{{time}} AS time,
quantile(0.95)(
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000
) AS "P95 latency (ms)"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
AND JSONExtract(raw, 'span', 'root', 'Nullable(Boolean)') = true
GROUP BY time
ORDER BY time
Find all spans for a trace:
SELECT
JSONExtract(raw, 'span', 'name', 'Nullable(String)') AS span_name,
JSONExtract(raw, 'span', 'span_id', 'Nullable(String)') AS span_id,
JSONExtract(raw, 'span', 'parent_span_id', 'Nullable(String)') AS parent_span_id,
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000 AS duration_ms,
JSONExtract(raw, 'span', 'status', 'code', 'Nullable(String)') AS status
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
AND raw LIKE '%YOUR_TRACE_ID%'
AND JSONExtractString(raw, 'span', 'trace_id') = 'YOUR_TRACE_ID'
ORDER BY dt, _insert_index
Slow database queries:
SELECT
JSONExtract(raw, 'span', 'name', 'Nullable(String)') AS operation,
JSONExtractString(raw, 'span', 'attributes', 'db.system') AS db_type,
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
- JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000 AS duration_ms
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
AND JSONExtractString(raw, 'span', 'attributes', 'db.system') != ''
ORDER BY duration_ms DESC
LIMIT 20
| Mistake | Fix |
|---|---|
JSONExtract(raw, 'trace_id', ...) | JSONExtract(raw, 'span', 'trace_id', ...) |
JSONExtract(raw, 'service.name', ...) | The service name expression built from the source tool's service_fields |
{{_service}} or a guessed field | Use the service name expression from the source tool |
duration column | Calculate: end_time_unix_nano - start_time_unix_nano |
WHERE dt BETWEEN | WHERE dt >= {{start_time}} AND dt < {{end_time}} |
'String' type | 'Nullable(String)' - prevents failures on missing fields |
| ID equality without a prefilter | Add raw LIKE '%<id>%' before the extraction (see rule 8) |
avgMerge(...) on spans | AVG(...) - spans are not pre-aggregated |
SELECT * for raw span data | Select specific columns: dt, _insert_index, raw |
kind = 'SPAN_KIND_SERVER' | Lowercase short names: kind = 'server', status.code = 'error' |
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub betterstackhq/claude-plugin --plugin betterstack17 skills in this plugin
/chart-alertsGuide for creating and managing Better Stack chart alerts. Load when asked to set up alerting, create alerts on charts, or configure monitoring thresholds./chart-generationComplete reference for chart types, units, and settings on Better Stack dashboards. Load right before creating charts - after the queries are built with the query skills./chart-stylingBetter Stack chart styling and advanced settings reference - series colors and order, number chart coloring thresholds, heatmap color categories, gauge bounds, y-axis tuning, custom units, and the per-key settings table with cross-setting gotchas. Load when configuring how a chart looks beyond defaults, or when unsure which settings key applies to a chart type.Other plugins' skills for the same job