CAUTIONCreating 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
- 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, the database supports creating synchronous materialized views in shared-data clusters.
tasks and task_runs in Information Schema.
The database supports asynchronous materialized views from v2.4. The major differences between asynchronous materialized views and synchronous materialized views in previous versions are as follows:
Synchronous materialized view
Syntax
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 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_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, the database 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
On shared-data range tables
You can use ordinaryCREATE MATERIALIZED VIEW ... AS SELECT on eligible shared-data tables with range distribution. Omit DISTRIBUTED BY when creating the range base table. The following view groups by store_id, although the base table is sorted by id; the filter column does not need to appear in the view’s output.
ORDER BY. Historical data is built online, and subsequent INSERT and load operations maintain the view synchronously. Base-table and view tablets support splitting and merging through ALTER TABLE ... SPLIT TABLETS and ALTER TABLE ... MERGE TABLETS. To target a view’s layout, use its tablet IDs. Merge eligibility still requires source tablets to be free of shared files; compaction can remove files shared by a split. Wait for the creation job to reach FINISHED before creating another sibling view or rollup.
The existing single-table, expression and base-table model restrictions still apply. Range synchronous views do not support shared-nothing clusters or Primary Key base tables. On a base table with an AUTO_INCREMENT column, a view column cannot be computed from that column; selecting the column itself or filtering on it in WHERE is supported. Each logical partition must have exactly one physical partition during creation; multiple logical partitions are supported. Complete a coordinated upgrade of all FEs before creating these views: older FEs cannot safely reconstruct their range-view metadata. Upgrade all CNs before splitting or merging tablets of these views.
On a base table with colocate_with, the view’s sort key must start with the colocated columns, in the same order and with the same types. The sort key of a synchronous materialized view is its leading non-aggregated columns, in SELECT order. For a view without GROUP BY, aggregation, or DISTINCT, the sort key is a prefix of the SELECT list (at most three columns and 36 bytes; it ends with the first VARCHAR column, or before the first column whose type cannot be a key, such as FLOAT or DOUBLE), and ORDER BY does not change it. To choose the sort key of such a projection, use ALTER TABLE ... ADD ROLLUP ... ORDER BY (...) instead.
Range synchronous views reject expressions whose generated MV column name conflicts with a real base-table column. For example, SUM(v) cannot be used if the base table already contains mv_sum_v. Rename the conflicting base column or use a different expression alias where applicable. Directly selecting a real base-table column whose name starts with mv_ is supported.
A schema change or column rename is rejected if it would leave a surviving MV expression or WHERE clause unresolved or change its stored aggregate-state signature, including removing a referenced struct field. Adding fields and removing unreferenced fields remain supported. Drop the affected view first. Dropping a column only from a named view does not drop its base-table source.
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_]:
CAUTION Currently, the database 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.
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.
Asynchronous materialized view
Syntax
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 distribution strategy of the asynchronous materialized view. The database supports hash bucketing and random bucketing (from v3.1 onwards). In shared-data mode, if enable_range_distribution and enable_mv_range_distribution are both enabled, omitting this parameter selects range distribution. Otherwise, a materialized view whose refresh_mode is not INCREMENTAL uses random bucketing, and the database automatically sets the number of buckets. Materialized views whose refresh_mode is INCREMENTAL follow different distribution rules. For details, see Incremental Materialized View.
NOTE While creating an asynchronous materialized view, you must specify eitherdistribution_descorrefresh_scheme, or both.
-
Hash bucketing:
Syntax
For more information, see Data distribution.
NOTE Since v2.5.7, the database 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 the database 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:CAUTION Asynchronous materialized views with a random bucketing strategy cannot be assigned to a colocation group.
For more information, see Random bucketing
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.
NOTEThe refresh strategy of the asynchronous materialized view. Valid values:
- 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.
ASYNC: Automatic refresh mode. Each time the base table data changes, the materialized view is automatically refreshed. This mode applies only to materialized views whose base tables are all internal tables or materialized views. Creating anASYNCmaterialized view on external tables without a refresh interval fails.SCHEDULE [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:SCHEDULE START ('2023-09-12 16:30:25') EVERY (INTERVAL 5 MINUTE). The legacy formASYNC [START (...)] EVERY (...)is still accepted for backward compatibility butSHOW CREATE MATERIALIZED VIEWalways renders the scheduled form withSCHEDULE.MANUAL: Manual refresh mode. The materialized view will not be refreshed unless you trigger a refresh task manually.
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,WEEK,DAY,HOUR, andMINUTE.WEEKis supported from v3.3.1 onwards.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,time_slice(dt, INTERVAL 7 DAY) AS mv_dtin the SELECT list withPARTITION BY date_trunc("MONTH", mv_dt), where time_slice must have a finer granularity than date_trunc. Thetime_slicefunction cannot be nested indate_truncwithin the PARTITION BY clause, because the second argument ofdate_truncthere must be a column. 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).
- 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 the database materialized view partition expressions. The mapping relationship is as follows: - For non-Iceberg partition columns, where partition expression computation is not involved, additional partition expression handling is not required. You can map them directly.
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 ofINDEX (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: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.
PROPERTIES (optional)
Properties of the asynchronous materialized view. You can modify the properties of an existing materialized view using ALTER MATERIALIZED VIEW.-
session.: If you want to alter a session variable-related property of the materialized view, you must add asession.prefix to the property, for example,session.insert_timeout. You do not need to specify the prefix for non-session properties, for example,mv_rewrite_staleness_second. -
replication_num: The number of materialized view replicas to create. -
storage_medium: Storage medium type. Valid values:HDDandSSD. -
storage_cooldown_time: the storage cooldown time for a partition. If both HDD and SSD storage mediums are used, data in the SSD storage is moved to the HDD storage after the time specified by this property. Format: “yyyy-MM-dd HH:mm:ss”. The specified time must be later than the current time. If this property is not explicitly specified, the storage cooldown is not performed by default. -
bloom_filter_columns: An array of column names that enable Bloom filter indexing. For details about Bloom filter indexes, see Bloom filter Index. -
partition_ttl: The time-to-live (TTL) for partitions. Partitions whose data is within the specified time range are retained. Expired partitions are deleted automatically. Unit:YEAR,MONTH,DAY,HOUR, andMINUTE. For example, you can specify this property as2 MONTH. This property is recommended overpartition_ttl_number. It is supported from v3.1.5 onwards. -
partition_ttl_number: The number of most recent materialized view partitions to retain. For the partitions with a start time earlier than the current time, after the number of these partitions exceeds this value, less recent partitions will be deleted. The database will periodically check materialized view partitions according to the time interval specified in the FE configuration itemdynamic_partition_check_interval_seconds, and automatically delete expired partitions. If you enabled the dynamic partitioning strategy, the partitions created in advance are not counted in. When the value is-1, all partitions of the materialized view will be preserved. Default:-1. -
partition_refresh_number: In a single refresh, the maximum number of partitions to refresh. If the number of partitions to be refreshed exceeds this value, the database will split the refresh task and complete it in batches. Only when the previous batch of partitions is refreshed successfully, the database will continue to refresh the next batch of partitions until all partitions are refreshed. If any of the partitions fail to be refreshed, no subsequent refresh tasks will be generated. When the value is-1, the refresh task will not be split. The default value is changed from-1to1since v3.3, meaning the database refeshes partitions one by one. -
partition_refresh_strategy:The refresh strategy for a materialized view during a single refresh operation. When set toadaptive, the number of partitions to refresh will be automatically determined based on the data volume in the base table partitions, significantly improving refresh efficiency. When set tostrict, the number of partitions refreshed in a single operation is strictly controlled bypartition_refresh_number. If this property is not specified, the value of the FE configuration itemdefault_mv_partition_refresh_strategyis used, which isadaptivefrom v4.1 onwards andstrictin earlier versions. Setting it toforcerefreshes every partition on each refresh; it has no effect on a materialized view whoserefresh_modeisINCREMENTAL, which is maintained from base table changes by definition. -
excluded_trigger_tables: If a base table of the materialized view is listed here, the automatic refresh task will not be triggered when the data in the base table is changed. This parameter only applies to load-triggered refresh strategy, and is usually used together with the propertyauto_refresh_partitions_limit. Format:[db_name.]table_name. When the value is an empty string, any data change in all base tables triggers the refresh of the corresponding materialized view. The default value is an empty string. -
excluded_refresh_tables: The base tables listed in this property will not be updated to the materialized view when their data changes. Format:[db_name.]table_name. The default value is an empty string. When the value is an empty string, any base table data change will trigger the corresponding materialized view refresh. Tip The difference betweenexcluded_trigger_tablesandexcluded_refresh_tablesis:excluded_trigger_tablescontrols whether to trigger a refresh, not whether to participate in the refresh. For example, a partitioned materialized view is obtained by joining two partitioned tables A and B, and the partitions of the two tables A and B correspond one to one.excluded_trigger_tablecontains table A. During a period of time, table A updated partitions[1,2,3], but because it is anexcluded_trigger_table, the refresh of the materialized view is not triggered. At this time, table B updates partition[3], and the materialized view triggers a refresh, which will refresh the three partitions[1, 2, 3]. Here you can see thatexcluded_trigger_tableonly controls whether to trigger a refresh. Although the update of table A cannot trigger a materialized view refresh, when the update of table B triggers a materialized view refresh, the partition updated by table A will also be added to the refresh task.excluded_refresh_tablescontrols whether to participate in the refresh. In the above example, if table A exists in bothexcluded_trigger_tableandexcluded_refresh_tables, when the update of table B triggers a materialized view refresh, only partition[3]will be refreshed.
-
auto_refresh_partitions_limit: The number of most recent materialized view partitions that need to be refreshed when a materialized view refresh is triggered. You can use this property to limit the refresh range and reduce the refresh cost. However, because not all the partitions are refreshed, the data in the materialized view may not be consistent with the base table. Default:-1. When the value is-1, all partitions will be refreshed. When the value is a positive integer N, the database sorts the existing partitions in chronological order, and refreshes the current partition and N-1 most recent partitions. If the number of partitions is less than N, the database refreshes all existing partitions. If there are dynamic partitions created in advance in your materialized view, the database refreshes all pre-created partitions. This property is not supported on a materialized view whoserefresh_modeisINCREMENTAL, because incremental maintenance requires a complete baseline. To batch the initial full refresh of such a view, usepartition_refresh_numberinstead; refreshes after that process only the base table changes and are not affected by either property. -
mv_rewrite_staleness_second: This materialized view can be used directly for query rewrite, regardless of whether the base table data has changed, as long as the gap between the latest base-table modification time and the materialized view’s last confirmed complete refresh does not exceed the time interval specified in this property. Because the comparison is against the latest base-table modification time (not the current wall-clock time), a materialized view whose base tables have not changed since its last complete refresh stays usable for query rewrite no matter how much time passes. Otherwise, the database checks whether the base tables have been updated to determine whether the materialized view can be used for query rewrite. Note that a refresh covering only part of the partitions (for example, a manualREFRESH ... PARTITION START ... END, or a refresh limited byauto_refresh_partitions_limit) does not renew this freshness baseline. Unit: Second. This property is supported from v3.0. -
colocate_with: The colocation group of the asynchronous materialized view. See Colocate Join for further information. This property is supported from v3.0. -
unique_constraintsandforeign_key_constraints: The Unique Key constraints and Foreign Key constraints when you create an asynchronous materialized view for query rewrite in the View Delta Join scenario. See Asynchronous materialized view - Rewrite queries in View Delta Join scenario for further information. This property is supported from v3.0. -
excluded_refresh_tables:The base tables listed in this property will not trigger data refresh to the materialized view when their data changes. This property is usually used together with theexcluded_trigger_tablesproperty. Format:[db_name.]table_name. The default value is an empty string. When the value is an empty string, any data change in all base tables will trigger the corresponding materialized view refresh.CAUTION The Unique Key constraints and Foreign Key constraints are only used for query rewrite. The Foreign Key constraint checks are not guaranteed when data is loaded into the table. You must ensure the data loaded into the table meets the constraints.
-
resource_group: The resource group to which the refresh tasks of the materialized view belong. The default value of this property isdefault_mv_wg, which is a system-defined resource group specifically used for materialized view refresh. Thecpu_core_limitofdefault_mv_wgis1,mem_limitis0.8. For more about resource groups, see Resource group. -
query_rewrite_consistency: The query rewrite rule for the asynchronous materialized views. This property is supported from v3.2. Valid values:-
disable: Disable automatic query rewrite of the asynchronous materialized view. -
checked(Default value): Enable automatic query rewrite only when the materialized view meets the timeliness requirement, which means:- If
mv_rewrite_staleness_secondis not specified, the materialized view can be used for query rewrite only when its data is consistent with the data in all base tables. - If
mv_rewrite_staleness_secondis specified, the materialized view can be used for query rewrite when its last confirmed complete refresh is within the staleness time interval.
- If
-
loose: Enable automatic query rewrite directly, and no consistency check is required. -
force_mv: From v3.5.0 onwards, the database materialized views support Common Partition Expression TTL. Theforce_mvsemantic is specifically designed for this scenario. When this semantic is enabled:- If the materialized view does not have the
partition_retention_conditionproperty, it will always force the use of the materialized view for query rewrite, regardless of whether the base table has been updated. - If the materialized view has the
partition_retention_conditionproperty:- For partitions within the TTL range, query rewrite based on the materialized view is always available, regardless of whether the base table has been updated.
- For partitions outside the TTL range, a Union compensation between the materialized view and the base table is required, regardless of whether the base table has been updated.
partition_retention_conditionproperty defined and the partition for20241131has expired, but the base table data for20241203has been updated while the materialized view data for20241203has not been refreshed, the following applies when thequery_rewrite_consistencyproperty is set toforce_mv:- The materialized view guarantees that queries against the partitions within the TTL range (for example, from
20241201to20241203) defined inpartition_retention_conditioncan always be transparently rewritten. - For queries against partitions outside the
partition_retention_conditionrange, compensation will occur automatically based on the Union of the materialized view and the base table.
force_mvsemantic andpartition_retention_condition. - If the materialized view does not have the
-
-
storage_volume: The name of the storage volume used to store the asynchronous materialized view you want to create if you are using a shared-data cluster. This property is supported from v3.1 onwards. If this property is not specified, the storage volume of the database is used; if the database has no storage volume, the default storage volume is used. Example:"storage_volume" = "def_volume". -
file_bundling: Whether to enable the File Bundling optimization for the asynchronous materialized view. This property is supported only for shared-data clusters, from v4.2.1 onwards. If this property is not specified, the FE configurationenable_file_bundling(Default:true) decides. Existing materialized views keep File Bundling disabled after the upgrade. You can change this property with ALTER MATERIALIZED VIEW. For what File Bundling does and the restrictions on changing it, see thefile_bundlingproperty in CREATE TABLE. -
force_external_table_query_rewrite: Whether to enable query rewrite for external catalog-based materialized views. This property is supported from v3.2. Valid values:true(Default value since v3.2): Enable query rewrite for external catalog-based materialized views.false: Disable query rewrite for external catalog-based materialized views.
falseby default in versions earlier than v3.2. When this feature is enabled, the materialized view is used for query rewrite in accordance with the rule specified inquery_rewrite_consistency. -
enable_query_rewrite: Whether to use the materialized view for query rewrite. When there are many materialized views, query rewrite based on materialized views can impact the optimizer’s time consumption. With this property, you can control whether the materialized view can be used for query rewrite. This feature is supported from v3.3.0 onwards. Valid values:default(Default): The system will not perform semantic checks on the materialized view, but only the SPJG-type materialized views can be used for query rewrite. Note that if the text-based query rewrite is enabled, non-SPJG-type materialized views can also be used for query rewrite.true: The system will perform semantic checks when creating or modifying the materialized view. If the materialized view is not eligible for query rewrite (that is, the definition of the materialized view is not an SPJG-type query), a failure will be returned.false: The materialized view will not be used for query rewrite.
-
[Preview]
transparent_mv_rewrite_mode: Specifies the transparent rewrite mode for queries directly against the materialized view. This feature is supported from v3.3.0 onwards. Valid values:false(Default, compatible with the behavior in earlier versions): Queries directly against the materialized view will not be rewritten, and are only returned with the existing data in the materialized view. Their query results may be different from those of queries based on the definition of the materialized view according to the refresh status (data consistency) of the materialized view.true: Queries directly against the materialized view will be rewritten and returned with the most updated data, which is consistent with the result of the materialized view definition query. Please note that when the materialized view is inactive or does not support transparent query rewrite, these queries will be executed as the materialized view definition query.transparent_or_error: Queries directly against the materialized view will be rewritten whenever they are eligible. If the materialized view is inactive or does not support transparent query rewrite, these queries will be returned with an error.transparent_or_defaultQueries directly against the materialized view will be rewritten whenever they are eligible. If the materialized view is inactive or does not support transparent query rewrite, these queries will be returned with the existing data in the materialized view.
-
partition_retention_condition: From v3.5.0 onwards, the database materialized views support Common Partition Expression TTL. This property is the expression that declares the partitions to be retained dynamically. Partitions that do not meet the condition in the expression will be dropped regularly. Example:'partition_retention_condition' = 'dt >= CURRENT_DATE() - INTERVAL 3 MONTH'.- The expression can only contain partition columns and constants. Non-partition columns are not supported.
- Common Partition Expression applies to List partitions and Range partitions differently:
- For materialized views with List partitions, StarRocks supports deleting partitions filtered by the Common Partition Expression.
- For materialized views with Range partitions, StarRocks can only filter and delete partitions using the partition pruning capability of FE. Partitions correspond to predicates that are not supported by partition pruning cannot be filtered and deleted.
force_mvsemantic andpartition_retention_condition. -
refresh_mode: Controls how a materialized view is refreshed. See Incremental refresh support by base table for eligible inputs in 4.2. Valid values:PCT: (Default) For partitioned materialized views, only the affected partition is refreshed when there is a data change, ensuring result consistency for that partition. For non-partitioned materialized views, any data change in the base table triggers a full refresh of the materialized view.INCREMENTAL: Ensures that only incremental refreshes are performed. If the materialized view does not support incremental refresh based on its definition or encounters non-incremental data, creation or refresh will fail.
Query an asynchronous materialized view
An asynchronous materialized view is a physical table. You can operate it as any regular table except that you cannot directly load data into an asynchronous materialized view.Automatic query rewrite with asynchronous materialized view
StarRocks v2.5 supports automatic and transparent query rewrite based on the SPJG-type asynchronous materialized views. The SPJG-type materialized views refer to materialized views whose plan only includes Scan, Filter, Project, and Aggregate types of operators. The SPJG-type materialized views query rewrite includes single table query rewrite, Join query rewrite, aggregation query rewrite, Union query rewrite and query rewrite based on nested materialized views. See Asynchronous materialized view - Rewrite queries with the asynchronous materialized view for further information.Supported data types
-
Asynchronous materialized views created based on the database default catalog support the following data types:
- Date: DATE, DATETIME
- String: CHAR, VARCHAR
- Numeric: BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, LARGEINT, FLOAT, DOUBLE, DECIMAL, PERCENTILE
- Semi-structured: ARRAY, JSON, MAP (from v3.1 onwards), STRUCT (from v3.1 onwards)
- Other: BITMAP, HLL
NOTE BITMAP, HLL, and PERCENTILE have been supported since v2.4.5.
-
Asynchronous materialized views created based on the database external catalogs support the following data types:
-
Hive Catalog
- Numeric: INT/INTEGER, BIGINT, DOUBLE, FLOAT, DECIMAL
- Date: TIMESTAMP
- String: STRING, VARCHAR, CHAR
- Semi-structured: ARRAY
-
Hudi Catalog
- Numeric: BOOLEAN, INT, LONG, FLOAT, DOUBLE, DECIMAL
- Date: DATE, TimeMillis/TimeMicros, TimestampMillis/TimestampMicros
- String: STRING
- Semi-structured: ARRAY
-
Iceberg Catalog
- Numeric: BOOLEAN, INT, LONG, FLOAT, DOUBLE, DECIMAL(P, S)
- Date: DATE, TIME, TIMESTAMP
- String: STRING, UUID, FIXED(L), BINARY
- Semi-structured: LIST
-
Hive Catalog
Incremental Materialized View
StarRocks v4.1 introduced therefresh_mode parameter to control the refresh behavior of materialized views. You can specify refresh_mode when creating each materialized view. If refresh_mode is not set during materialized view creation, the system uses the default value PCT, governed by the default_mv_refresh_mode parameter (Default: pct, valid values: pct, incremental). Please note the following usage guidance:
-
AUTOmode: If the materialized view definition supports incremental maintenance, incremental refresh is attempted first. If planning determines that a particular round of data changes cannot be processed incrementally, that round automatically falls back to PCT. Once processing completes, the baseline advances, and subsequent rounds continue to attempt incremental refresh. If CREATE analysis determines that the definition does not support incremental maintenance, PCT partition refresh is used instead. - At creation, AUTO attempts full incremental analysis and trial compilation of the refresh plan. On a semantic error, it restores the original definition and analyzes it again as PCT. If PCT analysis also fails, CREATE reports the error.
-
Materialized views with
refresh_modeset toINCREMENTALdo not support specifying partition refresh. An exception is thrown if you attempt a partition refresh.
Distribution
Materialized views whoserefresh_mode is INCREMENTAL follow these distribution rules:
- If you omit
distribution_desc, the database uses range distribution only in shared-data mode whenenable_range_distributionandenable_mv_range_distributionare both enabled. In all other cases, the database falls back to hash distribution over all target key columns. - Range distribution has no user-facing
DISTRIBUTED BY RANGEsyntax and cannot be specified explicitly. - If you explicitly specify hash or random distribution, the database normalizes it to hash distribution over all target key columns. An explicitly specified bucket count is preserved.
- A range-distributed partition starts with a single tablet, and so does the replacement partition an overwrite refresh writes into, so such a refresh would otherwise be written by one node. The database therefore pre-splits the tablets that refresh writes into, deriving the boundaries from the internal row-id column instead of sampling any data. This applies in two cases. When the view’s row ids are fingerprints computed by the refresh query, the partitions the refresh overwrites share the estimated output equally, and up to
tablet_pre_split_max_partitions_per_loadof them are pre-split if the estimate calls for more tablets than there are partitions. When the row ids are generated by the storage engine, only a refresh that overwrites a single partition is pre-split, for example the first refresh of a newly created view. It is best-effort: any other case is refreshed without pre-splitting and the reason is recorded understarrocks_fe_tablet_pre_split_eligibility_skipped. Setenable_tablet_pre_split_for_mv_refreshtofalseto turn it off.
Sort Key
A materialized view whoserefresh_mode is INCREMENTAL is a Primary Key table keyed by an internal row-id column, so ORDER BY defines a sort key of its own instead of becoming part of the primary key.
- On a hash- or random-distributed materialized view, the sort key is the
ORDER BYcolumns. - On a range-distributed materialized view,
ORDER BYis not supported: the sort key defines the tablet boundaries and must equal the primary key, which is a column you cannot name. AddDISTRIBUTED BY HASH(...)if you need a sort key. - If you omit
ORDER BY, the materialized view is sorted by its primary key.
Incremental refresh support by base table
In 4.2.0, the first refresh of an incremental materialized view establishes a full baseline. Subsequent refreshes process the changes supported for each base table.- Shared-data Primary Key tables support inserts, updates and deletes when
enable_change_data_captureis enabled on every base table before the view is created. A multi-table view using this capability requires all inputs to be CDC-enabled shared-data Primary Key tables. Eligible definitions include projections, filters, grouped aggregates, inner and cross joins,UNION ALL, and derived tables. - Shared-data Duplicate Key tables support incremental refresh for appended rows.
- Shared-data Aggregate Key tables require the view to group by all or a subset of the base aggregation keys and to use compatible aggregate functions, such as
SUMover aSUMcolumn. - Iceberg tables support incremental refresh for appends. A change that rewrites or removes existing data, for example an overwrite, causes a refresh in
INCREMENTALmode to fail. - Paimon tables do not support
INCREMENTALrefresh.
Supported Incremental Operators
The following operator restrictions apply to append-only Iceberg base tables.
Note
While operators listed above generally support incremental refresh, certain operator combinations currently have limitations:
- Incremental computation is supported for aggregation after Join and aggregation after UNION.
- However, incremental computation is not supported when performing Join after aggregation or UNION ALL after aggregation.
Usage notes
- The current version of the database does not support creating multiple materialized views at the same time. A new materialized view can only be created when the one before is completed.
-
About synchronous materialized views:
- Synchronous materialized views only support aggregate functions on a single column. Query statements in the form of
sum(a+b)are not supported. - Synchronous materialized views support only one aggregate function for each column of the base table. Query statements such as
select sum(a), min(a) from tableare not supported. - 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.
- Synchronous materialized views do not support clauses such as JOIN, and the HAVING clause of GROUP BY.
- When using ALTER TABLE DROP COLUMN to drop a specific column in a base table, you must ensure that all synchronous materialized views of the base table do not contain the dropped column, otherwise, the drop operation will fail. Before you drop the column, you must first drop all synchronous materialized views that contain the column.
- Creating too many synchronous materialized views for a table will affect the data load efficiency. When data is being loaded to the base table, the data in the synchronous materialized view and the base table will be updated synchronously. If a base table contains
nsynchronous materialized views, the efficiency of loading data into the base table is about the same as the efficiency of loading data intontables.
- Synchronous materialized views only support aggregate functions on a single column. Query statements in the form of
-
About nested asynchronous materialized views:
- The refresh strategy for each materialized view only applies to the corresponding materialized view.
- Currently, the database does not limit the number of nesting levels. In a production environment, we recommend that the number of nesting layers not exceed THREE.
-
About external catalog asynchronous materialized views:
- External catalog materialized view only support asynchronous fixed-interval refresh and manual refresh.
- Strict consistency is not guaranteed between the materialized view and the base tables in the external catalog.
- Currently, building materialized views based on external resources is not supported.
- Currently, the database cannot perceive if the base table data in the external catalog has changed, so all partitions will be refreshed by default every time the base table is refreshed. You can manually refresh only some of partitions using REFRESH MATERIALIZED VIEW.
Examples
Examples of synchronous materialized views
The schema of the base table is as follows:Text
text
text
text
text
text
text
key field of the k3, k4, and k5 columns is true, which indicates that they are the sort keys. The key field of the k6, and k7 columns is false, which indicates that they are not the sort keys.
Example 6: Create a synchronous materialized view that contains the WHERE clause and complex expressions.
Examples of asynchronous materialized views
The following examples are based on the base tables below:str2date to transform the STRING type partition key of the base table into the date type as for the materialized view.
force_mv semantic for query rewrite.
refreshMode field has been added to the EXTRA_MESSAGE column in information_schema.task_runs to indicate the refresh mode of the TaskRun. For more details, see materialized_view_task_run_details.