What are Materialized Views?
Materialized views automatically update aggregations when new data is inserted into the source datasource. Unlike copy pipes that run on a schedule, materialized views update in real-time. Use materialized views when:- You need real-time aggregations
- You want to pre-compute expensive queries
- You’re aggregating large amounts of data
- You need periodic snapshots
- You want to control when aggregations run
- You need to transform data from multiple sources
Defining Materialized Views
UsedefineMaterializedView() to create a materialized view:
Aggregate Functions
Materialized views use special aggregate function types:SimpleAggregateFunction
For simple aggregations likesum, min, max, any:
AggregateFunction
For complex aggregations likeuniq, quantile, groupArray:
State suffix:
Querying Materialized Views
Query the target datasource using merge combinators:sumMerge()for SimpleAggregateFunction(sum, …)minMerge()for SimpleAggregateFunction(min, …)maxMerge()for SimpleAggregateFunction(max, …)uniqMerge()for AggregateFunction(uniq, …)quantileMerge(0.95)()for AggregateFunction(quantile(0.95), …)
Complete Example
A full materialized view setup with hourly aggregations:Deployment Methods
Control how materialized views are updated during deployment:Default (Recreate)
Recreates the table when the schema changes:Alter Method
Preserves existing data when only the query changes:alter when:
- You’re only changing the SQL query
- You want to preserve existing aggregated data
- You want faster deployments
Best Practices
Choose the right engine
Use
AggregatingMergeTree for the target datasource when using AggregateFunction types.Match aggregate functions
The aggregate function in your SQL must match the type in your schema:
simpleAggregateFunction("sum", ...)→sum()in SQLaggregateFunction("uniq", ...)→uniqState()in SQL
Use appropriate granularity
Aggregate at the right time granularity:
toStartOfHour()for hourly aggregationstoStartOfDay()/toDate()for daily aggregationstoStartOfInterval()for custom intervals
Next Steps
Copy Pipes
Learn about scheduled data snapshots
Type-Safe Client
Query your materialized views with type safety