---
title: "Connect Grafana to ClickHouse®: examples and walkthrough"
excerpt: "ClickHouse Grafana example that connects in minutes. Visualize analytical data in your existing dashboards without moving anything."
authors: "Cameron Archer"
categories: "AI Resources"
createdOn: "2025-10-14 19:51:08"
publishedOn: "2025-10-17 19:51:08"
updatedOn: "2025-10-17 19:51:08"
status: "published"
---

Grafana turns ClickHouse® query results into interactive dashboards, but the connection setup and query optimization process trips up many developers the first time they try it. The official ClickHouse® plugin for Grafana supports both HTTP and native protocols, yet choosing the right configuration depends on your infrastructure, security requirements, and performance goals.

This guide walks through installing the Grafana plugin, configuring secure connections, writing optimized queries with Grafana macros, and troubleshooting common errors that prevent dashboards from loading correctly.

![An example real-time analytics dashboard that visualizes metrics from ClickHouse® in Grafana](grafana.png)

## Why use Grafana with ClickHouse® for real-time analytics

Grafana turns ClickHouse® query results into visual dashboards that update as new data arrives. When you connect the two, you get fast analytical queries from ClickHouse® combined with Grafana's charting and visualization options for building monitoring dashboards.

This pairing works well for observability scenarios like tracking application performance metrics, monitoring system health, or analyzing user behavior patterns. ClickHouse® handles high-volume queries with sub-second response times, while Grafana renders those results as interactive time-series charts, tables, and log panels.

## Version and plugin compatibility matrix

The official ClickHouse® plugin for Grafana works with ClickHouse® versions 21.1 and later. Grafana 8.0 and above supports the plugin, though Grafana 9.0 or later provides the best experience with regular plugin updates and improved query builder features.

### ClickHouse® server versions and protocols

ClickHouse® exposes two protocols for external connections: [HTTP on port 8123](https://www.tinybird.co/blog-posts/clickhouse-http-interface-support) and native TCP on port 9000. The Grafana plugin supports both, though HTTP is more common because it works through standard web infrastructure without special network configuration.

Newer ClickHouse® versions starting with 23.0 include performance improvements for the HTTP interface and better support for query progress tracking, with [throughput jumping to 962 QPS](https://presentations.clickhouse.com/2023-release-23.10/index.html?utm_source=openai) in concurrent workloads. Older versions still work but lack some newer optimization features.

### Grafana OSS vs Grafana Cloud support

Both Grafana Open Source and Grafana Cloud support the ClickHouse® plugin, with slightly different installation processes. With Grafana OSS, you install the plugin manually using `grafana-cli` or through the web interface. Grafana Cloud includes a plugin catalog where you enable the ClickHouse® plugin with one click, and updates happen automatically.

## Prerequisites and connection options

Before connecting Grafana to ClickHouse®, you'll want a running ClickHouse® instance with network access from your Grafana server. You'll also want credentials for a ClickHouse® user account, ideally with read-only permissions if you're only building dashboards.

### Native plugin vs Tinybird HTTPS endpoint

You can connect Grafana to ClickHouse® in two ways: directly through the native plugin or by [querying Tinybird via its HTTP interface](https://www.tinybird.co/docs/forward/work-with-data/publish-data/guides/connect-grafana). Direct connection means managing your own ClickHouse® infrastructure, including server maintenance, security updates, and scaling as your data grows.

Tinybird provides [managed ClickHouse® infrastructure](https://www.tinybird.co/blog-posts/tinybird-vs-clickhouse) with built-in HTTPS API endpoints that work with Grafana's standard HTTP data source. This removes the operational work of running ClickHouse® yourself, and Tinybird handles scaling, backups, and performance optimization automatically.

{% html %}
<iframe width="560" height="315" src="https://www.youtube.com/embed/f84URbyCnzk?si=brXYwpvobZqKlnoJ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
{% /html %}

### Network and TLS requirements

For direct ClickHouse® connections, verify that Grafana can reach your ClickHouse® server on the appropriate port (8123 for HTTP or 9000 for native). If your ClickHouse® instance uses TLS, you'll configure SSL certificates in the Grafana data source settings.

Production deployments typically use TLS to encrypt data in transit between Grafana and ClickHouse®. Self-signed certificates require uploading the certificate file in Grafana's data source configuration, while certificates from trusted authorities work without extra setup.

## Step-by-step plugin installation

Installing the ClickHouse® plugin takes a few minutes and can be done through three different methods depending on your Grafana setup.

### 1. Install from Grafana UI

Navigate to Administration > Plugins in your Grafana instance and search for "ClickHouse®" in the plugin catalog. Click the official "ClickHouse®" plugin by Grafana Labs, then click Install. After installation completes, the plugin appears in your installed plugins list and you can create data sources.

### 2. Install with grafana-cli

For command-line installation, use the `grafana-cli` tool that comes with Grafana:

```bash
grafana-cli plugins install grafana-clickhouse-datasource
```

After the plugin installs, restart your Grafana server to load it. You can verify installation by checking the plugins directory, typically at `/var/lib/grafana/plugins/`.

### 3. Install in Grafana Cloud

Access your Grafana Cloud portal and navigate to the Connections section. Search for "ClickHouse®" in the available integrations and click Enable. Grafana Cloud automatically installs and updates the plugin without manual version management.

## Configure the ClickHouse® data source in Grafana

After installing the plugin, you'll create a new data source that tells Grafana how to connect to your ClickHouse® instance.

### Host port and authentication settings

In Grafana, navigate to Connections > Data sources and click "Add new data source." Select ClickHouse® from the list. In the connection settings, enter your ClickHouse® server URL including protocol and port, like `http://localhost:8123` or `https://clickhouse.example.com:8443`.

For authentication, enter a ClickHouse® username and password in the provided fields. Creating a dedicated read-only user in ClickHouse® for Grafana connections limits potential damage if credentials get compromised.

### Secure connections with HTTPS or TLS

Enable the "TLS/SSL" toggle in the data source settings if your ClickHouse® instance requires encrypted connections. For self-signed certificates, upload the certificate file using the "TLS/SSL Auth Details" section. Tinybird uses HTTPS by default for all API endpoints, so connections are encrypted without extra configuration when using Tinybird as your ClickHouse® backend.

### Test the connection

Click "Save & Test" at the bottom of the data source configuration page. Grafana sends a test query to ClickHouse® and displays a success message if the connection works. Error messages typically point to network issues, incorrect credentials, or firewall rules blocking the connection.

## Build your first time series query

Time-series visualizations show how metrics change over time and are the most common dashboard type in Grafana.

### 1. Select timestamp and value columns

Create a new dashboard and add a panel. In the panel editor, select your ClickHouse® data source and choose the query builder or SQL editor. For a time-series chart, your query needs at least two columns: a timestamp and a numeric value.

```sql
SELECT
    timestamp AS time,
    metric_value
FROM metrics_table
ORDER BY time
```

The query builder provides dropdown menus to select your table and columns, while the SQL editor gives you full control over query syntax.

### 2. Apply $__timeFilter macro

Grafana provides macros that inject dynamic values into your queries based on dashboard settings. The `$__timeFilter` macro adds a WHERE clause that filters data to the time range selected in the dashboard:

```sql
SELECT
    timestamp AS time,
    avg(response_time) AS avg_response
FROM api_logs
WHERE $__timeFilter(timestamp)
GROUP BY time
ORDER BY time
```

This macro automatically updates when users change the dashboard time range, so your query always returns relevant data without manual editing.

### 3. Render a line chart

In the panel settings, select "Time series" as the visualization type. Grafana automatically detects the time column and numeric value columns, then renders a line chart showing how values change over time. You can customize colors, axis labels, and legends in the panel options on the right side of the editor.

## Use macros variables and ad-hoc filters

Grafana's dynamic query features let you build flexible dashboards that users can customize without editing SQL.

### Common macros for grouping and sampling

The ClickHouse® plugin includes several macros that simplify common query patterns:

- **$__timeFilter:** Filters rows to the dashboard's selected time range
- **$__timeInterval:** Groups data into appropriate time buckets based on the selected range
- **$__conditionalAll:** Handles "All" selections in dropdown variables

Here's an example using `$__timeInterval` for automatic grouping:

```sql
SELECT
    $__timeInterval(timestamp) AS time,
    count(*) AS events
FROM user_events
WHERE $__timeFilter(timestamp)
GROUP BY time
ORDER BY time
```

When viewing a 24-hour range, this query might group by minutes. Zooming out to a month automatically switches to daily grouping without changing the query.

### Template variables for dynamic tables

Template variables add dropdown menus to your dashboard that change query behavior. Create a variable in dashboard settings that queries ClickHouse® for available table names or dimension values:

```sql
SELECT DISTINCT table_name
FROM system.tables
WHERE database = 'my_database'
```

Reference this variable in your panel queries using `${table_name}` syntax, letting users switch between different tables without creating separate panels.

### Ad-hoc filters with enums and text search

Enable ad-hoc filters in your ClickHouse® data source settings to let users add WHERE clause conditions through the dashboard UI. Users can filter on any column by clicking the filter icon in the dashboard toolbar, then selecting a column, operator, and value from dropdown menus.

## Visualize logs and traces stored in ClickHouse®

Beyond metrics, Grafana can display structured logs and distributed traces when the data is stored in ClickHouse® with the right schema.

### Logs panel with level and message columns

The Logs panel in Grafana expects specific column names or aliases to display log data correctly. Your query returns a timestamp, log level, and message text:

```sql
SELECT
    timestamp AS time,
    level,
    message
FROM application_logs
WHERE $__timeFilter(timestamp)
ORDER BY timestamp DESC
```

Grafana colors log lines based on the level column (INFO, WARN, ERROR) and makes them searchable through the panel's filter box.

### Traces panel using OpenTelemetry schema

If you're storing distributed traces in ClickHouse® using the OpenTelemetry format, you can query span data and display it in Grafana's Traces panel. The query returns trace IDs, span IDs, parent span IDs, and timing information:

```sql
SELECT
    TraceId,
    SpanId,
    ParentSpanId,
    SpanName,
    Timestamp,
    Duration
FROM otel_traces
WHERE $__timeFilter(Timestamp)
    AND TraceId = '${trace_id}'
```

This visualization shows the waterfall view of spans within a trace, helping you identify slow operations in distributed systems.

## Performance tips for large dashboards

As your ClickHouse® tables grow, [dashboard queries might slow down](https://www.tinybird.co/blog-posts/7-tips-to-make-your-dashboards-faster) without optimization.

### Use materialized views to pre-aggregate

[Materialized views in ClickHouse®](https://www.tinybird.co/blog-posts/what-are-materialized-views-and-why-do-they-matter-for-realtime) compute and store aggregated results as data arrives, rather than calculating them at query time. For dashboard queries that always aggregate the same way (like daily active users or hourly error rates), create a materialized view that maintains the aggregated table. This approach can deliver 10× to 20× faster performance for search queries:

```sql
CREATE MATERIALIZED VIEW daily_active_users_mv
ENGINE = SummingMergeTree()
ORDER BY date
AS SELECT
    toDate(timestamp) AS date,
    uniqState(user_id) AS unique_users
FROM user_events
GROUP BY date
```

Point your Grafana queries at the materialized view instead of the raw events table for faster dashboard loading.

### Limit result sets with LIMIT and SAMPLE

Add LIMIT clauses to your queries to prevent returning millions of rows to Grafana. For time-series charts, 10,000 points is usually more than enough since most screens can't display that level of detail:

```sql
SELECT
    $__timeInterval(timestamp) AS time,
    count(*) AS events
FROM large_events_table
WHERE $__timeFilter(timestamp)
GROUP BY time
ORDER BY time
LIMIT 10000
```

For approximate results on very large tables, use ClickHouse®'s SAMPLE clause to query a representative subset of data instead of scanning every row.

### Monitor query cost in system tables

ClickHouse® tracks every query in the `system.query_log` table. Query this table to find slow dashboard queries and identify optimization opportunities:

```sql
SELECT
    query,
    query_duration_ms,
    read_rows,
    read_bytes
FROM system.query_log
WHERE query LIKE '%FROM metrics_table%'
ORDER BY query_duration_ms DESC
LIMIT 10
```

Look for queries that scan many rows but return few results, which often benefit from better indexing or pre-aggregation. Proper indexing can achieve query latencies under 0.5 seconds even on 650 million-row datasets.

## Troubleshooting common errors

Several common issues can prevent Grafana from connecting to ClickHouse® or executing queries correctly.

### Authentication or HTTP 400 issues

If you see authentication errors or HTTP 400 responses, verify that the username and password in your Grafana data source match a valid ClickHouse® user. Check that the user has SELECT permissions on the tables you're querying using ClickHouse®'s `SHOW GRANTS` command. Also confirm that ClickHouse®'s HTTP interface is enabled and listening on the expected port (the `http_port` setting in ClickHouse®'s config file controls this, typically set to 8123).

### Unknown function macro errors

Errors mentioning unknown functions like `$__timeFilter` usually mean the ClickHouse® plugin isn't properly installed or is outdated. Update the plugin to the latest version through Grafana's plugin management interface. If errors persist, verify that you're using the official Grafana Labs ClickHouse® plugin rather than an older community version.

### Empty panels because of timezone mismatch

When panels show no data despite having records in the expected time range, timezone mismatches are often the cause. ClickHouse® might store timestamps in one timezone while Grafana interprets them in another, causing the time filter to miss all records. Store all timestamps in UTC within ClickHouse® and configure Grafana to use UTC for queries. You can convert to local timezones only when displaying results to users using ClickHouse®'s `toTimeZone()` function.

## From local dev to managed ClickHouse® with Tinybird

[Tinybird](https://www.tinybird.co) simplifies the ClickHouse®-Grafana integration by providing managed infrastructure and HTTP endpoints that work with Grafana's built-in ClickHouse® plugin. Instead of managing ClickHouse® servers yourself, you can focus on building queries and dashboards while Tinybird handles infrastructure scaling and performance optimization.

Start by installing the Tinybird CLI and creating a data source from a CSV or JSON file. The CLI automatically infers the schema from your data and creates a ClickHouse® table in Tinybird's managed infrastructure:

```bash
curl -L tinybird.co | sh
tb login
tb datasource create events --file events.csv
```

You can then stream additional data using the [Events API](https://www.tinybird.co/docs/forward/get-data-in/events-api) or connect real-time data sources like Kafka.

Next, create a Tinybird pipe that defines your SQL query and exposes it as an API endpoint:

```tinybird
TOKEN dashboard_read READ

NODE endpoint
SQL >
    %
    SELECT
        toStartOfMinute(timestamp) AS time,
        avg(response_time) AS avg_response
    FROM api_logs
    WHERE timestamp >= now() - INTERVAL {{Int32(hours, 24)}} HOUR
    GROUP BY time
    ORDER BY time

TYPE endpoint
```

Deploy the pipe with `tb deploy` and Tinybird generates an HTTPS URL that returns JSON results. You can either add this URL as an HTTP data source in Grafana or use Tinybird's HTTP interface to query both data sources and pipes as views.

To get started, [create a free Tinybird account](https://cloud.tinybird.co/signup). The free tier includes enough compute and storage to build several production dashboards without infrastructure setup or maintenance work.

## FAQs about Grafana and ClickHouse®

### How can I connect Grafana to ClickHouse® if plugins are disabled?

Use Grafana's built-in HTTP data source to query ClickHouse®'s HTTP interface directly at `http://your-clickhouse:8123/?query=SELECT...`. Alternatively, connect to a Tinybird API endpoint which provides HTTPS access to ClickHouse® data without requiring plugin installation.

### How do I share a dashboard with customer-level row security?

Configure ClickHouse® row-level security policies that filter data based on the authenticated user, or use Tinybird's token-based access control to create separate API tokens for each customer. Each token can include filters that automatically limit query results to that customer's data.

### How can I migrate an existing InfluxDB dashboard to ClickHouse®?

Convert InfluxQL queries to ClickHouse® SQL syntax by replacing InfluxDB's measurement names with ClickHouse® table names and translating time functions to their ClickHouse® equivalents. Update the data source configuration in your dashboard to point to ClickHouse® instead of InfluxDB, then test each panel to verify the query results match your expectations./
