CREATE MATERIALIZED VIEW
CREATE MATERIALIZED VIEW creates a materialized view. For usage information about materialized views, see Synchronous materialized view and Asynchronous materialized view.
CAUTION
- Only users with the CREATE MATERIALIZED VIEW privilege in the database where the base table resides can create a materialized view.
- From v3.4.0 onwards, StarRocks supports creating synchronous materialized views in shared-data clusters.
Creating a materialized view is an asynchronous operation. Running this command successfully indicates that the task of creating the materialized view is submitted successfully. You can view the building status of a synchronous materialized view in a database via SHOW ALTER MATERIALIZED VIEW command, and view that of an asynchronous materialized view by querying the metadata views tasks and task_runs in Information Schema.
StarRocks supports asynchronous materialized views from v2.4. The major differences between asynchronous materialized views and synchronous materialized views in previous versions are as follows:
| Single-table aggregation | Multi-table join | Query rewrite | Refresh strategy | Base table | |
|---|---|---|---|---|---|
| ASYNC MV | Yes | Yes | Yes |
| Multiple tables from:
|
| SYNC MV (Rollup) | Limited choices of aggregate functions | No | Yes | Synchronous refresh during data loading | Single table in the default catalog |
Synchronous materialized viewβ
Syntaxβ
CREATE MATERIALIZED VIEW [IF NOT EXISTS] [database.]<mv_name>
[COMMENT ""]
[PROPERTIES ("key"="value", ...)]
AS
<query_statement>
Parameters in brackets [] are optional.
Parametersβ
mv_name (required)
The name of the materialized view. The naming requirements are as follows:
- The name must consist of letters (a-z or A-Z), digits (0-9), or underscores (
_), and it can only start with a letter. - The length of the name cannot exceed 64 characters.
- The name is case-sensitive.
COMMENT (optional)
Comment on the materialized view. Note that COMMENT must be placed after mv_name. Otherwise, the materialized view cannot be created.
query_statement (required)
The query statement to create the materialized view. Its result is the data in the materialized view. The syntax is as follows:
SELECT select_expr[, select_expr ...]
[WHERE where_expr]
[GROUP BY column_name[, column_name ...]]
[ORDER BY column_name[, column_name ...]]
-
select_expr (required)
All columns in the query statement, that is, all columns in the materialized view schema. This parameter supports the following values:
- Simple columns or aggregate columns such as
SELECT a, abs(b), min(c) FROM table_a, wherea,b, andcare the names of columns in the base table. If you do not specify column names for the materialized view, StarRocks automatically assigns names to the columns. - Expressions such as
SELECT a+1 AS x, b+2 AS y, c*c AS z FROM table_a, wherea+1,b+2andc*care the expressions that reference the columns in the base tables, andx,yandzare the aliases assigned to the columns in the materialized view.
NOTE
- You must specify at least one column in
select_expr. - When creating a synchronous materialized view with an aggregate function, you must specify the GROUP BY clause, and specify at least one GROUP BY column in
select_expr. - Synchronous materialized views do not support clauses such as JOIN and the HAVING clause of GROUP BY.
- From v3.1 onwards, each synchronous materialized view can support more than one aggregate function for each column of the base table, for example, query statements such as
select b, sum(a), min(a) from table group by b. - From v3.1 onwards, synchronous materialized views support complex expressions for SELECT and aggregate functions, for example, query statements such as
select b, sum(a + 1) as sum_a1, min(cast (a as bigint)) as min_a from table group by borselect abs(b) as col1, a + 1 as col2, cast(a as bigint) as col3 from table. The following restrictions are imposed on the complex expression used for synchronous materialized views:- Each complex expression must have an alias and different aliases must be assigned to different complex expressions among all the synchronous materialized views of a base table. For example, query statements
select b, sum(a + 1) as sum_a from table group by bandselect b, sum(a) as sum_a from table group by bcannot be used to create synchronous materialized views for a same base table. You can set different aliases for a complex expression. - You can check whether your queries are rewritten by the synchronous materialized views created with complex expressions by executing
EXPLAIN <sql_statement>. For more information, see Query analysis.
- Each complex expression must have an alias and different aliases must be assigned to different complex expressions among all the synchronous materialized views of a base table. For example, query statements
- Simple columns or aggregate columns such as
-
WHERE (optional)
From v3.1.8 onwards, synchronous materialized views support the WHERE clause which can filter rows used for the materialized view.
-
GROUP BY (optional)
The GROUP BY column of the query. If this parameter is not specified, the data will not be grouped by default.
-
ORDER BY (optional)
The ORDER BY column of the query.
- Columns in the ORDER BY clause must be declared in the same order as the columns in
select_expr. - If the query statement contains a GROUP BY clause, the ORDER BY columns must be identical to the GROUP BY columns.
- If this parameter is not specified, the system will automatically supplement the ORDER BY column according to the following rules:
- If the materialized view is the AGGREGATE type, all GROUP BY columns are automatically used as sort keys.
- If the materialized view is not the AGGREGATE type, StarRocks automatically selects sort keys based on the prefix columns.
- Columns in the ORDER BY clause must be declared in the same order as the columns in
Query a synchronous materialized viewβ
Because a synchronous materialized view is essentially an index of the base table rather than a physical table, you can only query a synchronous materialized view using the hint [_SYNC_MV_]:
-- Do not omit the brackets [] in the hint.
SELECT * FROM <mv_name> [_SYNC_MV_];
CAUTION
Currently, StarRocks automatically generates names for columns in a synchronous materialized view even if you have specified aliases for them.
Automatic query rewrite with synchronous materialized viewβ
When a query that follows the pattern of a synchronous materialized view is executed, the original query statement is automatically rewritten and the intermediate results stored in the materialized view are used.
The following table shows the correspondence between the aggregate function in the original query and the aggregate function used to construct the materialized view. You can select the corresponding aggregate function to build a materialized view according to your business scenario.
| aggregate function in the original query | aggregate function of the materialized view |
|---|---|
| sum | sum |
| min | min |
| max | max |
| count | count |
| bitmap_union, bitmap_union_count, count(distinct) | bitmap_union |
| hll_raw_agg, hll_union_agg, ndv, approx_count_distinct | hll_union |
| percentile_approx, percentile_union | percentile_union |
In addition to the above functions, starting from StarRocks v3.4.0, synchronous materialized views also support generic aggregate functions. For more information about generic aggregate functions, see Generic aggregate function states.
-- Create a synchronous materialized view test_mv1 to store aggregate states.
CREATE MATERIALIZED VIEW test_mv1
AS
SELECT
dt,
-- Original aggregate functions.
min(id) AS min_id,
max(id) AS max_id,
sum(id) AS sum_id,
bitmap_union(to_bitmap(id)) AS bitmap_union_id,
hll_union(hll_hash(id)) AS hll_union_id,
percentile_union(percentile_hash(id)) AS percentile_union_id,
-- Generic aggregate state functions.
ds_hll_count_distinct_union(ds_hll_count_distinct_state(id)) AS hll_id,
avg_union(avg_state(id)) AS avg_id,
array_agg_union(array_agg_state(id)) AS array_agg_id,
min_by_union(min_by_state(province, id)) AS min_by_province_id
FROM t1
GROUP BY dt;
Asynchronous materialized viewβ
Syntaxβ
CREATE MATERIALIZED VIEW [IF NOT EXISTS] [database.]<mv_name>
[COMMENT ""]
-- You must specify either `distribution_desc` or `refresh_scheme`, or both.
-- distribution_desc
[DISTRIBUTED BY HASH(<bucket_key>[,<bucket_key2> ...]) [BUCKETS <bucket_number>]]
-- refresh_desc
[REFRESH
-- refresh_moment
[IMMEDIATE | DEFERRED]
-- refresh_scheme
[ASYNC | ASYNC [START (<start_time>)] EVERY (INTERVAL <refresh_interval>) | MANUAL]
]
-- partition_expression
[PARTITION BY
[ <partition_column> [,...] ] | [ <date_function_expr> ]
]
-- order_by_expression
[ORDER BY (<sort_key>)]
[PROPERTIES ("key"="value", ...)]
AS
<query_statement>
Parameters in brackets [] are optional.
Parametersβ
mv_name (required)
The name of the materialized view. The naming requirements are as follows:
- The name must consist of letters (a-z or A-Z), digits (0-9), or underscores (
_), and it can only start with a letter. - The length of the name cannot exceed 64 characters.
- The name is case-sensitive.
CAUTION
Multiple materialized views can be created on the same base table, but the names of the materialized views in the same database cannot be duplicated.
COMMENT (optional)
Comment on the materialized view. Note that COMMENT must be placed after mv_name. Otherwise, the materialized view cannot be created.
distribution_desc (optional)
The bucketing strategy of the asynchronous materialized view. StarRocks supports hash bucketing and random bucketing (from v3.1 onwards). If you do not specify this parameter, StarRocks uses the random bucketing strategy and automatically sets the number of buckets.
NOTE
While creating an asynchronous materialized view, you must specify either
distribution_descorrefresh_scheme, or both.
-
Hash bucketing:
Syntax
DISTRIBUTED BY HASH (<bucket_key1>[,<bucket_key2> ...]) [BUCKETS <bucket_number>]For more information, see Data distribution.
NOTE
Since v2.5.7, StarRocks can automatically set the number of buckets (BUCKETS) when you create a table or add a partition. You no longer need to manually set the number of buckets. For detailed information, see set the number of buckets.
-
Random bucketing:
If you choose the random bucketing strategy and allow StarRocks to set the number of buckets automatically, you do not need to specify
distribution_desc. However, if you want to set the number of buckets manually, you can refer to the following syntax:DISTRIBUTED BY RANDOM BUCKETS <bucket_number>CAUTION
Asynchronous materialized views with a random bucketing strategy cannot be assigned to a colocation group.
For more information, see Random bucketing
refresh_moment (optional)
The refresh moment of the materialized view. Default value: IMMEDIATE. Valid values:
IMMEDIATE: Refresh the asynchronous materialized view immediately after it is created.DEFERRED: The asynchronous materialized view is not refreshed after it is created. You can manually refresh the materialized view or schedule regular refresh tasks.
refresh_scheme (optional)
NOTE
- While creating an asynchronous materialized view, you must specify either
distribution_descorrefresh_scheme, or both.- External table materialized views do not support automatic refresh triggered by base table data changes. They only support asynchronous fixed-interval refresh and manual refresh.
The refresh strategy of the asynchronous materialized view. Valid values:
ASYNC: Automatic refresh mode. Each time the base table data changes, the materialized view is automatically refreshed.ASYNC [START (<start_time>)] EVERY(INTERVAL <interval>): Regular refresh mode. The materialized view is refreshed regularly at the interval defined. You can specify the interval asEVERY (interval n day/hour/minute/second)using the following units:DAY,HOUR,MINUTE, andSECOND. The default value is10 MINUTE. You can further specify the refresh start time asSTART('yyyy-MM-dd hh:mm:ss'). If the start time is not specified, the current time is used. Example:ASYNC START ('2023-09-12 16:30:25') EVERY (INTERVAL 5 MINUTE).MANUAL: Manual refresh mode. The materialized view will not be refreshed unless you trigger a refresh task manually.
If this parameter is not specified, the default value MANUAL is used.
partition_expression (optional)
The partitioning strategy of the asynchronous materialized view. If this parameter is not specified, no partitioning strategy is adopted by default.
Valid values:
partition_column: The column(s) used for partitioning. The expressionPARTITION BY dtmeans to partition the materialized view according to thedtcolumn.date_function_expr: The complex expression with date functions used for partitioning.date_truncfunction: The function used to truncate the time unit.PARTITION BY date_trunc("MONTH", dt)means that thedtcolumn is truncated to month as the unit for partitioning. Thedate_truncfunction supports truncating time to units includingYEAR,MONTH,DAY,HOUR, andMINUTE.str2datefunction: The function used to transform string type partitions of the base table into date types.PARTITION BY str2date(dt, "%Y%m%d")means that thedtcolumn is a STRING date type whose date format is"%Y%m%d". Thestr2datefunction supports a lot of date formats, you can refer to str2date for more information. Supported from v3.1.4.time_slicefunction: From v3.1 onwards, you can further use these functions to convert the given time into the beginning or end of a time interval based on the specified time granularity, for example,PARTITION BY date_trunc("MONTH", time_slice(dt, INTERVAL 7 DAY))where time_slice must have a finer granularity than date_trunc. You can use them to specify a GROUP BY column with a finer granularity than that of the partitioning key, for example,GROUP BY time_slice(dt, INTERVAL 1 MINUTE) PARTITION BY date_trunc('DAY', ts).
From v3.5.0 onwards, asynchronous materialized views support multi-column partition expressions. You can specify multiple partition columns for the materialized view to map all or part of the partition columns of the base tables.
Notes for multi-column partition expressions:
-
Currently, multi-column partitions in materialized views can only be directly mapped to the base table's partition columns. Mapping using functions or expressions on the base table's partition columns is not supported.
-
Because Iceberg partition expressions support the
transformfunction, additional handling is required when mapping Iceberg partition expressions to StarRocks materialized view partition expressions. The mapping relationship is as follows:Iceberg Transform Iceberg partition expression Materialized view partition expression Identity <col><col>hour hour(<col>)date_trunc('hour', <col>)day day(<col>)date_trunc('day', <col>)month month(<col>)date_trunc('month', <col>)year year(<col>)date_trunc('year', <col>)bucket bucket(<col>, <n>)Not supported truncate truncate(<col>)Not supported -
For non-Iceberg partition columns, where partition expression computation is not involved, additional partition expression handling is not required. You can map them directly.
See Example -5 for detailed instructions on multi-column partition expressions.
CAUTION
From v3.3.3 onwards, StarRocks supports creating asynchronous materialized views with the List Partitioning strategy.
- You can create list-partitioned materialized views based on tables that are created with the List Partitioning or Expression partitioning strategy.
- Currently, you can only specify one Partition Key when creating materialized views with the List Partitioning strategy. You must choose one Partition Key if the base table has more than one Partition Key.
- The refresh behavior and query rewrite logic of materialized views with the List Partitioning strategy are consistent with those with the Range Partitioning strategy.
order_by_expression (optional)
The sort key of the asynchronous materialized view. If you do not specify the sort key, StarRocks chooses some of the prefix columns from SELECT columns as the sort keys. For example, in select a, b, c, d, sort keys can be a and b. This parameter is supported from StarRocks v3.0 onwards.
NOTE There are two different uses of
ORDER BYin materialized views:
ORDER BYin the CREATE MATERIALIZED VIEW statement defines the sort key of the materialized view, which helps accelerate queries based on the sort key. This does not affect the materialized view's SPJG-based transparent acceleration capability but does not guarantee global ordering of the materialized view's query results.ORDER BYin the materialized view's query definition guarantees global ordering of the query results, but prevents the materialized view from being used for SPJG-based transparent query rewrite. Therefore,ORDER BYshould not be used in the materialized view's query definition if the MV is used for query rewrite usage.
INDEX (optional)
Asynchronous materialized views support βBitmapβ and βBloomFilterβ indexes to accelerate query performance, and their usage is the same as in regular tables. For details on the use cases and information about βBitmapβ and βBloomFilterβ indexes, please refer toοΌBitmap Index and Bloom filter Index.
Using Bitmap Indexes:
-- Create an index
CREATE INDEX <index_name> ON <mv_name>(<column_name>) USING BITMAP COMMENT '<comment>';
-- Check index creation progress
SHOW ALTER TABLE COLUMN;
-- View indexes
SHOW INDEXES FROM <mv_name>;
-- Drop an index
DROP INDEX <index_name> ON <mv_name>;
Using BloomFilter Indexes:
-- Create an index
ALTER MATERIALIZED VIEW <mv_name> SET ("bloom_filter_columns" = "<col1,col2,col3,...>");
-- View indexes
SHOW CREATE MATERIALIZED VIEW <mv_name>;
-- Drop an index
ALTER MATERIALIZED VIEW <mv_name> SET ("bloom_filter_columns" = "");