Writing SQL queries
Create tailored charts by writing your own custom SQL queries.
Want a dashboard that works out of the box?
Use one of our ready-to-use templates to create a dashboard
Getting started
Create your first chart using a custom SQL query. Start by creating a dashboard in Dashboards → Create dashboard.
Create a new chart on your dashboard and use the query below:
Getting Missing columns error?
Try selecting a different source or add metric for the column to your source.
Dashboard queries use ClickHouse SQL, which is largely similar to ANSI SQL you’re likely familiar with.
Want an in-depth guide on ClickHouse aggregations?
Check out the official blog post about ClickHouse aggregate combinators
On top of SQL, dashboard queries feature variables like {{source}} or {{time}}. Variables conveniently insert selected source, current time range, and other selected values into your queries. Read more about query variables.
Queries access a unified row-based metrics schema. This schema stores all data in a unified format with metrics stored as named values with labels in a tags map. This allows for fast and efficient querying. Read more about querying the metrics below.
Not familiar with SQL?
Follow our examples below or start with SQL tutorial from W3Schools
Curious about ClickHouse SQL?
Read more about ClickHouse SQL syntax.
How to query the metrics?
We store all data in a unified format, making querying consistent.
- Accessing custom fields: All custom or dynamic columns like labels and tags use the
label()function. For example,response_statusbecomeslabel('response_status'). Labels are always strings, sotoString(label(...))is redundant. - Standard columns: Columns like
time,dt,name,series_id, andtagsare part of the schema and should not use thelabel()wrapper. - Event type specific counts: Each ingested event creates multiple rows. To count just the original events of a given kind, use the matching count column directly:
sum(logs_count),sum(spans_count),sum(exceptions_count),sum(replays_count),sum(web_events_count), orsum(metrics_count). Each is zero on rows of a different event type, so no explicit filter is needed. When querying named metrics withname = 'metric_name', don't filter by event type at all. The name predicate is enough. - Event counting: Use
countMerge(events_count)for a generic event count across all event types, or an event type specific count likesum(logs_count)to count a single event type. - Type handling for labels: Since
label()returns a string, explicit type conversions liketoUInt16OrNull()ortoFloat64OrNull()are required for numeric comparisons or operations. - No nested aggregate functions: ClickHouse does not allow nesting aggregate functions like
sum(countMerge(...)). Merge functionscountMerge,sumMerge,avgMerge, etc. already combine internal states. - Time filtering: Use
timeinWHEREclauses for accurate filtering across bucket boundaries, and{{time}}inSELECTandGROUP BYfor bucketing.
Want to count the number of log lines?
Use sum(logs_count). Use countMerge(events_count) only for a total count across all event types. Avoid using count(*) as it returns incorrect results. Metric tables don't have the same number of rows as the original log tables.
For metrics with aggregations, use avgMerge(value_avg) to get the average value of a metric.
Similarly, use minMerge(value_min) and maxMerge(value_max) to get a metric's minimum and maximum values.
Make sure to always match the -Merge function with the metric suffix correctly:
- ✅ Correct: Using sumMerge with _sum suffix:
sumMerge(bucket_sum) - ❌ Incorrect: Mixing sum and count:
sumMerge(bucket_count)
Want to use percentiles?
Check out the complete example on percentiles below.
Which metrics can you query?
We automatically create metrics for your logs based on the platform of your source.
Find the complete list of available metrics for your logs in Sources → your source → Configure → Extract metrics tab.
See Query with to know how to query the metric.
Use either ClickHouse aggregations or name of the metric depending on the configured aggregations.
You can add more metrics to use in your SQL queries.
Event type specific counts
Each event type has a dedicated count column. Summing it gives you the number of original events of that kind, with no extra filter needed:
metrics_count covers metrics sent to us directly. extracted_metrics_count covers metric rows we derived from logs, spans, and other events. Keeping the two distinct lets you query just the source-emitted metrics if you need to.
Query examples
See the examples below for full queries using Metrics.
Number of errors
Chart the number of logs with the error log level:
Use sum(logs_count) to count log events, or countMerge(events_count) to count events of all types. Avoid count(*).
Filter error log lines using the label('level') metric. The metric has to be present in Extract metrics configuration with No aggregation selected.
Average request duration
Chart the average duration of request:
Use avgMerge(value_avg) to calculate an average for the request_duration metric. The metric has to be added in Extract metrics → Metrics with avg aggregation.
The column name Request duration will be used in chart tooltips and the legend. Select which column should be charted on the Y-axis on the right side in Chart setting → Axes.
Percentile request duration
Chart the 95th percentile request duration:
Here we use the histogramQuantile(0.95) helper function to directly calculate the 95th percentile for the request_duration_seconds histogram metric. If querying multiple metrics, use quantilePrometheusHistogramArrayMergeIf as described in the schema migration guide.
Want to learn how to use the aggregation functions?
Check out the official guide on ClickHouse Aggregate Combinators
Prometheus-like metrics
Want to access metric labels?
Use label('tag_name') to get value for any metric tag. Use the resulting tag value to select, group by, or anywhere else in your SQL queries.
Metrics you send to Better Stack are processed like logs for fast and efficient querying. We process your metrics and store them as ClickHouse -State combinators.
Everything about querying the metrics written above also applies to writing queries for Prometheus-like metrics.
The most significant difference when writing queries for Prometheus-like metrics is the Extract metrics configuration. We automatically configure Metrics for your Prometheus-like metrics.
Let's take a look at the Extract metrics configuration for metric sources.
You can find it in Sources → your source → Configure → Extract metrics tab:
Value metric represents the immediate value of the metric. Use it with gauge metrics or anytime you want to chart the metric value directly.
Rate represents how much the metric value has increased per second. Common use for rates is to calculate the number of requests per second. Use rate with counter metrics.
What are gauges and counter metrics?
Gauge is a metric that can go up and down, used for, e.g., CPU or memory usage.
Counter is a metric that can only increase, commonly used for number of requests.
Read more about metric types
Tags contain all metric tags, commonly called labels. Use
label('tag_name')to get value for any tag. Use the resulting tag value to select, group by, or anywhere else in your SQL queries.Name is the name of your metric. Use it to select, filter, or anywhere else in your SQL queries.
Series_id is a unique value for each metric series. Use
GROUP BY series_idwhen aggregating your metrics.
What is a metric series?
Metric series represent individual series of values that make up your metric. For example, a metric with hostname tag will have one series for each hostname.
Examples with metrics
See complete SQL query examples using ClickHouse aggregator combinators and Prometheus-like metrics.
View Prometheus metrics
List your metrics with their tags and values as a Table chart type:
Select metric name, tags, and time. Use anyLastMerge(value_last) to get an unaggregated value for the metric.
Visualize the data using a Table chart type. In the right sidebar, choose Chart settings → Chart → Table.
CPU load
Chart CPU load using cpu_load gauge metric:
Select cpu_load metric by its name using WHERE name = 'cpu_load'.
Use maxMerge(value_max) to get the maximal CPU load in each time interval. Calculating maximum gives you an accurate visualization of CPU load peaks. Using avgMerge(value_avg) is a good alternative if you care about average values more than peaks.
Write a subquery to aggregate and use a second query to get the final result:
- Subquery calculates a maximum for each metric series. Using
GROUP BY series_idensures that you get a correct maximum for each series. - In the outer query, sum all metrics series together to get the final result.
Chart CPU for multiple servers by setting label('host') as series.
Number of requests
Chart the request rate or count using the requests_total counter metric:
Select requests_total metric using WHERE name = 'requests_total'.
Calculate the average request rate using avgMerge(rate_avg). The metric requests_total is a counter metric, and rate_avg is its average per-second increase, not the raw increment.
As in the previous example, aggregate first to get the average rate for each series with GROUP BY series_id, then SUM() the per-series rates in the outer query. Use SELECT 'Requests per second' as series to name the series shown in tooltips and the chart legend. Usually, you should avoid using value_* with counter metrics.
Counter rate is lower than expected, or below 1?
rate_avg is a per-second average, so a counter that goes up by 1 only every few seconds reads below 1. For example, 0.25 is one request every four seconds. This applies to every counter, including ones incremented via statsd.incr() and exported through OpenTelemetry.
To chart the raw number of requests in each time interval instead, multiply the summed rate by {{interval_seconds}}, the length in seconds of each {{time}} bucket. This converts the per-second rate back into the actual count over the sampled interval.
Number of running servers
Get the number of running servers by counting the number of values for hostname tag:
Select the up metric using WHERE name = 'up' to only get hostname values for running servers. You should always select metrics by name to prevent other metrics tags and values from causing inaccuracies in your chart. Selecting only the metrics you need will also make your queries faster.
Count the total number of unique values for the hostname tag using COUNT(DISTINCT label('hostname')).
Need help?
Please let us know at hello@betterstack.com.
We're happy to help! 🙏