Pre-aggregate ClickHouse data with materialized views
Use ClickHouse materialized views to maintain aggregated tables automatically so dashboards read pre-computed results instead of scanning raw events.
25 Mar 2026, 11:51 UTC

Problem and useful takeaway
If your ClickHouse dashboard runs COUNT, SUM, or AVG over millions of raw events every time it loads, the query rescans the source table and latency grows with data volume. A materialized view keeps a separate, pre-aggregated table up to date as new rows are inserted, so read queries scan a much smaller table instead.
Takeaway: define a materialized view over your raw event table, query the view's target table directly, and monitor its size with ClickHouse system tables.
Prerequisites
- A running ClickHouse server accessible through
clickhouse-clientor the HTTP interface. - A source table using the
MergeTreeengine family; materialized views attach to inserts on that table. - Privileges to create tables and views, insert into the source, and select from the target.
Create the raw event table
Run this in clickhouse-client as a user with DDL privileges. Replace default with your database if needed.
CREATE TABLE IF NOT EXISTS default.events_raw (
event_date Date,
event_time DateTime,
user_id UInt64,
event_type LowCardinality(String),
value Float64
) ENGINE = MergeTree()
PARTITION BY toYYYYMM(event_date)
ORDER BY (event_date, event_type);
This table stores one row per raw event. The view aggregates it by hour and event type.
Create the materialized view and its target table
Use CREATE MATERIALIZED VIEW ... TO ... so ClickHouse creates a physical target table and populates it from new inserts into events_raw.
CREATE MATERIALIZED VIEW IF NOT EXISTS default.events_hourly_mv
TO default.events_hourly
AS SELECT
toStartOfHour(event_time) AS hour,
event_type,
count() AS event_count,
sum(value) AS value_sum
FROM default.events_raw
GROUP BY hour, event_type;
Where to run: clickhouse-client or the ClickHouse HTTP endpoint.
Required permissions: CREATE MATERIALIZED VIEW and CREATE TABLE on the target database, plus SELECT on the source table.
Expected behavior: ClickHouse creates default.events_hourly with the columns from the SELECT list. Future inserts into events_raw trigger the aggregation and insert results into events_hourly.
Risk: without POPULATE, rows already in events_raw are not backfilled. Only new inserts flow into the view.
Backfill existing data (optional)
If the source table already contains data, insert it into the view manually after creation:
INSERT INTO default.events_hourly
SELECT
toStartOfHour(event_time) AS hour,
event_type,
count() AS event_count,
sum(value) AS value_sum
FROM default.events_raw
GROUP BY hour, event_type;
Do not combine this with POPULATE on the same view, or you may write duplicate aggregated rows.
Verify data flows into the view
Insert a test batch into the source table:
INSERT INTO default.events_raw (event_date, event_time, user_id, event_type, value) VALUES
(toDate('2026-12-01'), '2026-12-01 10:05:00', 1, 'click', 1.0),
(toDate('2026-12-01'), '2026-12-01 10:07:00', 2, 'click', 2.0),
(toDate('2026-12-01'), '2026-12-01 10:15:00', 3, 'purchase', 5.0);
Then check the target table:
SELECT hour, event_type, event_count, value_sum
FROM default.events_hourly
ORDER BY hour, event_type;
Expected check: one row per hour and event type present in the inserted batch, with counts and sums matching the source rows. You can also compare table-level counts:
SELECT count(*) FROM default.events_hourly;
SELECT count(*) FROM default.events_raw;
The target count will be lower because it stores aggregated groups, not raw rows. Confirm the groups that should exist from your test insert.
Query the pre-aggregated table
Applications should read from default.events_hourly, not the raw table, for this aggregation:
SELECT
hour,
sum(event_count) AS total_events,
sum(value_sum) AS total_value
FROM default.events_hourly
WHERE hour >= toStartOfHour(now() - toIntervalDay(7))
GROUP BY hour
ORDER BY hour;
Use EXPLAIN PIPELINE before the query to confirm ClickHouse reads from events_hourly and does not scan events_raw.
Monitor size and control growth
The target table stores its own parts on disk. Check storage with:
SELECT
name,
database,
engine,
total_rows,
total_bytes_on_disk
FROM system.tables
WHERE database = 'default' AND name = 'events_hourly';
Inspect parts and partition sizes:
SELECT
partition,
name,
rows,
bytes_on_disk
FROM system.parts
WHERE table = 'events_hourly' AND active
ORDER BY partition;
To prevent unbounded growth, add a TTL to the target table when you create it, or alter it later:
ALTER TABLE default.events_hourly MODIFY TTL date_add(hour, toIntervalDay(-30));
This removes aggregated rows older than 30 days. Verify TTL application by checking system.parts after a merge; inactive parts should eventually disappear for expired partitions.
Change or remove the view
ClickHouse does not support altering a materialized view definition in place. To change the aggregation:
- Stop writers that depend on the old view if necessary.
DROP MATERIALIZED VIEW IF EXISTS default.events_hourly_mv;DROP TABLE IF EXISTS default.events_hourly;if you also want to remove the aggregated data.- Recreate the view with the new SELECT, and backfill if needed.
Dropping the view does not automatically drop the target table; dropping the target table deletes the pre-aggregated data. Plan for a read gap during recreation if dashboards query the target table directly.
Limitations
- Materialized views react to
INSERTinto the source table. They do not automatically reflectALTER ... UPDATEorDELETEmutations in the same way; plan your backfill strategy accordingly. - Avoid non-deterministic functions such as
now()orrand()inside the view's SELECT, because results can be inconsistent when rows are re-aggregated or backfilled. - Changing the view requires DROP and recreation; existing aggregated data is not migrated automatically.
- Large views consume disk space proportional to the number of distinct aggregation groups. Monitor with
system.tablesand set TTL where retention policy allows.
Practical check before production use
Run a representative insert volume into the source table, then measure query time against events_hourly versus the equivalent aggregation over events_raw. Confirm that system.parts shows active parts for the target table and that no unexpected errors appear in the ClickHouse server log during inserts. If the view target grows faster than expected, add a TTL or reduce the granularity of the GROUP BY.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.