> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Using the Query builder in the ClickHouse Grafana plugin

# Query builder

export const ClickHouseSupportedBadge = () => {
  return <div className="ClickHouseSupportedBadge">
            <div className="ClickHouseSupportedIcon">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1.30762 1.39073C1.30762 1.3103 1.37465 1.22986 1.46849 1.22986H2.64824C2.72868 1.22986 2.80912 1.29689 2.80912 1.39073V14.4886C2.80912 14.5691 2.74209 14.6495 2.64824 14.6495H1.46849C1.38805 14.6495 1.30762 14.5825 1.30762 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M4.2832 1.39073C4.2832 1.3103 4.35023 1.22986 4.44408 1.22986H5.62383C5.70427 1.22986 5.7847 1.29689 5.7847 1.39073V14.4886C5.7847 14.5691 5.71767 14.6495 5.62383 14.6495H4.44408C4.36364 14.6495 4.2832 14.5825 4.2832 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M7.25977 1.39073C7.25977 1.3103 7.3268 1.22986 7.42064 1.22986H8.60039C8.68083 1.22986 8.76127 1.29689 8.76127 1.39073V14.4886C8.76127 14.5691 8.69423 14.6495 8.60039 14.6495H7.42064C7.3402 14.6495 7.25977 14.5825 7.25977 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M10.2354 1.39073C10.2354 1.3103 10.3024 1.22986 10.3962 1.22986H11.576C11.6564 1.22986 11.7369 1.29689 11.7369 1.39073V14.4886C11.7369 14.5691 11.6698 14.6495 11.576 14.6495H10.3962C10.3158 14.6495 10.2354 14.5825 10.2354 14.4886V1.39073Z" fill="currentColor" />
                    <path d="M13.2256 6.6057C13.2256 6.52526 13.2926 6.44482 13.3865 6.44482H14.5662C14.6466 6.44482 14.7271 6.51186 14.7271 6.6057V9.27354C14.7271 9.35398 14.6601 9.43442 14.5662 9.43442H13.3865C13.306 9.43442 13.2256 9.36739 13.2256 9.27354V6.6057Z" fill="currentColor" />
                </svg>
            </div>
            ClickHouse Supported
        </div>;
};

export const Image = ({img, alt, size}) => {
  return <Frame>
      <img src={img} alt={alt} />
    </Frame>;
};

Any query can be run with the ClickHouse plugin.
The query builder is a convenient option for simpler queries, but for complicated queries you will need to use the [SQL Editor](#sql-editor).

All queries in the query builder have a [query type](#query-types), and require at least one column to be selected.

The available query types are:

* [Table](#table): the simplest query type for showing data in table format. Works well as a catch-all for both simple and complex queries containing aggregate functions.
* [Logs](#logs): optimized for building queries for logs. Works best in explore view with [defaults configured](/integrations/connectors/data-visualization/grafana/config#logs).
* [Time Series](#time-series): best used for building time series queries. Allows selecting a dedicated time column and adding aggregate functions.
* [Traces](#traces): optimized for searching/viewing traces. Works best in explore view with [defaults configured](/integrations/connectors/data-visualization/grafana/config#traces).
* [SQL Editor](#sql-editor): the SQL Editor can be used when you want full control over the query. In this mode, any SQL query can be executed.

<h2 id="query-types">
  Query types
</h2>

The *Query Type* setting will change the layout of the query builder to match the type of query being built.
The query type also determines which panel is used when visualizing data.

<h3 id="table">
  Table
</h3>

The most flexible query type is the table query. This is a catch-all for the other query builders designed to handle simple and aggregate queries.

| Field        | Description                                                                                                                                                                                           |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Builder Mode | Simple queries exclude Aggregates and Group By, while aggregate queries include these options.                                                                                                        |
| Columns      | The selected columns. Raw SQL can be typed into this field to allow for functions and column aliasing.                                                                                                |
| Aggregates   | A list of [aggregate functions](/reference/functions/aggregate-functions/index). Allows for custom values for function and column. Only visible in Aggregate mode.                                    |
| Group By     | A list of [GROUP BY](/reference/statements/select/group-by) expressions. Only visible in Aggregate mode.                                                                                              |
| Order By     | A list of [ORDER BY](/reference/statements/select/order-by) expressions.                                                                                                                              |
| Limit        | Appends a [LIMIT](/reference/statements/select/limit) statement to the end of the query. If set to `0` then it will be excluded. Some visualizations might need this set to `0` to show all the data. |
| Filters      | A list of filters to be applied in the `WHERE` clause.                                                                                                                                                |

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/ujc-kN615--sFi3M/images/integrations/data-visualization/grafana/demo_table_query.png?fit=max&auto=format&n=ujc-kN615--sFi3M&q=85&s=7dcb2d45c406bd9117d0f29c9edfd634" alt="Example aggregate table query" border width="1246" height="956" data-path="images/integrations/data-visualization/grafana/demo_table_query.png" />

This query type will render the data as a table.

<h3 id="logs">
  Logs
</h3>

The logs query type offers a query builder focused on querying logs data.
Defaults can be configured in the data source's [log configuration](/integrations/connectors/data-visualization/grafana/config#logs) to allow the query builder to be pre-loaded with a default database/table and columns.
OpenTelemetry can also be enabled to auto select the columns according to a schema version.

**Time** and **Level** filters are added by default, along with an Order By for the Time column.
These filters are tied to their respective fields, and will update as the columns are changed.
The **Level** filter is excluded from the SQL by default, changing it from the `IS ANYTHING` option will enable it.

The logs query type supports [data links](#data-links).

| Field          | Description                                                                                                                                                                         |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Use OTel       | Enables OpenTelemetry columns. Will overwrite the selected columns to use columns defined by the selected OTel schema version (Disables column selection).                          |
| Columns        | Extra columns to be added to the log rows. Raw SQL can be typed into this field to allow for functions and column aliasing.                                                         |
| Time           | The primary timestamp column for the log. Will display time-like types, but allows for custom values/functions.                                                                     |
| Log Level      | Optional. The *level* or *severity* of the log. Values typically look like `INFO`, `error`, `Debug`, etc.                                                                           |
| Message        | The log message content.                                                                                                                                                            |
| Order By       | A list of [ORDER BY](/reference/statements/select/order-by) expressions.                                                                                                            |
| Limit          | Appends a [LIMIT](/reference/statements/select/limit) statement to the end of the query. If set to `0` then it will be excluded, but this isn't recommended for large log datasets. |
| Filters        | A list of filters to be applied in the `WHERE` clause.                                                                                                                              |
| Message Filter | A text input for conveniently filtering logs using a `LIKE %value%`. Excluded when input is empty.                                                                                  |

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/4Hi2sd8mn4aAdMgN/images/integrations/data-visualization/grafana/demo_logs_query.png?fit=max&auto=format&n=4Hi2sd8mn4aAdMgN&q=85&s=5093b03e9e718832a8171169a8e75f2f" alt="Example OTel logs query" border width="1246" height="1123" data-path="images/integrations/data-visualization/grafana/demo_logs_query.png" />

<br />

This query type will render the data in the logs panel along with a logs histogram panel at the top.

Extra columns that are selected in the query can be viewed in the expanded log row:

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/4Hi2sd8mn4aAdMgN/images/integrations/data-visualization/grafana/demo_logs_query_fields.png?fit=max&auto=format&n=4Hi2sd8mn4aAdMgN&q=85&s=e15016f600a98dd695a80b1595facf4a" alt="Example of extra fields on logs query" border width="824" height="204" data-path="images/integrations/data-visualization/grafana/demo_logs_query_fields.png" />

<h3 id="time-series">
  Time series
</h3>

The time series query type is similar to [table](#table), but with a focus on time series data.

The two views are mostly the same, with these notable differences:

* A dedicated *Time* field.
* In Aggregate mode, a time interval macro is automatically applied along with a Group By for the Time field.
* In Aggregate mode, the "Columns" field is hidden.
* A time range filter and Order By are automatically added for the **Time** field.

<Warning>
  **Is your visualization missing data?**

  In some cases the time series panel will appear to be cut off because the limit defaults to `1000`.

  Try removing the `LIMIT` clause by setting it to `0` (if your dataset allows).
</Warning>

| Field        | Description                                                                                                                                                                                                                 |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Builder Mode | Simple queries exclude Aggregates and Group By, while aggregate queries include these options.                                                                                                                              |
| Time         | The primary time column for the query. Will display time-like types, but allows for custom values/functions.                                                                                                                |
| Columns      | The selected columns. Raw SQL can be typed into this field to allow for functions and column aliasing. Only visible in Simple mode.                                                                                         |
| Aggregates   | A list of [aggregate functions](/reference/functions/aggregate-functions/index). Allows for custom values for function and column. Only visible in Aggregate mode.                                                          |
| Group By     | A list of [GROUP BY](/reference/statements/select/group-by) expressions. Only visible in Aggregate mode.                                                                                                                    |
| Order By     | A list of [ORDER BY](/reference/statements/select/order-by) expressions.                                                                                                                                                    |
| Limit        | Appends a [LIMIT](/reference/statements/select/limit) statement to the end of the query. If set to `0` then it will be excluded, this is recommended for some time series datasets in order to show the full visualization. |
| Filters      | A list of filters to be applied in the `WHERE` clause.                                                                                                                                                                      |

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/ujc-kN615--sFi3M/images/integrations/data-visualization/grafana/demo_time_series_query.png?fit=max&auto=format&n=ujc-kN615--sFi3M&q=85&s=887272fea50f6a00e8a504ba002e9beb" alt="Example time series query" border width="1246" height="1008" data-path="images/integrations/data-visualization/grafana/demo_time_series_query.png" />

This query type will render the data with the time series panel.

<h3 id="traces">
  Traces
</h3>

The trace query type offers a query builder for easily searching and viewing traces.
It is designed for OpenTelemetry data, but columns can be selected to render traces from a different schema.
Defaults can be configured in the data source's [trace configuration](/integrations/connectors/data-visualization/grafana/config#traces) to allow the query builder to be pre-loaded with a default database/table and columns. If defaults are configured, the column selection will be collapsed by default.
OpenTelemetry can also be enabled to auto select the columns according to a schema version.

Default filters are added with the intent to show only top level spans.
An Order By for the Time and Duration Time columns is also included.
These filters are tied to their respective fields, and will update as the columns are changed.
The **Service Name** filter is excluded from the SQL by default, changing it from the `IS ANYTHING` option will enable it.

The trace query type supports [data links](#data-links).

| Field                 | Description                                                                                                                                                                           |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Trace Mode            | Changes the query from Trace Search to Trace ID lookup.                                                                                                                               |
| Use OTel              | Enables OpenTelemetry columns. Will overwrite the selected columns to use columns defined by the selected OTel schema version (Disables column selection).                            |
| Trace ID Column       | The trace's ID.                                                                                                                                                                       |
| Span ID Column        | Span ID.                                                                                                                                                                              |
| Parent Span ID Column | Parent span ID. This is usually empty for top level traces.                                                                                                                           |
| Service Name Column   | Service name.                                                                                                                                                                         |
| Operation Name Column | Operation name.                                                                                                                                                                       |
| Start Time Column     | The primary time column for the trace span. The time when the span started.                                                                                                           |
| Duration Time Column  | The duration of the span. By default Grafana expects this to be a float in milliseconds. A conversion is automatically applied via the `Duration Unit` dropdown.                      |
| Duration Unit         | The unit of time used for the duration. Nanoseconds by default. The selected unit will be converted to a float in milliseconds as required by Grafana.                                |
| Tags Column           | Span Tags. Exclude this if not using an OTel based schema as it expects a specific Map column type.                                                                                   |
| Service Tags Column   | Service Tags. Exclude this if not using an OTel based schema as it expects a specific Map column type.                                                                                |
| Order By              | A list of [ORDER BY](/reference/statements/select/order-by) expressions.                                                                                                              |
| Limit                 | Appends a [LIMIT](/reference/statements/select/limit) statement to the end of the query. If set to `0` then it will be excluded, but this isn't recommended for large trace datasets. |
| Filters               | A list of filters to be applied in the `WHERE` clause.                                                                                                                                |
| Trace ID              | The Trace ID to filter by. Only used in Trace ID mode, and when opening a trace ID [data link](#data-links).                                                                          |

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/ujc-kN615--sFi3M/images/integrations/data-visualization/grafana/demo_trace_query.png?fit=max&auto=format&n=ujc-kN615--sFi3M&q=85&s=6674b15e9474559759363299c6ba20c9" alt="Example OTel trace query" border width="2112" height="1078" data-path="images/integrations/data-visualization/grafana/demo_trace_query.png" />

This query type will render the data with the table view for Trace Search mode, and the trace panel for Trace ID mode.

<h2 id="sql-editor">
  SQL editor
</h2>

For queries that are too complex for the query builder, you can use the SQL Editor.
This gives you full control over the query by allowing you to write and run plain ClickHouse SQL.

The SQL editor can be opened by selecting "SQL Editor" at the top of the query editor.

[Macro functions](#macros) can still be used in this mode.

You can switch between query types to get a visualization that best fits your query.
This switch also has an effect even in dashboard view, notably with time series data.

<Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/4Hi2sd8mn4aAdMgN/images/integrations/data-visualization/grafana/demo_raw_sql_query.png?fit=max&auto=format&n=4Hi2sd8mn4aAdMgN&q=85&s=7b888920ebac3ea143092d7ba8b02a6c" alt="Example raw SQL query" border width="1185" height="729" data-path="images/integrations/data-visualization/grafana/demo_raw_sql_query.png" />

<h2 id="data-links">
  Data links
</h2>

Grafana [data links](https://grafana.com/docs/grafana/latest/panels-visualizations/configure-data-links)
can be used to link to new queries.
This feature has been enabled within the ClickHouse plugin for linking a trace to logs and vice versa. It works best with OpenTelemetry configured for both logs and traces in the [data source's config](/integrations/connectors/data-visualization/grafana/config#opentelemetry)

<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between', marginBottom: '15px' }}>
  Example of trace links in a table

  <Image size="sm" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/ujc-kN615--sFi3M/images/integrations/data-visualization/grafana/trace_id_in_table.png?fit=max&auto=format&n=ujc-kN615--sFi3M&q=85&s=eb8bdbb7eec86c1ab70c0d5ceb45488a" alt="Trace links in table" border width="339" height="148" data-path="images/integrations/data-visualization/grafana/trace_id_in_table.png" />
</div>

<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' }}>
  Example of trace links in logs

  <Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/ujc-kN615--sFi3M/images/integrations/data-visualization/grafana/trace_id_in_logs.png?fit=max&auto=format&n=ujc-kN615--sFi3M&q=85&s=59e8d902cae77b999c490b07c46ae8d4" alt="Trace links in logs" border width="743" height="58" data-path="images/integrations/data-visualization/grafana/trace_id_in_logs.png" />
</div>

<h3 id="how-to-make-a-data-link">
  How to make a data link
</h3>

You can make a data link by selecting a column named `traceID` in your query. This name is case insensitive, and supports adding an underscore before the "ID". For example: `traceId`, `TraceId`, `TRACE_ID`, and `tracE_iD` would all be valid.

If OpenTelemetry is enabled in a [log](#logs) or [trace](#traces) query, a trace ID column will be included automatically.

By including a trace ID column, the "**View Trace**" and "**View Logs**" links will be attached to the data.

<h3 id="linking-abilities">
  Linking abilities
</h3>

With the data links present, you can open traces and logs using the provided trace ID.

"**View Trace**" will open a split panel with the trace, and "**View Logs**" will open a logs query filtered by the trace ID.
If the link is clicked from a dashboard instead of the explore view, the link will be opened in a new tab in the explore view.

Having defaults configured for both [logs](/integrations/connectors/data-visualization/grafana/config#logs) and [traces](/integrations/connectors/data-visualization/grafana/config#traces) is required when crossing query types (logs to traces and traces to logs). Defaults aren't required when opening a link of the same query type since the query can be simply copied.

<div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' }}>
  Example of viewing a trace (right panel) from a logs query (left panel)

  <Image size="md" img="https://mintcdn.com/private-7c7dfe99-fix-nav-issues/4Hi2sd8mn4aAdMgN/images/integrations/data-visualization/grafana/demo_data_links.png?fit=max&auto=format&n=4Hi2sd8mn4aAdMgN&q=85&s=441535b26ce87fabd3c7098440545bf1" alt="Example of data links linking" border width="2138" height="1100" data-path="images/integrations/data-visualization/grafana/demo_data_links.png" />
</div>

<h2 id="macros">
  Macros
</h2>

Macros are a simple way to add dynamic SQL to your query.
Before a query gets sent to the ClickHouse server, the plugin will expand the macro and replace it will the full expression.

Queries from both the SQL Editor and Query Builder can use macros.

<h3 id="using-macros">
  Using macros
</h3>

Macros can be included anywhere in the query, multiple times if needed.

Here is an example of using the `$__timeFilter` macro:

Input:

```sql theme={null}
SELECT log_time, log_message
FROM logs
WHERE $__timeFilter(log_time)
```

Final query output:

```sql theme={null}
SELECT log_time, log_message
FROM logs
WHERE log_time >= toDateTime(1415792726) AND log_time <= toDateTime(1447328726)
```

In this example, the Grafana dashboard's time range is applied to the `log_time` column.

The plugin also supports notation using braces `{}`. Use this notation when queries are needed inside [parameters](/reference/syntax#defining-and-using-query-parameters).

<h3 id="list-of-macros">
  List of macros
</h3>

This is a list of all macros available in the plugin:

| Macro                                        | Description                                                                                                                                                                        | Output example                                                                                                    |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `$__dateFilter(columnName)`                  | Replaced by a time range filter on the provided column using the Grafana panel's time range as a [Date](/reference/data-types/date).                                               | `columnName >= toDate('2022-10-21') AND columnName <= toDate('2022-10-23')`                                       |
| `$__timeFilter(columnName)`                  | Replaced by a time range filter on the provided column using the Grafana panel's time range as a [DateTime](/reference/data-types/datetime).                                       | `columnName >= toDateTime(1415792726) AND time <= toDateTime(1447328726)`                                         |
| `$__timeFilter_ms(columnName)`               | Replaced by a time range filter on the provided column using the Grafana panel's time range as a [DateTime64](/reference/data-types/datetime64).                                   | `columnName >= fromUnixTimestamp64Milli(1415792726123) AND columnName <= fromUnixTimestamp64Milli(1447328726456)` |
| `$__dateTimeFilter(dateColumn, timeColumn)`  | Shorthand that combines `$__dateFilter()` and `$__timeFilter()` using separate Date and DateTime columns. Alias `$__dt()`                                                          | `$__dateFilter(dateColumn) AND $__timeFilter(timeColumn)`                                                         |
| `$__fromTime`                                | Replaced by the starting time of the Grafana panel range cast to a [DateTime](/reference/data-types/datetime).                                                                     | `toDateTime(1415792726)`                                                                                          |
| `$__fromTime_ms`                             | Replaced by the starting time of the panel range cast to a [DateTime64](/reference/data-types/datetime64).                                                                         | `fromUnixTimestamp64Milli(1415792726123)`                                                                         |
| `$__toTime`                                  | Replaced by the ending time of the Grafana panel range cast to a [DateTime](/reference/data-types/datetime).                                                                       | `toDateTime(1447328726)`                                                                                          |
| `$__toTime_ms`                               | Replaced by the ending time of the panel range cast to a [DateTime64](/reference/data-types/datetime64).                                                                           | `fromUnixTimestamp64Milli(1447328726456)`                                                                         |
| `$__timeInterval(columnName)`                | Replaced by a function calculating the interval based on window size in seconds.                                                                                                   | `toStartOfInterval(toDateTime(columnName), INTERVAL 20 second)`                                                   |
| `$__timeInterval_ms(columnName)`             | Replaced by a function calculating the interval based on window size in milliseconds.                                                                                              | `toStartOfInterval(toDateTime64(columnName, 3), INTERVAL 20 millisecond)`                                         |
| `$__interval_s`                              | Replaced by the dashboard interval in seconds.                                                                                                                                     | `20`                                                                                                              |
| `$__conditionalAll(condition, $templateVar)` | Replaced by the first parameter when the template variable in the second parameter doesn't select every value. Replaced by the 1=1 when the template variable selects every value. | `condition` or `1=1`                                                                                              |
