Modern applications generate large volumes of data from transactions, user activities, application logs, IoT devices, and business operations. As datasets grow, analytical queries can become expensive because they repeatedly scan and aggregate millions or billions of records.
ClickHouse is designed for analytical workloads and provides materialized views to reduce the amount of work required at query time. Instead of calculating every result from the original dataset whenever a user runs a query, an incremental materialized view processes newly inserted data and stores the transformed results in another table.
This approach shifts computation from query time to insert time. Applications can then query smaller, pre-aggregated datasets instead of repeatedly scanning the complete source table.
For example, an e-commerce application may receive millions of order events every day. A dashboard that displays daily revenue by country does not need to aggregate every individual order whenever someone opens the dashboard. An incremental materialized view can maintain the required aggregation as new orders arrive.
This article explains how incremental materialized views work in ClickHouse, how to build them using SQL, how to handle aggregate states, and how to manage historical data, joins, duplicates, and production performance.
What Are Incremental Materialized Views in ClickHouse?
An incremental materialized view in ClickHouse is a database object that executes a query whenever new data is inserted into its source table.
The query processes the newly inserted block rather than scanning the entire source table. Its result is then written to a destination table.
The destination table stores the transformed or aggregated data. As additional inserts arrive, the view processes each new block and adds its results to the destination.
This is different from a traditional materialized view implementation in some relational databases, where a stored result may be refreshed by rerunning a complete query.
In ClickHouse, an incremental materialized view behaves more like an insert trigger. It is automatically executed as part of the insert pipeline.
The architecture contains three main components:
Source table: Receives the original application data.
Materialized view: Applies filtering, transformation, or aggregation to newly inserted data.
Target table: Stores the results produced by the materialized view.
For example, consider an application that stores every customer order in an orders table. A materialized view can calculate the revenue generated by each country and day. When new orders arrive, only those new rows are processed.
The dashboard can then read the smaller aggregation table instead of scanning the complete orders table.
How Incremental Materialized Views Work
The processing flow is straightforward.
An application inserts records into a source table.
ClickHouse receives the inserted data block.
The materialized view executes its SELECT query against that newly inserted block.
The transformed or aggregated result is written to the target table.
Additional inserts produce additional result blocks.
The target table's storage engine combines or aggregates data when required.
Consider an example in which an application receives these orders:
Order ID | Country | Amount |
|---|
101 | India | 500 |
102 | India | 700 |
103 | USA | 900 |
An incremental materialized view can calculate revenue by country for the inserted block.
The target table receives:
Country | Revenue |
|---|
India | 1200 |
USA | 900 |
When another batch of orders arrives, the materialized view processes that batch and writes its partial results to the target table.
The final result is produced by combining the partial aggregations stored in the target table.
This design is particularly effective when the application frequently queries a relatively small summary of a much larger dataset.
Creating a Source Table
Let's build an example using an e-commerce order processing system.
The source table stores order information, including the order identifier, customer, country, order date, and amount.
CREATE TABLE orders
(
order_id UInt64,
customer_id UInt64,
country LowCardinality(String),
order_date DateTime,
amount Decimal(12, 2)
)
ENGINE = MergeTree
ORDER BY (order_date, country, order_id);
The MergeTree engine is suitable for analytical data storage. The ORDER BY expression determines the table's sorting key and helps organize data for queries.
For this example, the application inserts order records into the orders table.
INSERT INTO orders VALUES
(101, 1001, 'India', '2026-12-01 10:15:00', 500.00),
(102, 1002, 'India', '2026-12-01 11:30:00', 700.00),
(103, 1003, 'USA', '2026-12-01 12:00:00', 900.00),
(104, 1004, 'India', '2026-12-02 09:45:00', 300.00),
(105, 1005, 'USA', '2026-12-02 13:20:00', 450.00);
The source table now contains five order records. A dashboard may need daily revenue and order counts grouped by country.
Calculating this aggregation directly from the source table is possible, but repeating the operation over a large dataset can become expensive.
An incremental materialized view can maintain the aggregation automatically.
Creating a Target Aggregation Table
Before creating the materialized view, create a destination table to store the aggregated results.
For this example, use the AggregatingMergeTree engine.
CREATE TABLE daily_country_sales
(
order_day Date,
country LowCardinality(String),
total_orders AggregateFunction(count),
total_revenue AggregateFunction(sum, Decimal(12, 2))
)
ENGINE = AggregatingMergeTree
ORDER BY (order_day, country);
The target table stores aggregate states rather than only final numeric values.
An aggregate state contains the intermediate information required to calculate the final result. ClickHouse can combine these states during background merges or when a query explicitly merges them.
This is useful because separate insert blocks may produce multiple partial results for the same country and day.
Creating an Incremental Materialized View
Now create a materialized view that reads new records from the orders table and writes aggregate states to the target table.
CREATE MATERIALIZED VIEW daily_country_sales_mv
TO daily_country_sales
AS
SELECT
toDate(order_date) AS order_day,
country,
countState() AS total_orders,
sumState(amount) AS total_revenue
FROM orders
GROUP BY
order_day,
country;
The materialized view executes whenever new records are inserted into orders.
The query uses two important aggregate-state functions:
The materialized view does not need to scan all existing orders. It processes the newly inserted block and writes the corresponding aggregate states to daily_country_sales.
This is the central idea behind incremental materialized views: process new data once and reuse the stored aggregation for future queries.
Querying Aggregated Results
To retrieve the final revenue and order count, use the corresponding Merge functions.
SELECT
order_day,
country,
countMerge(total_orders) AS order_count,
sumMerge(total_revenue) AS revenue
FROM daily_country_sales
GROUP BY
order_day,
country
ORDER BY
order_day,
country;
The Merge functions combine aggregate states and return the final values.
The output for the sample data is:
Order Day | Country | Order Count | Revenue |
|---|
2026-12-01 | India | 2 | 1200.00 |
2026-12-01 | USA | 1 | 900.00 |
2026-12-02 | India | 1 | 300.00 |
2026-12-02 | USA | 1 | 450.00 |
As more orders are inserted, the materialized view automatically processes them. The dashboard query continues reading the aggregation table.
The target table may contain multiple partial states for the same grouping key until background merges combine them. Using the Merge functions in the query ensures the correct final result without relying on a background merge having already completed.
Using SimpleAggregateFunction for Simpler Aggregations
Not every aggregation requires the AggregateFunction data type.
For suitable functions, ClickHouse provides SimpleAggregateFunction. It can store the resulting value directly and is often easier to work with.
For example, sum and count can be represented using SimpleAggregateFunction.
CREATE TABLE daily_sales_simple
(
order_day Date,
country LowCardinality(String),
total_orders SimpleAggregateFunction(sum, UInt64),
total_revenue SimpleAggregateFunction(sum, Decimal(12, 2))
)
ENGINE = AggregatingMergeTree
ORDER BY (order_day, country);
The materialized view can then write partial counts and sums:
CREATE MATERIALIZED VIEW daily_sales_simple_mv
TO daily_sales_simple
AS
SELECT
toDate(order_date) AS order_day,
country,
count() AS total_orders,
sum(amount) AS total_revenue
FROM orders
GROUP BY
order_day,
country;
The final query uses ordinary sum functions:
SELECT
order_day,
country,
sum(total_orders) AS order_count,
sum(total_revenue) AS revenue
FROM daily_sales_simple
GROUP BY
order_day,
country
ORDER BY
order_day,
country;
SimpleAggregateFunction is convenient for supported aggregates whose intermediate values can be combined using the same aggregation operation. For more complex aggregates, such as averages or distinct counts, AggregateFunction states are generally more appropriate.
For example, an average should not be calculated by simply averaging the averages from separate insert batches. Instead, store an average state and combine it using avgMerge.
Handling Average and Distinct Count Aggregations
Some analytical calculations require more than storing a simple total.
Consider a dashboard that displays average order value and the number of unique customers per country.
For these calculations, use aggregate-state functions.
CREATE TABLE country_customer_metrics
(
country LowCardinality(String),
average_order_value AggregateFunction(avg, Decimal(12, 2)),
unique_customers AggregateFunction(uniq, UInt64)
)
ENGINE = AggregatingMergeTree
ORDER BY country;
Create the materialized view:
CREATE MATERIALIZED VIEW country_customer_metrics_mv
TO country_customer_metrics
AS
SELECT
country,
avgState(amount) AS average_order_value,
uniqState(customer_id) AS unique_customers
FROM orders
GROUP BY country;
Query the final results:
SELECT
country,
avgMerge(average_order_value) AS average_order_value,
uniqMerge(unique_customers) AS unique_customers
FROM country_customer_metrics
GROUP BY country
ORDER BY country;
The average and distinct-count states are combined across the inserted blocks. This avoids incorrectly averaging partial averages or adding together distinct counts that may contain duplicate customers.
Processing Multiple Materialized Views
A source table can have multiple incremental materialized views.
For example, the orders table may feed separate target tables for:
Daily revenue by country.
Total orders by customer.
Revenue by product category.
Hourly order volume.
Each view can apply a different transformation or aggregation to the same inserted data.
This design helps separate analytical workloads. A dashboard that displays country-level revenue does not need to read a target table designed for customer-level reporting.
However, every additional materialized view adds work to the insert pipeline. Too many expensive views can reduce ingestion throughput.
ClickHouse supports parallel materialized view processing through the parallel_view_processing setting. Enabling it can improve insert performance when views are independent and the cluster has sufficient resources. It should not be enabled without checking dependencies and execution requirements.
Understanding Joins in Incremental Materialized Views
Incremental materialized views can also use JOIN operations.
Consider an application with two tables:
A materialized view can enrich newly inserted orders with customer details.
However, there is an important behavior to understand: only inserts into the left-most source table trigger an incremental materialized view.
If the view uses orders as the left-most table and customers as a joined table, inserting new orders triggers the view. Updating customers alone does not trigger the view.
This means the materialized view reads the customer information available when the new order rows are processed. Previously stored results are not automatically updated when customer details change.
This behavior is appropriate for relatively stable reference data, but it can produce stale results when joined data changes frequently.
For complex joins that need to reflect changes from multiple source tables, consider a refreshable materialized view instead.
Handling Historical Data and Backfilling
One important limitation of incremental materialized views is that creating a view does not automatically process all existing records in the source table.
By default, it processes records inserted after the view is created.
For example, suppose the orders table already contains 50 million records. Creating a new incremental materialized view does not automatically aggregate those 50 million records. It starts processing new inserts.
This means historical data must be backfilled separately when the target table needs to represent the complete history.
A basic backfill operation can use INSERT INTO SELECT:
INSERT INTO daily_country_sales
SELECT
toDate(order_date) AS order_day,
country,
countState() AS total_orders,
sumState(amount) AS total_revenue
FROM orders
GROUP BY
order_day,
country;
This query calculates aggregate states for the existing source records and inserts them into the target table.
However, production backfills require careful coordination. If new records are inserted while the backfill is running, those records may be processed both by the backfill query and by the materialized view.
A safe backfill strategy should define a clear boundary between historical records and live inserts. One approach is to backfill a bounded time range while the materialized view handles records outside that range. Another approach is to build a separate target table, validate the result, and then switch to it.
Avoid using the POPULATE option as a shortcut for large production backfills. It can create a race condition in which records inserted during view creation are missed. A controlled backfill process is easier to monitor and recover.
Incremental vs. Refreshable Materialized Views
ClickHouse also supports refreshable materialized views. Although both approaches store query results, they work differently.
Incremental materialized views process newly inserted blocks. Refreshable materialized views periodically execute their complete query and update the stored result.
Feature | Incremental materialized view | Refreshable materialized view |
|---|
Execution | On source-table inserts | On a configured schedule |
Processing | Newly inserted data blocks | Full query execution |
Data freshness | Updated as inserts arrive | Updated at refresh intervals |
Complex joins | Requires careful source-table handling | Suitable for queries involving multiple changing tables |
Typical workload | Continuous aggregation and transformation | Periodic reports and complex denormalization |
Compute cost | Distributed across inserts | Concentrated during refresh |
Use incremental materialized views when data arrives continuously and the application needs results updated as inserts occur.
Use refreshable materialized views when the query is complex, depends on multiple changing tables, or can tolerate slightly stale results.
Best Practices for Production Applications
Incremental materialized views can improve analytical performance, but they must be designed carefully.
Design the target table around query patterns
The target table should contain the dimensions and aggregate values required by application queries. Avoid storing unnecessary columns because they increase storage and processing costs.
Choose an ORDER BY key that supports the most common filters and grouping operations.
Use the correct aggregate-state functions
Use countState, sumState, avgState, and uniqState when the aggregation must be combined across multiple insert blocks.
Use the matching Merge functions when reading aggregate states. For suitable simple aggregates, SimpleAggregateFunction can reduce query complexity.
Plan for duplicate inserts
Incremental materialized views process inserted blocks. They do not automatically understand whether an incoming business event represents a duplicate transaction.
If the application retries an insert, the materialized view may process that data again. This can result in duplicated totals.
Design ingestion around reliable event identifiers, deduplication, and appropriate retry handling. Do not assume that the source table's sorting key automatically prevents duplicate business events.
Monitor insert performance
Materialized views add processing to the insert pipeline. Monitor insert latency, CPU usage, memory consumption, merge activity, and target-table growth.
If insert performance degrades, inspect the materialized view queries and consider simplifying transformations or separating expensive workloads.
Backfill historical data carefully
A new materialized view does not automatically contain historical data. Plan a controlled backfill and ensure that live inserts are not counted twice.
Keep joins predictable
Use joins against relatively stable reference data when possible. If multiple joined tables change frequently and the result must reflect those changes, consider refreshable materialized views or another controlled transformation pipeline.
Validate results against the source table
Before using an incremental materialized view for production reporting, compare its output with a direct aggregation over the source table.
Repeat this validation after schema changes, backfills, and changes to the materialized view query.
Common Mistakes to Avoid
One common mistake is assuming that a materialized view automatically processes historical records. Incremental views normally process only new inserts, so existing data requires a separate backfill.
Another mistake is using ordinary average calculations on partial averages. The correct approach is to store an aggregate state using avgState and combine it using avgMerge.
Developers also sometimes assume that updates to a joined table automatically update the materialized view. Only inserts into the source table trigger the incremental view. Changes to right-side JOIN tables do not retroactively update existing target rows.
A further mistake is ignoring duplicate inserts. If an application retries an event, its aggregation may be counted again unless the ingestion process handles duplicates correctly.
Finally, do not create many expensive materialized views without measuring their impact on insert throughput. Faster analytical queries should not come at the cost of an unreliable ingestion pipeline.
Advantages and Disadvantages
Incremental materialized views provide several advantages:
Move aggregation work from query time to insert time.
Improve the performance of frequently executed analytical queries.
Process only newly inserted data rather than repeatedly scanning the full source table.
Support filtering, transformations, and complex aggregate functions.
Allow multiple target tables to serve different reporting requirements.
Scale well for large analytical datasets when the transformations are designed appropriately.
They also introduce some limitations:
Existing records require a separate backfill.
Updates and deletes in the source table do not automatically update previously generated results.
Changes to joined tables do not trigger the view.
Additional views increase insert-time processing.
Duplicate events can produce incorrect aggregates without proper handling.
Aggregate-state tables require appropriate Merge functions when querying results.
Conclusion
Incremental materialized views are an effective way to build fast analytical pipelines in ClickHouse. They process newly inserted data, apply transformations or aggregations, and store the results in dedicated target tables.
For applications that continuously ingest events, transactions, or activity records, this approach can significantly reduce the amount of work required by dashboards and reporting queries.
A successful implementation depends on choosing the right target-table engine, using aggregate states correctly, planning historical backfills, understanding JOIN behavior, and handling duplicate events.
When the workload requires continuous aggregation, incremental materialized views are often a strong choice. When the query depends on multiple changing tables or requires a complete periodic recalculation, refreshable materialized views may be more appropriate.
Join the conversation! Your thoughts help the community grow.