Skip to content

Lesson 8 of 9 · 27m

Materialized Views, Aggregate States, and Projections

Precomputing expensive answers the ClickHouse way: incremental materialized views, AggregatingMergeTree states, projections, backfills, and correctness tradeoffs.

Raw-event scans are the truth, but they are not always the product. Once a dashboard asks the same expensive question every minute, precomputation stops being an optimization and becomes architecture. ClickHouse gives you several tools — materialized views, aggregate states, and projections — and each has sharp edges you should understand before betting a business metric on it.

Materialized views are insert-time transforms

A ClickHouse materialized view is not usually a stored query result refreshed on demand. The common pattern is a trigger-like transform: rows inserted into a source table are also written to a target table through the view.

CREATE TABLE events_daily
(
    day Date, tenant_id UInt64, event_name LowCardinality(String),
    events AggregateFunction(count, UInt64),
    bytes_total AggregateFunction(sum, UInt64)
)
ENGINE = AggregatingMergeTree
ORDER BY (tenant_id, event_name, day);

CREATE MATERIALIZED VIEW events_daily_mv TO events_daily AS
SELECT toDate(event_time) AS day, tenant_id, event_name,
       countState() AS events, sumState(bytes) AS bytes_total
FROM events
GROUP BY day, tenant_id, event_name;

The *State functions store intermediate aggregate state rather than final numbers. Query them with the matching *Merge functions:

SELECT day, countMerge(events) AS events, sumMerge(bytes_total) AS bytes_total
FROM events_daily
WHERE tenant_id = 42
GROUP BY day
ORDER BY day;

This design is fast because merges can combine compatible aggregate states in the background. It is also easy to misuse: you must keep dimensions consistent, understand that rows inserted before the view existed are missing, and know exactly how late or duplicate data behaves.

Projections are alternate physical layouts

Projections let a table maintain an additional precomputed representation inside the same part lifecycle. They are useful when a second query shape is common enough to deserve its own physical organization but you do not want a separately backfilled table. They still cost storage and insert work. The word "projection" does not mean free.

The backfill problem never goes away

The most common operational surprise: create a materialized view today, then wonder why last month is missing. A normal insert-trigger view only sees new inserts. Historical data needs an explicit backfill, usually through a controlled INSERT INTO target SELECT ... GROUP BY ... job.

For large backfills, process bounded slices, validate in staging when correctness is uncertain, reconcile counts against raw data, and document whether duplicates were deduplicated or accepted.

Correctness is a product decision

Approximate aggregates are often fine for analytics, but not all approximations are equal. uniq can be expensive at high cardinality; uniqCombined or uniqTheta trade exactness for memory. Duplicate ingestion can inflate counts. Late events can alter previous days. None of these are implementation details — they are semantics your users will notice.

A good aggregate table names its semantics. events_daily_exact and events_daily_approx tell different stories. So does a column called deduped_events versus one called events.

Field notes

  • Use TO target_table in materialized views unless you have a specific reason not to. Explicit targets are easier to schema-manage.
  • Views can chain, but chains turn ingestion failures into distributed mysteries. Keep the pipeline shallow enough to diagram on one page.
  • Aggregate states are type-specific. countState pairs with countMerge, not wishful thinking.
  • Recreating a view does not rebuild historical rows. Say this out loud in design reviews.
  • Check target-table growth and merge health just as carefully as raw-table health. Aggregates are still data.

Was this lesson helpful?

Sign in to rate